当执行一个异步任务,任务经过4个步骤:
1.onPreExecute(), invoked on the UI thread before the task is executed. use this to diaply progress dialog.
2.doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. Can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
3.onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). Used to publish progress.
4.onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
在你活动的onCreate()
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv= (TextView)findViewById(R.id.textView);
new TheTask().execute();
}
class TheTask extends AsyncTask<Void, Void,String> {
protected void onPreExecute() {
//dispaly progress dialog
}
protected String doInBackground(Void... params) {
//do network operation
return "hello";
}
protected void onPostExecute(String result) {
//dismiss dialog. //set hello to textview
//use the returned value here.
tv.setText(result.toString());
}
}
考虑使用robospice(到的AsyncTask的替代品。 https://github.com/octo-online/robospice。
进行异步调用,在ui线程上通知。
AsyncTask解释谷歌:https://developer.android.com/guide/components/processes-and-threads.html#AsyncTask – 2013-03-26 11:09:10