添加依赖
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
添加权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
新建回调接口DownloadListener
public interface DownloadListener {
void onProgress(int progress);
void onSuccess();
void onFailed();
void onPaused();
void onCanceled();
}
新建DownloadTask
为保证DownloadTask可以一直在后台运行,创建下载服务
/**
* String 表示在执行AsyncTask的时候需要传入String参数给后台任务
* Integer 泛型参数指定为Integer,表示使用整型数据作为进度显示单位
* Integer 泛型参数指定为Integer,表示使用Integer数据来反馈执行结果
*/
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 = null;
private boolean isCanceled = false;
private boolean isPaused = false;
private int lastProgress = 0;
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;
//下载的URL地址
String downloadUrl = params[0];
//解析出下载的文件名
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
//将文件下载到Environment.DIRECTORY_DOWNLOADS目录下,SD卡的Download目录
String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
file = new File(directory + fileName);
//Download目录下是否已经存在要下载的文件
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) {
//以Java文件流的方式,读取服务器的响应数据
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 (IOException 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) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(downloadUrl)
.build();
try {
Response response = client.newCall(request).execute();
if (response!=null&&response.isSuccessful()){
long contentLength = response.body().contentLength();
response.body().close();
return contentLength;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
DownloadService
public class DownloadService extends Service {
private DownloadTask downloadTask;
private String downloadUrl;
private DownloadListener listener = new DownloadListener() {
@Override
public void onProgress(int progress) {
//调用getNotification方法构建一个用于显示下载进度的通知,getNotificationManager().notify()触发这个通知
getNotificationManager().notify(1, getNotification("Download...", progress));
}
@Override
public void onSuccess() {
downloadTask = null;
//下载成功时将前台服务通知关闭,并创建一个下载成功的通知
stopForeground(true);
getNotificationManager().notify(1, getNotification("Download Success", -1));
Toast.makeText(DownloadService.this, "Download Success", Toast.LENGTH_LONG).show();
}
@Override
public void onFailed() {
downloadTask = null;
//下载失败时将前台服务通知关闭,并创建一个下载失败的通知
stopForeground(true);
getNotificationManager().notify(1, getNotification("Download Faild", -1));
Toast.makeText(DownloadService.this, "Download Faild", Toast.LENGTH_LONG).show();
}
@Override
public void onPaused() {
downloadTask = null;
Toast.makeText(DownloadService.this, "Paused", Toast.LENGTH_LONG).show();
}
@Override
public void onCanceled() {
downloadTask = null;
stopForeground(true);
Toast.makeText(DownloadService.this, "Canceled", Toast.LENGTH_LONG).show();
}
};
private DownloadBinder mbinder = new DownloadBinder();
@Override
public IBinder onBind(Intent intent) {
return mbinder;
}
//让DownloadService和活动可以进行通信
class DownloadBinder extends Binder {
public void startDownload(String url) {
if (downloadTask == null) {
downloadUrl = url;
downloadTask = new DownloadTask(listener);
//开始下载
downloadTask.execute(downloadUrl);
//前台服务
startForeground(1, getNotification("Download...", 0));
Toast.makeText(DownloadService.this, "Download...", Toast.LENGTH_LONG).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);
//Download目录下是否已经存在要下载的文件
if (file.exists()) {
file.delete();
}
getNotificationManager().cancel(1);
stopForeground(true);
Toast.makeText(DownloadService.this, "Canceled", Toast.LENGTH_LONG).show();
}
}
}
}
public DownloadService() {
}
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);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//判断是否是8.0Android.O
String channelID = "1";
String channelName = "channel_name";
NotificationChannel channel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
channel.setLightColor(Color.GREEN);
channel.enableVibration(true);
getNotificationManager().createNotificationChannel(channel);
builder.setChannelId(channelID);//该句适配android 8.0 版本
}
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setWhen(System.currentTimeMillis())
.setOngoing(true)//设置是否是一个正在执行的通知
.setContentIntent(pi);
if (progress >= 0) {
//当progress>=0时显示进度
builder.setContentText(progress + "%");
//100 通知的最进度 progress当前进度 是否使用模糊进度条
builder.setProgress(100, progress, false);
}
//设置为前台服务,必须绑定一个notification对象,实际上也就是说如果你想做持久化的Service就得让用户知道,PID是自定义的整数表明notification的ID
return builder.build();
}
}
Mainactivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private DownloadService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
downloadBinder = (DownloadService.DownloadBinder) service;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppCompatButton startDownload = findViewById(R.id.start_download);
AppCompatButton pauseDownload = findViewById(R.id.pause_download);
AppCompatButton cancelDownload = 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 view) {
if (downloadBinder == null){
return;
}
switch (view.getId()){
case R.id.start_download:
String url = "要下载的地址";
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, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if(grantResults.length>0&&grantResults[0]!=PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"拒绝程序将无法使用程序",Toast.LENGTH_LONG).show();
finish();
}
break;
default:
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}
}
运行结果