(1)模拟图片下载的基础Demo
1.主要代码
public class DelayOperator { //延时操作,用来模拟下载 public void delay() { try { Thread.sleep(1000); }catch (InterruptedException e){ e.printStackTrace(); } } } public class MyAsyncTask extends AsyncTask { private TextView textView; private ProgressBar progressBar; public MyAsyncTask(TextView textView,ProgressBar progressBar) { super(); this.textView = textView; this.progressBar = progressBar; } //该方法不运行在UI线程中,主要用于异步操作,通过调用publishProgress()方法 //触发onProgressUpdate对UI进行操作 @Override protected String doInBackground(Integer… params) { DelayOperator dop = new DelayOperator(); int i ; for (i = 10;i <= 100;i+=10) { //判断是否为取消状态 dop.delay(); publishProgress(i); } return i + params[0].intValue() + “”; } //该方法运行在UI线程中,可对UI控件进行设置 @Override protected void onPreExecute() { textView.setText(“开始执行异步线程~”); } //在doBackground方法中,每次调用publishProgress方法都会触发该方法 //运行在UI线程中,可对UI控件进行操作 @Override protected void onProgressUpdate(Integer… values) { int value = values[0]; progressBar.setProgress(value); } }
2.实现效果
(2)进阶版从网络下载图片的实际应用
1.主要代码
public class ImageAsyncTask extends AsyncTask { private TextView textView; private ImageView imageView; public ImageAsyncTask(TextView textView,ImageView imageView) { super(); this.textView = textView; this.imageView=imageView; } @Override protected void onPreExecute() { super.onPreExecute(); //页面提示 textView.setText(“下载中…”); } @Override protected Integer doInBackground(String… params) { //记录成功下载的图片个数 int downloadSuccess = 0; try { for (int i = 0; i < params.length; i++) { //睡眠2秒,制造耗时操作效果 Thread.sleep(2000); if(isCancelled()){ break; } //循环取出可变参数中图片地址