Service的使用:断点下载

来源:互联网 发布:解剖软件 编辑:程序博客网 时间:2024/06/05 23:05

本文将使用到Service、OkHttp、AsyncTask、Notification、运行时权限申请。

首先,将OkHttp的依赖库添加好。

compile 'com.squareup.okhttp3:okhttp:3.8.1'

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

public interface DownloadListener {    void onProgress(int progress);    void onSuccess();    void onFailed();    void onPaused();    void onCanceled();}

接口定义好之后,就可以开始编写下载功能了,新建一个DownloadTask 继承自AsyncTask,如下:

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 (response != 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 downloadedUrl) throws IOException {        OkHttpClient client = new OkHttpClient();        Request request = new Request.Builder().url(downloadedUrl).build();        Response response = client.newCall(request).execute();        if (response != null && response.isSuccessful()) {            long contentLength = response.body().contentLength();            response.close();            return contentLength;        }        return 0;    }}

首先看一下AsyncTask中的3个泛型参数:第一个泛型参数指定为String,表示在执行AsyncTask的时候需要传入一个字符串参数给后台任务;第二个泛型参数指定为Integer,表示使用整型数据来作为进度显示单位;第三个泛型参数指定为Integer,表示使用整型数据来反馈执行结果。
然后在DownloadTask的构造函数中要求传入一个刚刚定义的DownloadListener参数,我们待会就会将下载的状态通过这个参数进行回调。
doInBackground()方法用于在后台执行具体的下载逻辑,onProgressUpdate()方法用于在界面上更新当前的下载进度,onPostExecute()用于通知最终的下载结果。
看一下doInBackground()方法,首先我们从参数中获取到了下载的URL地址,并根据URL地址解析出了下载的文件名,然后指定将文件下载到Environment.DIRECTORY_DOWNLOADS目录下,也就是SD卡的Download目录。我们还要判断一下Download目录中是不是已经存在要下载的文件了,如果已经存在的话则读取已下载的字节数,这样就可以在后面启用断点续传的功能。接下来使用OkHttp来发送一条网络请求,需要注意的是,这里在请求中添加了一个header,用于告诉服务器我们想要从哪个字节开始下载,因为已下载过的部分就不需要再从新下载了。接下来读取服务器响应的数据,并用Java的文件流方式,不断从网络上读取数据,不断写入到本地,一直到文件全部下载完成为止。在这个过程中,我们还要判断用户有没有触发暂停或者取消的操作,如果有的话则返回TYPE_CANCELED或者TYPE_PAUSED来中断下载,如果没有的话则实时计算当前的下载进度,然后调用publishProgress()方法进行通知。


为了保证DownloadTask可以一直在后台运行,我们还需要创建一个下载的服务。新建一个DownloadService,如下:

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, "Pause", Toast.LENGTH_SHORT).show();        }        @Override        public void onCanceled() {            downloadTask = null;            stopForeground(true);            Toast.makeText(DownloadService.this, "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();            } else {                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();                }            }        }    }    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);        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);        builder.setSmallIcon(R.mipmap.ic_launcher);        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));        builder.setContentIntent(pi);        builder.setContentTitle(title);        if (progress > 0) {            //当progress大于或等于0时才需显示下载进度            builder.setContentText(progress + "%");            builder.setProgress(100, progress, false);        }        return builder.build();    }}

首先这里创建了一个DownloadListener的匿名类实例,并在匿名类中实现了onProgress()、onSuccess()、onFailed()、onPaused()和onCanceled()这5个方法。在onProgress()方法中,调用getNotification()方法构建了一个用于显示下载进度的通知,然后调用NotificationManager的notify()方法去触发这个通知,这样就可以在下拉状态栏中实时看到当前下载的进度了。在onSuccess()方法中,首先是将正在下载的前台通知关闭,然后创建了一个新的通知用于告诉用户下载成功了。其他几个方法也类似。
接下来为了要让DownloadService可以和活动进行通信,我们又创建了一个DownloadBinder。为了让这个下载服务成为一个前台服务,调用了startForeground()方法,这样就会在系统状态栏中创建一个持续运行的通知了。注意取消下载的时候需要将正在下载的文件删除掉,这一点和暂停下载是不同的。
getNotification()方法中有个setProgress()方法接受3个参数,第一个参数传入通知的最大进度,第二个参数传入通知的当前进度,第三个参数表示是否使用模糊进度条,这里传入false。设置完setProgress()方法,通知上就会有进度条显示出来了。


下面是布局和MainActivity的代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    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" />    <Button        android:id="@+id/pause_download"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Pause DownLoad" />    <Button        android:id="@+id/cancel_download"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Cancel DownLoad" /></LinearLayout>

public class MainActivity extends AppCompatActivity implements View.OnClickListener {    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 = "这里填url地址";                downloadBinder.startDownload(url);                break;            case R.id.pause_download:                downloadBinder.pauseDownload();                break;            case R.id.cancel_download:                downloadBinder.cancelDownload();                break;        }    }    @Override    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {        switch (requestCode) {            case 1:                if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {                    Toast.makeText(this, "拒接权限将无法使用程序", Toast.LENGTH_SHORT).show();                    finish();                }                break;        }    }    @Override    protected void onDestroy() {        super.onDestroy();        unbindService(connection);    }}

首先创建了一个ServiceConnection的匿名类,然后在onServiceConnected()方法中获取到DownloadBinder的实例,有了这个实例,我们就可以在活动中调用服务提供的各种方法了。接下来分别调用了startService()和bindService()方法来启动和绑定服务。启动服务可以保证DownloadService一直在后台运行,绑定服务则可以让MainActivity和DownloadService进行通信,因此两个方法调用都必不可少。最后还进行了WRITE_EXTERNAL_STORAGE的运行时权限申请。另外需要注意,活动被销毁时记得对服务进行解绑,不然容易造成内存泄漏。

Demo

原创粉丝点击