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,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],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,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,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,-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,-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("下载成功",-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("全部取消下载",-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实现多线程下载实例全部内容,希望文章能够帮你解决android使用AsyncTask实现多线程下载实例所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)