AsyncTask不仅方便我们在子线程中对UI进行更新操作,还可以借助其本身的线程池来实现多线程任务。下面是一个使用AsyncTask来实现的多线程下载例子。

01 效果图
02 核心类 - DownloadTask.class
public class DownloadTask extends AsyncTask<String, Integer, Integer> {
public static final int TYPE_SUCCESS = 0;
public static final int TYPE_FAILURE = 1;
public static final int TYPE_PAUSE = 2;
public static final int TYPE_CANCEL = 3;
public int positionDownload;
private boolean isPaused = false;
private boolean isCancelled = false;
private DownloadListener downloadListener;
private int lastProgress;
public DownloadTask(DownloadListener downloadListener){
this.downloadListener = downloadListener;
}
public void setDownloadListener(DownloadListener downloadListener){
this.downloadListener = downloadListener;
}
@Override
protected Integer doInBackground(String... params) {
InputStream is = null;
RandomAccessFile savedFile = null;
File file = null;
long downloadLength = 0;
String downloadUrl = params[0];
positionDownload = Integer.parseInt(params[1]);
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_FAILURE;
} else if(contentLength == downloadLength){
return TYPE_SUCCESS;
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.addHeader("RANGE", "bytes="+downloadLength+"-")
.url(downloadUrl)
.build();
try {
Response response = client.newCall(request).execute();
if(response != null){
is = response.body().byteStream();
savedFile = new RandomAccessFile(file, "rw");
savedFile.seek(downloadLength);
byte[] buffer = new byte[1024];
int total = 0;
int length;
while((length = is.read(buffer)) != -1){
if(isCancelled){
response.body().close();
return TYPE_CANCEL;
} else if(isPaused) {
response.body().close();
return TYPE_PAUSE;
}
total += length;
savedFile.write(buffer, 0, length);
int progress = (int) ((total + downloadLength) * 100 / contentLength);
int currentDownload = (int) (total + downloadLength);
publishProgress(positionDownload, progress, currentDownload, (int) contentLength);
}
response.body().close();
return TYPE_SUCCESS;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(is != null) is.close();
if(savedFile != null) savedFile.close();
if(isCancelled && file != null) file.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
return TYPE_FAILURE;
}
@Override
protected void onProgressUpdate(Integer... values) {
int progress = values[1];
if(progress > lastProgress){
downloadListener.onProgress(values[0], progress, values[2], values[3]);
lastProgress = progress;
}
}
@Override
protected void onPostExecute(Integer status) {
switch (status){
case TYPE_SUCCESS:
downloadListener.onSuccess(positionDownload);
break;
case TYPE_FAILURE:
downloadListener.onFailure();
break;
case TYPE_PAUSE:
downloadListener.onPause();
break;
case TYPE_CANCEL:
downloadListener.onCancel();
break;
}
}
public void pauseDownload(){
isPaused = true;
}
public void cancelDownload(){
isCancelled = true;
}
private long getContentLength(String downloadUrl) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(downloadUrl)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
if(response != null && response.isSuccessful()){
long contentLength = response.body().contentLength();
response.body().close();
return contentLength;
}
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
}
03 核心类 - DownloadService.class
public class DownloadService extends Service {
private Map<String, DownloadTask> downloadTaskMap = new HashMap<>();
private DownloadBinder mBinder = new DownloadBinder();
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private Notification getNotification(String title, int progress) {
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = 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(pendingIntent);
builder.setContentTitle(title);
if(progress > 0){
builder.setContentText(progress + "%");
builder.setProgress(100, progress, false);
}
return builder.build();
}
private NotificationManager getNotificationManager() {
return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
class DownloadBinder extends Binder {
public void startDownload(String url, int position, DownloadListener listener){
if(!downloadTaskMap.containsKey(url)){
DownloadTask downloadTask = new DownloadTask(listener);
downloadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url, position+"");
downloadTaskMap.put(url, downloadTask);
if(downloadTaskMap.size() == 1){
startForeground(1, getNotification("正在下载" + downloadTaskMap.size(), -1));
} else{
getNotificationManager().notify(1, getNotification("正在下载" + downloadTaskMap.size(), -1));
}
}
}
public void updateDownload(String url, DownloadListener listener){
if(downloadTaskMap.containsKey(url)){
DownloadTask downloadTask = downloadTaskMap.get(url);
if(downloadTask != null){
downloadTask.setDownloadListener(listener);
}
}
}
public void pauseDownload(String url){
if(downloadTaskMap.containsKey(url)){
DownloadTask downloadTask = downloadTaskMap.get(url);
if(downloadTask != null){
downloadTask.pauseDownload();
}
downloadTaskMap.remove(url);
if(downloadTaskMap.size() > 0){
getNotificationManager().notify(1, getNotification("正在下载" + downloadTaskMap.size(), -1));
} else {
stopForeground(true);
getNotificationManager().notify(1, getNotification("全部暂停下载", -1));
}
}
}
public void downloadSuccess(String url){
if(downloadTaskMap.containsKey(url)){
DownloadTask downloadTask = downloadTaskMap.get(url);
downloadTaskMap.remove(url);
if(downloadTask != null){
downloadTask = null;
}
if(downloadTaskMap.size() > 0){
getNotificationManager().notify(1, getNotification("正在下载" + downloadTaskMap.size(), -1));
} else {
stopForeground(true);
getNotificationManager().notify(1, getNotification("下载成功", -1));
}
}
}
public boolean isDownloading(String url){
if(downloadTaskMap.containsKey(url)){
return true;
}
return false;
}
public void cancelDownload(String url){
if(downloadTaskMap.containsKey(url)){
DownloadTask downloadTask = downloadTaskMap.get(url);
if(downloadTask != null){
downloadTask.cancelDownload();
}
downloadTaskMap.remove(url);
if(downloadTaskMap.size() > 0){
getNotificationManager().notify(1, getNotification("正在下载" + downloadTaskMap.size(), -1));
} else {
stopForeground(true);
getNotificationManager().notify(1, getNotification("全部取消下载", -1));
}
}
if(url != null){
String fileName = url.substring(url.lastIndexOf("/"));
String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
File file = new File(directory + fileName);
if(file.exists()){
file.delete();
Toast.makeText(DownloadService.this, "Deleted", Toast.LENGTH_SHORT).show();
}
}
}
}
}
04 源码
下载地址
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
# android
# AsyncTask
# 多线程下载
# asynctask多线程
# Android 使用AsyncTask实现多任务多线程断点续传下载
# Android多线程AsyncTask详解
# Android使用AsyncTask实现多线程下载的方法
# Android开发笔记之:深入理解多线程AsyncTask
# Android 使用AsyncTask实现断点续传
# Android 使用AsyncTask实现多线程断点续传
# 来实现
# 多线程
# 是一个
# 还可以
# 下载地址
# 中对
# 大家多多
# getPath
# exists
# DIRECTORY_DOWNLOADS
# Environment
# getExternalStoragePublicDirectory
# OkHttpClient
# return
# getContentLength
# length
# contentLength
# downloadLength
# downloadUrl
# long
相关文章:
深圳防火门网站制作公司,深圳中天明防火门怎么编码?
,柠檬视频怎样兑换vip?
重庆市网站制作公司,重庆招聘网站哪个好?
Python如何创建带属性的XML节点
专业型网站制作公司有哪些,我设计专业的,谁给推荐几个设计师兼职类的网站?
济南网站建设制作公司,室内设计网站一般都有哪些功能?
详解jQuery中基本的动画方法
建站之星导航如何优化提升用户体验?
广州网站设计制作一条龙,广州巨网网络科技有限公司是干什么的?
c++ stringstream用法详解_c++字符串与数字转换利器
金*站制作公司有哪些,金华教育集团官网?
GML (Geography Markup Language)是什么,它如何用XML来表示地理空间信息?
如何通过VPS建站实现广告与增值服务盈利?
简单实现Android文件上传
宁波免费建站如何选择可靠模板与平台?
网站制作的软件有哪些,制作微信公众号除了秀米还有哪些比较好用的平台?
怀化网站制作公司,怀化新生儿上户网上办理流程?
如何正确下载安装西数主机建站助手?
如何实现建站之星域名转发设置?
如何快速搭建高效WAP手机网站?
实现虚拟支付需哪些建站技术支撑?
制作网站的公司有哪些,做一个公司网站要多少钱?
内部网站制作流程,如何建立公司内部网站?
宝华建站服务条款解析:五站合一功能与SEO优化设置指南
制作宣传网站的软件,小红书可以宣传网站吗?
如何用PHP快速搭建高效网站?分步指南
如何高效配置IIS服务器搭建网站?
如何在万网自助建站中设置域名及备案?
建站之星×万网:智能建站系统+自助建站平台一键生成
企业宣传片制作网站有哪些,传媒公司怎么找企业宣传片项目?
视频网站app制作软件,有什么好的视频聊天网站或者软件?
简单实现Android验证码
大连 网站制作,大连天途有线官网?
怎么用手机制作网站链接,dw怎么把手机适应页面变成网页?
宝塔建站无法访问?如何排查配置与端口问题?
股票网站制作软件,网上股票怎么开户?
网站制作和推广的区别,想自己建立一个网站做推广,有什么快捷方法马上做好一个网站?
小说建站VPS选用指南:性能对比、配置优化与建站方案解析
制作网站哪家好,cc、.co、.cm哪个域名更适合做网站?
如何用花生壳三步快速搭建专属网站?
如何高效生成建站之星成品网站源码?
如何将凡科建站内容保存为本地文件?
Android自定义控件实现温度旋转按钮效果
海南网站制作公司有哪些,海口网是哪家的?
在线ppt制作网站有哪些,请推荐几个好的课件下载的网站?
常州企业网站制作公司,全国继续教育网怎么登录?
如何零基础开发自助建站系统?完整教程解析
婚礼视频制作网站,学习*后期制作的网站有哪些?
高防服务器如何保障网站安全无虞?
宝盒自助建站智能生成技巧:SEO优化与关键词设置指南
*请认真填写需求信息,我们会在24小时内与您取得联系。