Android AsyncTask简单用法
三個泛型參數:
Param?任務執行器需要的數據類型
Progress?后臺計算中使用的進度單位數據類型
Result?后臺計算返回結果的數據類型有些參數是可以設置為不使用的,只要傳遞為Void型即可,比如AsyncTask
四個步驟:onPreExecute(),執行預處理,它運行于UI線程,可以為后臺任務做一些準備工作,比如繪制一個進度條控件。doInBackground(Params…),后臺進程執行的具體計算在這里實?現,doInBackground(Params…)是AsyncTask的關鍵,此方法必須重載。在這個方法內可以使用?publishProgress(Progress…)改變當前的進度值。onProgressUpdate(Progress…),運行于UI線程。如果在doInBackground(Params…)中?使用了publishProgress(Progress…),就會觸發這個方法。在這里可以對進度條控件根據進度值做出具體的響應。onPostExecute(Result),運行于UI線程,可以對后臺任務的結果做出處理,結果就是doInBackground(Params…)的返回值。此方法也要經常重載,如果Result為null表明后臺任務沒有完成(被取消或者出現異常)。
這4個方法都不能手動調用。而且除了doInBackground(Params…)方法,其余3個方法都是被UI線程所調用的,所以要求:1)?AsyncTask的實例必須在UI?thread中創建;2)?AsyncTask.execute方法必須在UI?thread中調用;
Task只能被執行一次,多次調用時將會出現異常,而且是不能手動停止。
import?android.app.Activity;?import?android.os.AsyncTask;?
import?android.os.Bundle;?
import?android.util.Log;?
import?android.widget.TextView;?
public?class?AsyncTaskTest?extends?Activity?{?
????TextView?tv;?
????final?String?TAG="AsyncTaskTest";?
??
????@Override?
????protected?void?onCreate(Bundle?savedInstanceState)?{?
????????super.onCreate(savedInstanceState);?
????????setContentView(R.layout.main);?
????????tv?=?(TextView)?findViewById(R.id.label);?
????????new?MyTask().execute(6,?12,?7);?
??
????}?
??
????class?MyTask?extends?AsyncTask<Integer,?Integer,?Integer>?{?
??
????????@Override?
????????protected?void?onPreExecute()?{?
????????????super.onPreExecute();?
????????????Log.d(TAG,?"onPreExecute()");?
????????}?
??
????????@Override?
????????protected?Integer?doInBackground(Integer...?params)?{?
????????????Log.d(TAG,?"doInBackground()");?
????????????int?p?=?0;?
????????????for?(int?index?=?0;?index?<?params.length;?index++)?{?
????????????????int?num?=?params[index];?
????????????????for?(int?j?=?0;?j?<?num;?j++)?{?
????????????????????if?(num?-?j?<=?0)?{?
????????????????????????break;?
????????????????????}?
????????????????????p++;?
????????????????????publishProgress(p);?
????????????????????try?{?
????????????????????????Thread.sleep(500);?
????????????????????}?catch?(InterruptedException?e)?{?
????????????????????????e.printStackTrace();?
????????????????????}?
????????????????}?
????????????}?
????????????return?p;?
????????}
??
????????@Override?
????????protected?void?onProgressUpdate(Integer...?progress)?{?
????????????Log.d(TAG,?"onProgressUpdate()");?
????????????tv.append("\nProgress:?"?+?progress[0]);?
????????}?
??
????????@Override?
????????protected?void?onPostExecute(Integer?result)?{?
????????????Log.d(TAG,?"onPostExecute()");?
????????????tv.append("\nFinished.?Result:?"?+?result);?
????????}?
??
????????@Override?
????????protected?void?onCancelled()?{?
????????????super.onCancelled();?
????????????Log.d(TAG,?"onCancelled()");
????????}
????}
}
?
轉載于:https://www.cnblogs.com/DswCnblog/archive/2012/11/12/2766871.html
總結
以上是生活随笔為你收集整理的Android AsyncTask简单用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 获取当前时间差
- 下一篇: 程序员到项目经理:从内而外的提升不看后悔