根据前面的自己写了一个测试程序:
MainActivity.java如下:
package com.example.androidasynctaskdemos;import android.os.AsyncTask;import android.os.Bundle;import android.app.Activity;import android.util.Log;import android.view.Menu;import android.widget.TextView;public class MainActivity extends Activity { private final static String TAG="MainActivity"; private myTask tasker; private TextView mText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mText=(TextView)findViewById(R.id.text_view); mText.setText("start"); tasker=new myTask(); tasker.execute("","","");//开始执行 } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public class myTask extends AsyncTask{ @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub Log.i(TAG,"doInBackground"); for(int i=1;i<1000;i++){ publishProgress(i);//通知更新UI信息 try { Thread.sleep(250);//每隔250ms更新一次UI } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); //这里将在doInBackground全部执行完成后开始执行 } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); Log.i(TAG,"onPreExecute"); //启动任何之前首先执行的地方,可以用于初始化UI信息 } @Override protected void onProgressUpdate(Integer... values) { // TODO Auto-generated method stub super.onProgressUpdate(values); Log.i(TAG,"onProgressUpdate"); mText.setText("result : "+values[0]);//实时更新UI处 } }}
布局文件: