现在的位置: 首页 > 综合 > 正文

AsyncTask类与AsyncQueryHandler类的用法

2013年05月16日 ⁄ 综合 ⁄ 共 4549字 ⁄ 字号 评论关闭

AsyncTask Android
1.5
提供了一个工具类,它使创建需要与用户界面交互的长时间

运行的任务变得更简单。相对来说AsyncTask更轻量级一些,适用于简单的异步处理,

不需要借助线程和Handler即可实现。

 

AsyncTask是抽象类.AsyncTask定义了三种泛型类型 ParamsProgressResult

Params 启动任务执行的输入参数,比如HTTP请求的URL

Progress 后台任务执行的百分比。

Result 后台执行任务最终返回的结果,比如String

 

AsyncTask的执行分为四个步骤,每一步都对应一个回调方法,这些方法不应该由应用

程序调用,开发者需要做的就是实现这些方法。

  1) 子类化AsyncTask

  2) 实现AsyncTask中定义的下面一个或几个方法

 ①onPreExecute(), 该方法将在执行实际的后台操作前被UI
thread
调用。可以在该

方法中做一些准备工作,如在界面上显示一个进度条。

    doInBackground(Params...), 将在onPreExecute 方法执行后马上执行,该方法运行

在后台线程中。这里将主要负责执行那些很耗时的后台计算工作。可以调用 publishProgress方法来更新实时的任务进度。该方法是抽象方法,子类必须实现。

    onProgressUpdate(Progress...),publishProgress方法被调用后,UI
thread
将调用这

个方法从而在界面上展示任务的进展情况,例如通过一个进度条进行展示。

    onPostExecute(Result), doInBackground 执行完成后,onPostExecute 方法将被

UI thread调用,后台的计算结果将通过该方法传递到UI thread.

 

四.为了正确的使用AsyncTask类,以下是几条必须遵守的准则:

  1) Task的实例必须在UI
thread
中创建

  2) execute方法必须在UI
thread
中调用

3) 不要手动的调用onPreExecute(), onPostExecute(Result)doInBackground(Params...),

onProgressUpdate(Progress...)这几个方法

  4) task只能被执行一次,否则多次调用时将会出现异常

        doInBackground方法和onPostExecute的参数必须对应,这两个参数在AsyncTask

声明的泛型参数列表中指定,第一个为doInBackground接受的参数,第二个为显示进度的参数,第三个为doInBackground返回和onPostExecute传入的参数。

 

 例:

package test.list;

import java.io.ByteArrayOutputStream;

import java.io.InputStream;

import java.util.ArrayList;

 

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

 

import android.app.Activity;

import android.app.ProgressDialog;

import android.content.Context;

import android.content.DialogInterface;

import android.os.AsyncTask;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

 

public class NetworkActivity extends Activity{

    private TextView message;

    private Button open;

    private EditText url;

 

    @Override

    public void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.network);

       message= (TextView) findViewById(R.id.message);

       url= (EditText) findViewById(R.id.url);

       open= (Button) findViewById(R.id.open);

       open.setOnClickListener(new View.OnClickListener() {

           public void onClick(View arg0) {

              connect();

           }

       });

 

    }

 

    private void connect() {

        PageTask task = new PageTask(this);

        task.execute(url.getText().toString());

    }

 

 

    class PageTask extends AsyncTask {

        // 可变长的输入参数,与AsyncTask.exucute()对应

        ProgressDialog pdialog;

        public PageTask(Context context){

            pdialog = new ProgressDialog(context, 0);  

            pdialog.setButton("cancel", new DialogInterface.OnClickListener() {

             public void onClick(DialogInterface dialog, int i) {

              dialog.cancel();

             }

            });

            pdialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

             public void onCancel(DialogInterface dialog) {

              finish();

             }

            });

            pdialog.setCancelable(true);

            pdialog.setMax(100);

            pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

            pdialog.show();

 

 

        }

        @Override

        protected String doInBackground(String... params) {

 

            try{

 

               HttpClient client = new DefaultHttpClient();

               // params[0]代表连接的url

               HttpGet get = new HttpGet(params[0]);

               HttpResponse response = client.execute(get);

               HttpEntity entity = response.getEntity();

               long length = entity.getContentLength();

               InputStream is = entity.getContent();

               String s = null;

               if(is != null) {

                   ByteArrayOutputStream baos =
new ByteArrayOutputStream();

 

                   byte[] buf = new byte[128];

 

                   int ch = -1;

 

                   int count = 0;

 

                   while((ch = is.read(buf)) !=
-1) {

 

                      baos.write(buf,
0, ch);

 

                      count += ch;

 

                      if(length
> 0) {

                          // 如果知道响应的长度,调用publishProgress()更新进度

                          publishProgress((int)
((count / (float) length) * 100));

                      }

 

                      // 让线程休眠100ms

                      Thread.sleep(100);

                   }

                   s = new String(baos.toByteArray());              }

               // 返回结果

               return s;

            } catch(Exception
e) {

               e.printStackTrace();

 

            }

 

            return null;

 

        }

抱歉!评论已关闭.