asyncqueryhandler和asynctask

AsyncTask类

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

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

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



二.AsyncTask是抽象类.AsyncTask定义了三种泛型类型 Params,Progress和Result。

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;



        }



        @Override

        protected void onCancelled() {

            super.onCancelled();

        }



        @Override

        protected void onPostExecute(String result) {

            // 返回HTML页面的内容

            message.setText(result);

            pdialog.dismiss();

        }



        @Override

        protected void onPreExecute() {

            // 任务启动,可以在这里显示一个对话框,这里简单处理

            message.setText(R.string.task_started);

        }



        @Override

        protected void onProgressUpdate(Integer... values) {

            // 更新进度

              System.out.println(""+values[0]);

              message.setText(""+values[0]);

              pdialog.setProgress(values[0]);

        }



     }



}

 

AsyncQueryHandler类

一.AsyncQueryHandler:异步的查询操作帮助类,它可以处理增删改查。



二.AsyncQueryHandler的作用:它提供:

startInsert,startDelete,startUpdate,startQuery这四个操作,并提供相对应的onInsertComplete,onDeleteComplete,onUpdateComplete,onQuerytComplete四个方法,以供操作完数据库后进行其它的操作,这四个 onXXXComplete方法都是空实现,以便我们只需要去实现我们关注的操作。



三.AsyncQueryHandler的使用方法:

1)需要继承AsyncQueryHandler类,并提供onInsertComplete方法的实现(可以实现任何一个或多个,当然你也可以一个也不实现,如果你不关注操作数据库的結果),在你的实现中做一些对数据库操作完成的处理。

2)使用时直接调用startQuery(或者其他四个中的任何一个)方法即可。传入的通用参数如下:

①token,一个令牌,需要跟onQueryComplete方法传入的一致。(当然你也可以不一

致,同样在数据库的操作结束后会调用对应的onQueryComplete方法 )。

②cookie,你想传给onQueryComplete方法使用的一个对象。(没有的话传递null即可)。

    ③Uri uri(进行查询的通用资源标志符)。

    ④projection 查询的列

    ⑤selection  限制条件

    ⑥orderBy 排序条件





猜你喜欢

转载自362429377-qq-com.iteye.com/blog/2280554