服务的最佳实践--完整版的下载示例

这里主要是《Android第一行代码》第二版书中10.6碰到的问题和解决方法,记录下来希望能帮到大家,也希望大家有更好的解决方案能一起交流.。

Android Studio版本如下:

这里我先列出按照书上代码运行会出现的错误:

(1)、java.net.UnknownServiceException: CLEARTEXT communication to raw.githubusercontent.com not permitted by network security policy

(2)、java.lang.SecurityException: Permission Denial: startForeground from pid=9733, uid=10085 requires android.permission.FOREGROUND_SERVICE

(3)、java.io.IOException: unexpected end of stream on http://raw.githubusercontent.com/...

当然还有一个缺少Channel的错误,那个错误比较简单,在后面的代码中会有修改的方法,这里就不赘述了。

现在主要来看看上面三个错误

(1)、第一个错误主要是使用Http进行网络访问的错误,这个有三种解决方法,有兴趣的可以翻看我写的前面一篇博客,这里我只给出解决方法,在AndroidManifest.xml中添加如下:

<application

    ......

    android:usesCleartextTraffic="true"

    ......

</application>


(2)、这个主要Android 9.0版本出现的问题,使用前台服务时需要申请权限,在AndroidManifest.xml中添加如下:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

(3)、这个问题就很隐蔽了,我查找了很多资料才找到的解决方案,在app/build.gradle的android闭包中添加如下:

compileOptions{
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8

        }

      这段代码是为了开启Java1.8,能够使用Lambda,因为 stream API 和接口默认实现等特性都只支持Android 7.0及以上的系统,而Lambda表达式能最低兼容到Android 2.3系统,基本上覆盖了所有的Android手机了。

没添加这段代码程序可以正常安装,但是启动下载的时候就会出现问题,这里我放两张图片

下面我们来结合书中的代码完整写一下这个项目 

1、添加依赖包

编辑app/build.gradle文件,在dependencies闭包中添加如下:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
    implementation 'com.squareup.okhttp3:okhttp:3.14.2'
}

 这里添加红色字体就行。

这里要注意compile已经全部被implementation替代了,由于之前的项目统一用compile依赖,导致的情况就是模块耦合性太高,不利于项目拆解,使用implementation之后虽然使用起来复杂了但是做到降低偶合兴提高安全性不失为一个好办法。

2、定义回调接口

定义一个回调接口,用于对下载过程中的各种状态进行监听和回调,代码如下:

//定义一个回调接口,用于对下载过程中的各种状态进行监听和回调
public interface DownloadListener {
    void onProgress(int progress);        //用于通知当前下载进度

    void onSuccess();                     //用于通知下载成功事件

    void onFailed();                      //用于通知下载失败事件

    void onPaused();                      //用于通知下载成功事件

    void onCanceled();                    //用于通知下载取消事件
}

3、编写下载任务

使用AsyncTask来进行实现。代码如下:

import android.os.AsyncTask;
import android.os.Environment;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;




public class DownloadTask extends AsyncTask<String,Integer,Integer> {

    public static final int TYPE_SUCCESS=0;
    public static final int TYPE_FAILED=1;
    public static final int TYPE_PAUSED=2;
    public static final int TYPE_CANCELED=3;

    private DownloadListener listener;

    private boolean isCanceled=false;

    private boolean isPaused=false;

    private int lastProgress;

    public DownloadTask(DownloadListener listener){
        this.listener=listener;
    }

