代码:
package com.test.handler; import com.test.demo.R; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class AsyncTaskTestActivity extends Activity { private TextView textView; private ProgressDialog dialog; //Counter 用于保存中间结果 private class Counter { public int progress; public int sum; public Counter(int progress, int sum) { this.progress = progress; this.sum = sum; } } //定义AsyncTask子类,传给任务的参数Void,处理中间结果类型为Counter类型,处理最终结果为Integer类型 private class MyTask extends AsyncTask<Void, Counter, Integer> { @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); textView.setText("result:0"); dialog.show(); } @Override protected Integer doInBackground(Void... params) { int sum = 0; try { for (int i = 0; i < 100; i++) { sum += i * 2; //发布中间结果,onProgressUpdate函数对中间结果进行处理,可以在UI组件上显示进度 publishProgress(new Counter(i, sum)); Thread.sleep(40); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } //返回最终处理结果 return Integer.valueOf(sum); } @Override protected void onProgressUpdate(Counter... values) { // 中间结果处理:设置进度条,textView上显示目前累加的结果 dialog.setProgress(values[0].progress); textView.setText("result:" + values[0].sum); } // doInBackground处理完成后执行 @Override protected void onPostExecute(Integer result) { super.onPostExecute(result); dialog.dismiss(); textView.setText("result:" + result); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_handler_test2); dialog = new ProgressDialog(this); dialog.setTitle("start"); dialog.setIcon(R.drawable.ic_dialog_load); dialog.setMessage("please wait"); dialog.setMax(100); dialog.setProgress(0); dialog.setIndeterminate(false); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setCancelable(false); textView = (TextView) findViewById(R.id.result2); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.handler_test2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } else if (id == R.id.action_reflash2) { //启动任务,每次都是创建新的任务对象 new MyTask().execute(); return true; } return super.onOptionsItemSelected(item); } }
layout文件:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.test.handler.AsyncTaskTestActivity" > <TextView android:id="@+id/result2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </RelativeLayout>
Android doc上给出的规定:
Threading rules
There are a few threading rules that must be followed for this class to work properly:
- The AsyncTask class must be loaded on the UI thread. This is done automatically as of
JELLY_BEAN
.- The task instance must be created on the UI thread.
execute(Params...)
must be invoked on the UI thread.- Do not call
onPreExecute()
,onPostExecute(Result)
,doInBackground(Params...)
,onProgressUpdate(Progress...)
manually.- The task can be executed only once (an exception will be thrown if a second execution is attempted.)