Android API 3时引进了AsyncTask,也叫异步任务。使用它可以很方便的更新主线程中的UI,使用它比Handler、Thread更简单。由于AsyncTask是抽象类,要使用它首先要创建子类继承它。创建子类时需要三个泛型参数
Params 调用execute时传入的参数,
Progress 需要显示的进度信息
Result 任务执行完毕后doInBackground的返回值
看下使用AsyncTask控制进度条的效果
代码实现
- package com.example.asynctaskdemo;
- import android.app.Activity;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ProgressBar;
- /**
- * AsyncTask的简单使用
- *
- * @author Administrator
- *
- */
- public class MainActivity extends Activity {
- private ProgressBar pro = null;
- private Button start = null;
- private Button stop = null;
- private boolean isExe = false;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- pro = (ProgressBar) findViewById(R.id.progress);
- start = (Button) findViewById(R.id.start);
- stop = (Button) findViewById(R.id.stop);
- final UpdatePro updatePro = new UpdatePro();
- // 开始任务
- start.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- if (!isExe) {
- // 一个任务只能被执行一次,否则会报异常
- updatePro.execute();
- isExe = true;
- }
- }
- });
- // 结束任务
- stop.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- if (isExe) {
- updatePro.cancel(true);
- }
- }
- });
- }
- /**
- * 更新UI线程
- *
- * @author Administrator
- *
- */
- class UpdatePro extends AsyncTask<Void, Integer, Boolean> {
- private int downloadPercent = 0;
- /**
- * 核心的操作
- */
- @Override
- protected Boolean doInBackground(Void... params) {
- // TODO Auto-generated method stub
- try {
- while (true) {
- downloadPercent = downloadPercent + 10;
- // 把数据传给onProgressUpdate更新UI
- publishProgress(downloadPercent);
- if (downloadPercent >= 300) {
- //downloadPercent = 0;
- break;
- }
- System.out.println("----- downloadPercent = "
- + downloadPercent);
- Thread.sleep(10000);
- }
- } catch (Exception e) {
- return false;
- }
- return true;
- }
- /**
- * 获取doInBackground返回的结果
- */
- @Override
- protected void onPostExecute(Boolean result) {
- // TODO Auto-generated method stub
- System.out.println("--------------onPostExecute " + result);
- super.onPostExecute(result);
- }
- /**
- * 最先执行 初始化工作
- */
- @Override
- protected void onPreExecute() {
- // TODO Auto-generated method stub
- System.out.println("--------------onPreExecute");
- pro.setProgress(0);
- super.onPreExecute();
- }
- /**
- * 得到publishProgress传入的值,更新UI
- */
- @Override
- protected void onProgressUpdate(Integer... values) {
- // TODO Auto-generated method stub
- System.out.println("--------------onProgressUpdate " + values[0]);
- pro.setProgress(values[0]);
- super.onProgressUpdate(values);
- }
- }
- }
Demo下载:http://files.cnblogs.com/android100/AsyncTaskDemo.zip