如何实现安卓下载呢?接下来由我来告诉大家
首先我们需要在项目中添加依赖库,编辑app/build.gradle文件,在dependencies闭包中添加如下内容
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
**implementation'com.squareup.okhttp3:okhttp:3.4.1'**
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
接下来
定义一个回掉接口。新建一个 DownloadListene
package com.example.hejun.servicebestpractice;
public interface DownloadListener {
void onProgress(int progress);
void onSuccess();
void onFailed();
void onPaused();
void onCanceled();
}
编写下载功能新建一个DownloadTask类
package com.example.hejun.servicebestpractice;
import android.content.Intent;
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...parms){
InputStream is = null;
RandomAccessFile savedFile = null;
File file = null;
try{
long downloadLength = 0;//记录已经下载的文件长度
String downloadUrl = parms[0];
String fileName =downloadUrl.substring ( downloadUrl.lastIndexOf ( "/" ) );
String directory = Environment.getExternalStoragePublicDirectory (
Environment.DIRECTORY_DOWNLOADS
).getPath ();
file = new File ( directory +fileName );
if (file.exists ()){
downloadLength= file.length ();
}
long contentLength = getContentLength(downloadUrl);
if (contentLength ==0){
return TYPE_FAILED;
}else if (contentLength == downloadLength){
//已经下载字节和文件总字节相等,说明已经下载完成了
return TYPE_SUCCESS;
}
OkHttpClient client = new OkHttpClient ();
Request request = new Request.Builder ()
//断点下载
.addHeader ( "RANGE","bytes="+downloadLength+"-" )
.url ( downloadUrl )
.build ();
Response response = client.newCall ( request ).execute();
if (response != null){
is = response.body ().byteStream ();
savedFile = new RandomAccessFile ( file,"rw" );
savedFile.