AsyncTask主要用來更新UI線程,比較耗時的操作可以在AsyncTask中使用。
AsyncTask是個抽象類,使用時需要繼承這個類,然後調用execute()方法。注意繼承時需要設定三個泛型Params,Progress和Result的類型,如AsyncTask<Void,Inetger,Void>:
- Params是指調用execute()方法時傳入的參數類型和doInBackgound()的參數類型
- Progress是指更新進度時傳遞的參數類型,即publishProgress()和onProgressUpdate()的參數類型
- Result是指doInBackground()的返回值類型
上面的說明涉及到幾個方法:
- doInBackgound() 這個方法是繼承AsyncTask必須要實現的,運行於後臺,耗時的操作可以在這裏做
- publishProgress() 更新進度,給onProgressUpdate()傳遞進度參數
- onProgressUpdate() 在publishProgress()調用完被調用,更新進度
好了,看下實際的例子,瞭解一下怎麼使用吧:
- public class MyActivity extends Activity
- {
- private Button btn;
- private TextView tv;
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- btn = (Button) findViewById(R.id.start_btn);
- tv = (TextView) findViewById(R.id.content);
- btn.setOnClickListener(new Button.OnClickListener(){
- public void onClick(View v) {
- update();
- }
- });
- }
- private void update(){
- UpdateTextTask updateTextTask = new UpdateTextTask(this);
- updateTextTask.execute();
- }
- class UpdateTextTask extends AsyncTask<Void,Integer,Integer>{
- private Context context;
- UpdateTextTask(Context context) {
- this.context = context;
- }
- /**
- * 運行在UI線程中,在調用doInBackground()之前執行
- */
- @Override
- protected void onPreExecute() {
- Toast.makeText(context,"開始執行",Toast.LENGTH_SHORT).show();
- }
- /**
- * 後臺運行的方法,可以運行非UI線程,可以執行耗時的方法
- */
- @Override
- protected Integer doInBackground(Void... params) {
- int i=0;
- while(i<10){
- i++;
- publishProgress(i);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- }
- }
- return null;
- }
- /**
- * 運行在ui線程中,在doInBackground()執行完畢後執行
- */
- @Override
- protected void onPostExecute(Integer integer) {
- Toast.makeText(context,"執行完畢",Toast.LENGTH_SHORT).show();
- }
- /**
- * 在publishProgress()被調用以後執行,publishProgress()用於更新進度
- */
- @Override
- protected void onProgressUpdate(Integer... values) {
- tv.setText(""+values[0]);
- }
- }
- }