Android AsyncTack 异步任务实例详解

2019-05-02 16:33:33刘景俊

Android AsyncTack 异步任务

              这里写一个小实例,来学习巩固Android AsyncTack 异步任务的知识,以便在项目中使用。

介绍一下如何使用

1, 继承AsyncTask

public class MyTask extends AsyncTask<Params, Progrss, Result>

我们来说一下这三个泛型的作用:

Params: 调用异步任务时传入的类型 ;

Progress : 字面意思上说是进度条, 实际上就是动态的由子线程向主线程publish数据的类型

Result : 返回结果的类型

2, 重写这个类的抽象方法doInBackground, 当然它也有几个方法需要重写, 我们一一看来

doInBackground(抽象方法, 必须实现)

/* 唯一执行在子线程中的方法
 *  所以不可以进行UI的更新
 * @param params
 * @return
 */
@Override//返回值: Result    参数: Param
protected String doInBackground(TextView... params) {
  text = params[0];
  Random random = new Random();
  for (int i = 0; i < 50; i++) {
    //要进行进度的更新
    publishProgress(i);
    //不能直接调用onProgressUpdate方法,
    //这样会使得onProgressUpdate在子线程中运行
    try {
      Thread.sleep(random.nextInt(10) * 10);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
  return "已完成";
}

下面三个方法根据具体情况选择使用

 //执行doInBackground之前调用
  @Override
  protected void onPreExecute() {
    super.onPreExecute();
  }

  @Override//与publishProgress(i)对应
  protected void onProgressUpdate(Integer... values) {
    super.onProgressUpdate(values);
    text.setText(String.valueOf(values[0]));
  }


 //在doInBackground之后执行
  @Override // 参数s为 Result
  protected void onPostExecute(String s) {
    super.onPostExecute(s);
    text.setText(s);
  }

3, 执行异步任务

有两种方式, 我已经把区别写在了注释中
/*
 直接execute异步任务, 都是同一线程去执行
*/

text = (TextView) findViewById(R.id.main_text1);
new MyTask().execute(text);
text = (TextView) findViewById(R.id.main_text2);
new MyTask().execute(text);
text = (TextView) findViewById(R.id.main_text3);
new MyTask().execute(text);
text = (TextView) findViewById(R.id.main_text4);
new MyTask().execute(text);

/*
  启动多条线程来执行异步任务
  API11以上可以使用
*/
 ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(4);
 text = (TextView) findViewById(R.id.main_text1);
 new MyTask().executeOnExecutor(executor, text);
 text = (TextView) findViewById(R.id.main_text2);
 new MyTask().executeOnExecutor(executor, text);
 text = (TextView) findViewById(R.id.main_text3);
 new MyTask().executeOnExecutor(executor, text);
 text = (TextView) findViewById(R.id.main_text4);
 new MyTask().executeOnExecutor(executor, text);
								 
			 
相关文章 大家在看