依赖
compile 'com.squareup.okhttp3:okhttp:3.9.0'
权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
接口
public interface CallBack {
void startDownload();
void pauseDownload();
void finishDownload();
void downloadProgress(long progress);
}
下载工具类
public class DownLoadUtils {
private static final String TAG = "DownloadUtils";
private static volatile DownLoadUtils instance;
private final OkHttpClient client;
private String filePath;
private File downloadFile;
private long startPosition;
private Call call;
private File file;
private DownLoadUtils() {
client = new OkHttpClient();
}
private CallBack callback;
public void setListener(CallBack callback) {
this.callback = callback;
}
/**
* 初始化下载父路径
*
* */
public void initDownload(String path){
file = new File(path);
// if (!file.getParentFile().exists()) {
// file.getParentFile().mkdir();
// }
// if (!file.exists()) {
// file.mkdir();
// }
filePath = file.getAbsolutePath();
Log.e(TAG, "initDownload: " + filePath);
}
public static DownLoadUtils getInstance() {
if (null == instance) {
synchronized (DownLoadUtils.class) {
if (instance == null) {
instance = new DownLoadUtils();
}
}
}
return instance;
}
public void startDownload(String url){
if (TextUtils.isEmpty(url)) {
//url为空直接返回回去
return;
}
if (url.contains(".")) {
String typeName = url.substring(url.lastIndexOf(".") + 1);
if (url.contains("/")) {
String name = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
String fn = name + "." + typeName;
//父路径 文件名
downloadFile = new File(file, fn);
}
}
startPosition = 0;
if (downloadFile.exists()) {
startPosition = downloadFile.length();
}
Request request = new Request.Builder()
.addHeader("RANGE", "bytes=" + startPosition + "-")
.url(url)
.build();
call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
callback.startDownload();
ResponseBody body = response.body();
long totalLength = body.contentLength()+startPosition;
Log.e(TAG, "totalLength: " + totalLength + "----");
InputStream is = body.byteStream();
byte[] buf = new byte[2048];
int len = 0;
long totalNum = startPosition;
while((len = is.read(buf,0,buf.length))!=-1){
RandomAccessFile raf = new RandomAccessFile(downloadFile, "rw");
raf.seek( totalNum);
raf.write(buf,0,len);
callback.downloadProgress(totalNum*100/totalLength);
totalNum+=len;
Log.e(TAG, "startposition "+totalNum+"===" );
}
callback.finishDownload();
body.close();
}
});
}
public void pauseDownload() {
callback.pauseDownload();
if (call != null && call.isExecuted()) {
call.cancel();
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnStart;
private Button btnPause;
private String downloadUrl = "http://dlsw.baidu.com/sw-search-sp/soft/4b/17170/Install_WLMessenger14.0.8117.416.1393467029.exe";
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.button);
btnPause = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.textView);
btnStart.setOnClickListener(this);
btnPause.setOnClickListener(this);
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File storageDirectory = Environment.getExternalStorageDirectory();
String absolutePath = storageDirectory.getAbsolutePath();
String path = absolutePath + "/Download/";
Log.e("---", "下载路径"+path);
DownLoadUtils.getInstance().initDownload(path);
DownLoadUtils.getInstance().setListener(new CallBack() {
@Override
public void startDownload() {
}
@Override
public void pauseDownload() {
}
@Override
public void finishDownload() {
}
@Override
public void downloadProgress(final long progress) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// Log.e("0000", "run: "+progress+"" );
textView.setText(progress+"");
}
});
}
});
}
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button:
DownLoadUtils.getInstance().startDownload(downloadUrl);
break;
case R.id.button2:
DownLoadUtils.getInstance().pauseDownload();
break;
}
}
}