Android AsyncTask的用法

来源:互联网 发布:sql存储过程详细说明 编辑:程序博客网 时间:2024/05/01 00:25
package com.sean.demo.asynctask;import android.app.Activity;import android.app.ProgressDialog;import android.content.Context;import android.os.AsyncTask;import android.os.Bundle;import android.util.Log;public class AsyncTaskDemoActivity extends Activity {private static final String TAG = "INFO";    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                MyAsyncTask task = new MyAsyncTask(this);        task.execute("Message");            }        class MyAsyncTask extends AsyncTask<String, Integer, String>{    //An asynchronous task is defined by 3 generic types, called Params, Progress and Result        //进度框        ProgressDialog pdialog;public MyAsyncTask(Context context) {// 构造函数pdialog = new ProgressDialog(context, 0);pdialog.setMax(100);pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);pdialog.show();}@Overrideprotected String doInBackground(String... params) {// 将在onPreExecute 方法执行后马上执行,该方法运行在后台线程中。// 这里将主要负责执行那些很耗时的后台计算工作。// 可以调用 publishProgress方法来更新实时的任务进度。// 该方法是抽象方法,子类必须实现。 Log.i(TAG,"doInBackground");try {Log.i(TAG,params[0]);//进度条控制for(int count=0;count<100;count++){publishProgress((int) ((count / (float)100) * 100));Thread.sleep(10);}} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}return params[0]+" result";//返回处理完成的结果。}@Overrideprotected void onCancelled() {// TODO Auto-generated method stubsuper.onCancelled();}@Overrideprotected void onPostExecute(String result) {// 在doInBackground 执行完成后,onPostExecute 方法将被UI thread调用,// 后台的计算结果将通过该方法传递到UI thread. super.onPostExecute(result);            pdialog.dismiss(); Log.i(TAG,"onPostExecute");Log.i(TAG,result);//这里显示的是Message result}@Overrideprotected void onPreExecute() {// 在执行doInBackground前被主线程调用。super.onPreExecute();Log.i(TAG,"onPreExecute");}@Overrideprotected void onProgressUpdate(Integer... values) {// 在publishProgress方法被调用后,// UI thread将调用这个方法从而在界面上展示任务的进展情况,例如通过一个进度条进行展示。 super.onProgressUpdate(values);pdialog.setProgress(values[0]);}        }}


AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, calledParams, Progress and Result, and 4 steps, calledonPreExecute, doInBackground, onProgressUpdate andonPostExecute.


原创粉丝点击