
1. 泛型
AysncTask<Params,Progress,Result>
Params:启动任务时传入的参数,通过调用asyncTask.execute(param)方法传入。
Progress:后台任务执行的进度,若不用显示进度条,则不需要指定。
Result:后台任务结束时返回的结果。
2. 重要方法
doInBackground(Params... params):必须重写的方法,后台任务就在这里执行,会开启一个新的线程。params为启动任务时传入的参数,参数个数不定。
onPreExecute():在主线程中调用,在后台任务开启前的 *** 作在这里进行,例如显示一个进度条对话框。
onPostExecute(Result result):当后台任务结束后,在主线程中调用,处理doInBackground()方法返回的结果。
onProgressUpdate(Progress... values):当在doInBackground()中调用publishProgress(Progress... values)时,返回主线程中调用,这里的参数个数也是不定的。
onCancelled():取消任务。
3. 注意事项
(1)execute()方法必须在主线程中调用;
(2)AsyncTask实例必须在主线程中创建;
(3)不要手动调用doInBackground()、onPreExecute()、onPostExecute()、onProgressUpdate()方法;
(4)注意防止内存泄漏,在doInBackground()方法中若出现对Activity的强引用,可能会造成内存泄漏。
4. 下载文件动态更新进度条(未封装)
布局:
<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.androID.com/tools" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" androID:orIEntation="vertical" androID:padding="20dp" tools:context="com.studying.asynctaskdemo.MainActivity"> <Progressbar androID:ID="@+ID/progressbar" androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:progress="0" /> <button androID:ID="@+ID/download" androID:layout_wIDth="match_parent" androID:layout_height="50dp" androID:layout_margintop="20dp" androID:text="@string/start_btn" /> <TextVIEw androID:ID="@+ID/status" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_margintop="20dp" androID:text="@string/waiting" /></linearLayout>
Activity:
public class MainActivity extends Activity { private static final String file_name = "test.pdf";//下载文件的名称 private static final String pdf_URL = "http://clfile.imooc.com/class/assist/118/1328281/AsyncTask.pdf"; private Progressbar mProgressbar; private button mDownloadBtn; private TextVIEw mStatus; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); initVIEw(); setListener(); } private voID initVIEw() { mProgressbar = (Progressbar) findVIEwByID(R.ID.progressbar); mDownloadBtn = (button) findVIEwByID(R.ID.download); mStatus = (TextVIEw) findVIEwByID(R.ID.status); } private voID setListener() { mDownloadBtn.setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw v) { //AsyncTask实例必须在主线程创建 DownloadAsyncTask asyncTask = new DownloadAsyncTask(); asyncTask.execute(pdf_URL); } }); } /** * 泛型: * String:传入参数为文件下载地址 * Integer:下载过程中更新Progressbar的进度 * Boolean:是否下载成功 */ private class DownloadAsyncTask extends AsyncTask<String,Integer,Boolean> { private String mfilePath;//下载文件的保存路径 @OverrIDe protected Boolean doInBackground(String... params) { if (params != null && params.length > 0) { String pdfUrl = params[0]; try { URL url = new URL(pdfUrl); URLConnection urlConnection = url.openConnection(); inputStream in = urlConnection.getinputStream(); int contentLength = urlConnection.getContentLength();//获取内容总长度 mfilePath = Environment.getExternalStorageDirectory() + file.separator + file_name; //若存在同名文件则删除 file pdffile = new file(mfilePath); if (pdffile.exists()) { boolean result = pdffile.delete(); if (!result) { return false; } } int downloadSize = 0;//已经下载的大小 byte[] bytes = new byte[1024]; int length = 0; OutputStream out = new fileOutputStream(mfilePath); while ((length = in.read(bytes)) != -1) { out.write(bytes,length); downloadSize += length; publishProgress(downloadSize / contentLength * 100); } in.close(); out.close(); } catch (IOException e) { e.printstacktrace(); return false; } } else { return false; } return true; } @OverrIDe protected voID onPreExecute() { super.onPreExecute(); mDownloadBtn.setText("下载中"); mDownloadBtn.setEnabled(false); mStatus.setText("下载中"); mProgressbar.setProgress(0); } @OverrIDe protected voID onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); mDownloadBtn.setText("下载完成"); mStatus.setText(aBoolean ? "下载完成" + mfilePath : "下载失败"); } @OverrIDe protected voID onProgressUpdate(Integer... values) { super.onProgressUpdate(values); if (values != null && values.length > 0) { mProgressbar.setProgress(values[0]); } } }}5. 下载文件动态更新进度条(封装)
Activity:
public class MainActivity extends Activity { private static final String file_name = "test.pdf"; private static final String pdf_URL = "http://clfile.imooc.com/class/assist/118/1328281/AsyncTask.pdf"; private Progressbar mProgressbar; private button mDownloadBtn; private TextVIEw mStatus; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); initVIEw(); setListener(); } private voID initVIEw() { mProgressbar = (Progressbar) findVIEwByID(R.ID.progressbar); mDownloadBtn = (button) findVIEwByID(R.ID.download); mStatus = (TextVIEw) findVIEwByID(R.ID.status); } private voID setListener() { mDownloadBtn.setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw v) { String localPath = Environment.getExternalStorageDirectory() + file.separator + file_name; DownloadHelper.download(pdf_URL,localPath,new DownloadHelper.OnDownloadListener() { @OverrIDe public voID onStart() { mDownloadBtn.setText("下载中"); mDownloadBtn.setEnabled(false); mStatus.setText("下载中"); mProgressbar.setProgress(0); } @OverrIDe public voID onSuccess(file file) { mDownloadBtn.setText("下载完成"); mStatus.setText(String.format("下载完成:%s",file.getPath())); } @OverrIDe public voID onFail(file file,String failinfo) { mDownloadBtn.setText("开始下载"); mDownloadBtn.setEnabled(true); mStatus.setText(String.format("下载失败:%s",failinfo)); } @OverrIDe public voID onProgress(int progress) { mProgressbar.setProgress(progress); } }); } }); }}DownloadHelper:
class DownloadHelper { static voID download(String url,String localPath,OnDownloadListener Listener) { DownloadAsyncTask task = new DownloadAsyncTask(url,Listener); task.execute(); } private static class DownloadAsyncTask extends AsyncTask<String,Boolean> { private String mFailinfo; private String mUrl; private String mfilePath; private OnDownloadListener mListener; DownloadAsyncTask(String mUrl,String mfilePath,OnDownloadListener mListener) { this.mUrl = mUrl; this.mfilePath = mfilePath; this.mListener = mListener; } @OverrIDe protected Boolean doInBackground(String... params) { String pdfUrl = mUrl; try { URL url = new URL(pdfUrl); URLConnection urlConnection = url.openConnection(); inputStream in = urlConnection.getinputStream(); int contentLength = urlConnection.getContentLength(); file pdffile = new file(mfilePath); if (pdffile.exists()) { boolean result = pdffile.delete(); if (!result) { mFailinfo = "存储路径下的同名文件删除失败!"; return false; } } int downloadSize = 0; byte[] bytes = new byte[1024]; int length; OutputStream out = new fileOutputStream(mfilePath); while ((length = in.read(bytes)) != -1) { out.write(bytes,length); downloadSize += length; publishProgress(downloadSize / contentLength * 100); } in.close(); out.close(); } catch (IOException e) { e.printstacktrace(); mFailinfo = e.getMessage(); return false; } return true; } @OverrIDe protected voID onPreExecute() { super.onPreExecute(); if (mListener != null) { mListener.onStart(); } } @OverrIDe protected voID onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); if (mListener != null) { if (aBoolean) { mListener.onSuccess(new file(mfilePath)); } else { mListener.onFail(new file(mfilePath),mFailinfo); } } } @OverrIDe protected voID onProgressUpdate(Integer... values) { super.onProgressUpdate(values); if (values != null && values.length > 0) { if (mListener != null) { mListener.onProgress(values[0]); } } } } interface OnDownloadListener{ voID onStart(); voID onSuccess(file file); voID onFail(file file,String failinfo); voID onProgress(int progress); }}总结
以上所述是小编给大家介绍的AndroID中使用AsyncTask实现下载文件动态更新进度条功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程小技巧网站的支持!
总结以上是内存溢出为你收集整理的Android中使用AsyncTask实现下载文件动态更新进度条功能全部内容,希望文章能够帮你解决Android中使用AsyncTask实现下载文件动态更新进度条功能所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)