安卓 断点下载Demo(通知栏显示进度)
真机测试过,要打开该app的状态栏通知
进入正题
1.添加需要使用的依赖库:
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
2.新建DownloadListener接口
–
这里是5个回调方法
public interface DownloadListener {
void onProgress(int progress);//当前下载的进度
void onSuccess();//下载成功
void onFailed();//下载失败
void onPaused();//暂停
void onCanceled();//取消
}
3.接下来编写下载功能DownloadTask
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
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;
import static android.content.ContentValues.TAG;
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 isPaused = false;
private boolean isCanceled = 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.getExternalStorageDirectory().getPath(); //打印一下文件文字和下载目录
Log.d(TAG,"doInBackground: "+directory+" "+fileName);
file = new File(directory+fileName);
if (file.exists()){
downloadedLength = file.length();
}
long contentLength = getConContentLength(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 process = (int) ((total + downloadedLength) * 100/contentLength);
publishProgress(process);
}
}
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 getConContentLength(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.为保证3可以在后台一直运行,需要一个下载服务DownloadService
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.widget.Toast;
import androidx.core.app.NotificationCompat;
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 onPaused() {
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();
}
};
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.getActivities(this, 0, new Intent[]{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) {
// TODO: Return the communication channel to the service.
return mBinder;
}
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();
// String directory = Environment.getExternalStorageDirectory().getPath();
File file = new File(directory + fileName);
if(file.exists()){
file.delete();
}
getNotificationManager().cancel(1);
stopForeground(true);
Toast.makeText(DownloadService.this,"Cancel",Toast.LENGTH_SHORT).show();
}
}
}
}
}
5.现在来画安卓页面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<!--<ProgressBar-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content"-->
<!--android:id="@+id/progress"-->
<!--style="?android:attr/progressBarStyleHorizontal"-->
<!--android:max="100"-->
<!--/>-->
<!--<TextView-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_centerHorizontal="true"-->
<!--android:textSize="22sp"-->
<!--android:text=""-->
<!--android:id="@+id/pro_text"-->
<!--android:layout_below="@id/progress" />-->
<Button
android:text="开始下载"
android:id="@+id/start_download"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:text="暂停下载"
android:id="@+id/pause_download"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:text="取消下载"
android:id="@+id/cancel_download"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
6.接下来写MainActivity,主要是3个按钮
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.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private DownloadService.DownloadBinder downloadBinder;
private DownloadTask downloadTask;
private ProgressBar pro_bar;
private TextView pro_text;
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 = findViewById(R.id.start_download);
Button pauseDownload = findViewById(R.id.pause_download);
Button cancelDownload = findViewById(R.id.cancel_download);
pro_text = findViewById(R.id.pro_text);
pro_bar = findViewById(R.id.progress);
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://180.153.93.17/dlied4.myapp.com/myapp/1104466820/sgame/2017_com.tencent.tmgp.sgame_h9857_1.51.1.5_2fb714.apk?mkey=5dca6b797559a117&f=0ae7&cip=117.89.135.226&proto=http";
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(MainActivity.this,"拒绝权限将无法使用程序",Toast.LENGTH_LONG).show();
finish();
}
break;
default:
}
}
@Override
protected void onDestroy(){
super.onDestroy();
unbindService(connection);
}
}
7.最后加上权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />