定义一个下载接口
public interface DownloadListener {
void onProgress(int progress);
void onSuccess();
void onFailed();
void onPause();
void onCanceled();
}
这个回调接口是为了对于下载过程中的各种状态的监听和回调
定义一个下载任务类
package com.example.snake.servicebestpractice;
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.Response;
import okhttp3.Request;
/**
-
Created by Snake on 2020/9/6.
*/
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_PAUSE = 2;
public static final int TYPE_CNACELED = 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”, “byte=” + 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_CNACELED;
}
else if (isPaused) {
return TYPE_PAUSE;
}
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_PAUSE:
listener.onPause();
break;
case TYPE_CNACELED:
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 reponse = client.newCall(request).execute(); if(reponse != null && reponse.isSuccessful()){ long contentleng =reponse.body().contentLength(); reponse.body().close(); return contentleng; } return 0;
}
}
这是完成了具体的下载功能,要想一直保持在后台运行需要创建一个下载的服务;
再建一个下载的Service
package com.example.snake.servicebestpractice;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;
import java.io.File;
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 onPause() {
downloadTask = null;
Toast.makeText(DownloadService.this,"Paused", Toast.LENGTH_SHORT).show();
}
@Override
public void onCanceled() {
downloadTask = null;
stopForeground(true);
Toast.makeText(DownloadService.this,"Canceled", Toast.LENGTH_SHORT).show();
}
} ;
public DownloadService() {
}
private DownloadBinder mBinder = new DownloadBinder();
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();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
这完成使下载任务成为一个前台任务
主活动用于启动服务
package com.example.snake.servicebestpractice;
import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
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 start = (Button)findViewById(R.id.start);
Button pause = (Button)findViewById(R.id.pause);
Button cancel = (Button)findViewById(R.id.cancel);
start.setOnClickListener(this);
pause.setOnClickListener(this);
cancel.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:
String url = "https://raw.githubusercontent.com/guolindev/eclipse/master/eclipse-inst-win64.exe";
downloadBinder.startDownload(url);
break;
case R.id.pause:
downloadBinder.pauseDownload();
break;
case R.id.cancel:
downloadBinder.cancelDownload();
break;
default:
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;
default:
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}
}
这里用分别调用了startService()和BindService()来启动和捆绑服务保证此服务一直在后台运行
配置的layout就只有三个按键start,pause,canceled
最后别忘了申请权限和一些配置
<?xml version="1.0" encoding="utf-8"?><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".DownloadService"
android:enabled="true"
android:exported="true"></service>
</application>
权限很重要,要是忘了,很有可能导致程序无法运行甚至崩溃