    @Override
    protected Integer doInBackground(String... params) {
        InputStream is=null;
        RandomAccessFile savedFile=null;
        File file=null;
        try{
            long downloadedLength=0;                                   //记录已下载的文件长度
            String downloadURL=params[0];
            String fileName=downloadURL.substring(downloadURL.lastIndexOf("/"));
            String directory= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
            file=new File(directory+fileName);
            if(file.exists()){
                downloadedLength=file.length();
            }
            long contentLength=getContentLength(downloadURL);
            if(contentLength==0){
                return TYPE_FAILED;
            }else if(contentLength==downloadedLength){
                //已下载字节和文件总字节相等,证明下载完成
                return TYPE_SUCCESS;
            }
            OkHttpClient client=new OkHttpClient();
            Request request=new Request.Builder()                                        //断点下载,制定从哪个字节开始下载
                    .addHeader("RANGE","bytes="+downloadedLength+"-")
                    .url(downloadURL)
                    .build();
            Response response=client.newCall(request).execute();
            if(request!=null){
                is=response.body().byteStream();
                savedFile=new RandomAccessFile(file,"rw");
                savedFile.seek(downloadedLength);                       //跳过已下载的字节
                byte[] b=new byte[1024];
                int total=0;
                int len;
                while((len=is.read(b))!=-1){
                    if(isCanceled){
                        return TYPE_CANCELED;
                    }else if(isPaused){
                        return TYPE_PAUSED;
                    }else{
                        total+=len;
                        savedFile.write(b,0,len);

                        //计算下载的百分比
                        int progress=(int)((total+downloadedLength)*100/contentLength);
                        publishProgress(progress);
                    }
                }
                response.body().close();
                return TYPE_SUCCESS;
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                if(is!=null){
                    is.close();
                }
                if(savedFile!=null){
                    savedFile.close();
                }
                if(isCanceled&&file!=null){
                    file.delete();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return TYPE_FAILED;
    }

    @Override
    protected void onProgressUpdate(Integer... values){
        int progress=values[0];
        if(progress>lastProgress){
            listener.onProgress(progress);
            lastProgress=progress;
        }
    }

    @Override
    protected void onPostExecute(Integer status){
        switch(status){
            case TYPE_SUCCESS:
                listener.onSuccess();
                break;

            case TYPE_FAILED:
                listener.onFailed();
                break;

            case TYPE_PAUSED:
                listener.onPaused();
                break;

            case TYPE_CANCELED:
                listener.onCanceled();
                break;

                default:
                    break;

        }
    }

    public void pauseDownload(){
        isPaused=true;
    }

    public void cancelDownload(){
        isCanceled=true;
    }


    private long getContentLength(String downloadUrl) throws IOException {
        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder()
                .url(downloadUrl)
                .build();
        Response response=client.newCall(request).execute();
        if(response!=null&&response.isSuccessful()){
            long contentLength=response.body().contentLength();
            response.body().close();
            return contentLength;
        }
        return 0;
    }
}

这部分按照书中的代码即可。

4、创建下载服务

为了保证DownloadTask可以一直在后台运行,创建下载服务,代码如下:

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;

import java.io.File;

import androidx.core.app.NotificationCompat;

//为了保证DownloadTask可以一直在后台运行
public class DownloadService extends Service {

    private DownloadTask downloadTask;
    private String downloadUrl;

    private DownloadListener listener=new DownloadListener() {
        @Override
        public void onProgress(int progress) {
            //构建显示下载进度的通知,并触发通知
            getNotificationManager().notify(1, getNotification("Downloading ...",progress));
        }

        @Override
        public void onSuccess() {
            downloadTask=null;
            //下载成功将前台服务关闭,并创建一个下载成功的通知
            stopForeground(true);
            getNotificationManager().notify(1,getNotification("Download Success",-1));
            Toast.makeText(DownloadService.this,"Download Success",Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onFailed() {
            downloadTask=null;
            //下载失败将前台服务关闭,并创建一个下载失败的通知
            stopForeground(true);
            getNotificationManager().notify(1,getNotification("Download Failed",-1));
            Toast.makeText(DownloadService.this,"Download Failed",Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onPaused() {
            downloadTask=null;

            Toast.makeText(DownloadService.this,"Download Pause",Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onCanceled() {
            downloadTask=null;
            stopForeground(true);
            Toast.makeText(DownloadService.this,"Download Canceled",Toast.LENGTH_SHORT).show();

        }
    };

    private DownloadBinder mBinder=new DownloadBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    class DownloadBinder extends Binder {
        public void startDownload(String url){
            if(downloadTask==null){
                downloadUrl=url;
                downloadTask=new DownloadTask(listener);
                downloadTask.execute(downloadUrl);
                startForeground(1,getNotification("Downloading...",0));
                Toast.makeText(DownloadService.this,"Downloading...",Toast.LENGTH_SHORT).show();
            }
        }

        public void pauseDownload(){
            if(downloadTask!=null){
                downloadTask.pauseDownload();
            }
        }

        public void cancelDownload(){
            if(downloadTask!=null){
                downloadTask.cancelDownload();
            }
            if(downloadUrl!=null){
                //取消下载时需将已下载文件删除,并将通知关闭
                String filename=downloadUrl.substring(downloadUrl.lastIndexOf("/"));
                String directory= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
                File file=new File(directory+filename);
                if(file.exists()){
                    file.delete();
                }
                getNotificationManager().cancel(1);
                stopForeground(true);
                Toast.makeText(DownloadService.this,"Canceled",Toast.LENGTH_SHORT).show();
            }
        }
    }

    //获取NotificationManager实例
    private NotificationManager getNotificationManager(){
        return (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    }

    //显示下载进度
    private Notification getNotification(String title,int progress){
        Intent intent=new Intent(this,MainActivity.class);
        PendingIntent pi=PendingIntent.getActivity(this,0,intent,0);

        NotificationManager manager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel=null;
        Uri uri= Settings.System.DEFAULT_NOTIFICATION_URI;

        //Android8.0之后的版本要求设置通知渠道
        if(android.os.Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
            channel=new NotificationChannel("Notification","This is 2",NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription("This is 1");
            channel.setSound(uri,Notification.AUDIO_ATTRIBUTES_DEFAULT);
            manager.createNotificationChannel(channel);

        }


        NotificationCompat.Builder builder=new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),
                R.mipmap.ic_launcher));
        builder.setWhen(System.currentTimeMillis());
        builder.setContentIntent(pi);
        builder.setContentTitle(title);
        builder.setChannelId("Notification");
        builder.setAutoCancel(true);
        if(progress>=0){
            //当progress大于或等于0时才显示下载进度
            builder.setContentText(progress+"%");
            builder.setProgress(100,progress,false);
        }
        return builder.build();
    }
}

这里将需要修改的代码用红色标出了,这部分和书上的代码有区别主要原因是在Android 8(API 26)之后引入了Channel,所有的Notification都要指定Channel(通道),对于每一个Channel你都可以单独去设置它;比如通知开关、提示音、是否震动或者是重要程度等;这样每个应用程序的通知在用户面前都是透明的。

这里就不详细讲了,这里我找了一个总结的比较精简的,有兴趣的可以参考:https://www.jianshu.com/p/b529e61d220a

5、编写前端代码

修改activity_main.xml中的代码,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button
            android:id="@+id/start_download"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Start Download"
            android:textAllCaps="false"/>

        <Button
            android:id="@+id/pause_download"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Pause download"
            android:textAllCaps="false" />

        <Button
            android:id="@+id/cancel_download"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Cancel download"
            android:textAllCaps="false" />

    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

这里我为了省功夫直接将LinearLayout嵌套在Constranintlayout里使用了,对界面没有影响,和书中代码是一样的,最后我们来修改MainActivity中的代码,代码如下:

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String TAG = "MainActivity";
    private DownloadService.DownloadBinder downloadBinder;

    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder=(DownloadService.DownloadBinder)service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button startDownload=(Button)findViewById(R.id.start_download);
        Button pauseDownload=(Button)findViewById(R.id.pause_download);
        Button cancelDownload=(Button)findViewById(R.id.cancel_download);
        startDownload.setOnClickListener(this);
        pauseDownload.setOnClickListener(this);
        cancelDownload.setOnClickListener(this);

        //启动服务
        Intent intent=new Intent(this,DownloadService.class);
        startService(intent);

        //绑定服务
        bindService(intent,connection,BIND_AUTO_CREATE);

        //判断是否有访问内存的权限
        if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }
    }

    @Override
    public void onClick(View v) {
        if(downloadBinder==null){
            return;
        }
        switch (v.getId()){
            case R.id.start_download:
                String url="http://raw.githubusercontent.com/guolindev/eclipse/master/eclipse-inst-win64.exe";
                Log.d(TAG, "onClick: ");
                downloadBinder.startDownload(url);
                break;
            case R.id.pause_download:
                downloadBinder.pauseDownload();
                break;
            case R.id.cancel_download:
                downloadBinder.cancelDownload();
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,String[] permissions,int[] grantResults){
        switch (requestCode){
            case 1:
                if(grantResults.length>0&&grantResults[0]!=PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(this,"拒绝权限将无法使用程序",Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        unbindService(connection);
    }
}

6、配置文件

添加如下代码:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>

这里主要是申请网络访问、访问SD卡和使用前台服务的权限。

在application标签中添加代码如下:

<application

    ......

    android:usesCleartextTraffic="true"

    ......

</application>

在app/build.gradle的android闭包中添加如下:

compileOptions{
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }

至此,这个下载项目就能正常运行了。

 刚接触Android不久,有错误还请大家指正,希望能和大家多交流。

 

原文地址:https://www.cnblogs.com/hzauxx/p/11001285.html