android异步处理的几种方式
1,对数据库uri查询的异步方式----AsyncQueryHandler
示例
首先写一个AsyncQueryHandler继承类QueryHandler,然后
new一个mQueryHandler对象。查询完了之后会回调onQueryComplete函数,如下:

private void query() {  

            Uri uri = Sms.CONVESATION_URI;  

            mQueryHandler.startQuery(0, null, uri, CONVERSATION_PROJECTION, null, null, "sms.date desc");  

        }  

        // 写一个异步查询类  

        private final class QueryHandler extends AsyncQueryHandler {  

            public QueryHandler(ContentResolver cr) {  

                super(cr);  

            }  



            @Override  

            protected void onQueryComplete(int token, Object cookie, Cursor cursor) {  

                super.onQueryComplete(token, cookie, cursor);  

                // 更新mAdapter的Cursor  

                mAdapter.changeCursor(cursor);  

            }  

        }

2,使用Thread+Handler实现非UI线程更新UI界面

示例如下:

public class ThreadHandlerActivity extends Activity {  
        /** Called when the activity is first created. */  

        private static final int MSG_SUCCESS = 0;//获取图片成功的标识  
        private static final int MSG_FAILURE = 1;//获取图片失败的标识  

        private ImageView mImageView;  
        private Button mButton;  

        private Thread mThread;  

        private Handler mHandler = new Handler() {  
            public void handleMessage (Message msg) {//此方法在ui线程运行  
                switch(msg.what) {  
                case MSG_SUCCESS:  
                    mImageView.setImageBitmap((Bitmap) msg.obj);//imageview显示从网络获取到的logo  
                    Toast.makeText(getApplication(), getApplication().getString(R.string.get_pic_success), Toast.LENGTH_LONG).show();  
                    break;  

                case MSG_FAILURE:  
                    Toast.makeText(getApplication(), getApplication().getString(R.string.get_pic_failure), Toast.LENGTH_LONG).show();  
                    break;  
                }  
            }  
        };  

        @Override  
        public void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.main);  
            mImageView= (ImageView) findViewById(R.id.imageView);//显示图片的ImageView  
            mButton = (Button) findViewById(R.id.button);  
            mButton.setOnClickListener(new OnClickListener() {  

                @Override  
                public void onClick(View v) {  
                    if(mThread == null) {  
                        mThread = new Thread(runnable);  
                        mThread.start();//线程启动  
                    }  
                    else {  
                        Toast.makeText(getApplication(), getApplication().getString(R.string.thread_started), Toast.LENGTH_LONG).show();  
                    }  
                }  
            });  
        }  

        Runnable runnable = new Runnable() {  

            @Override  
            public void run() {//run()在新的线程中运行  
                HttpClient hc = new DefaultHttpClient();  
                HttpGet hg = new HttpGet("http://csdnimg.cn/www/images/csdnindex_logo.gif");//获取csdn的logo  
                final Bitmap bm;  
                try {  
                    HttpResponse hr = hc.execute(hg);  
                    bm = BitmapFactory.decodeStream(hr.getEntity().getContent());  
                } catch (Exception e) {  
                    mHandler.obtainMessage(MSG_FAILURE).sendToTarget();//获取图片失败  
                    return;  
                }  
                mHandler.obtainMessage(MSG_SUCCESS,bm).sendToTarget();//获取图片成功,向ui线程发送MSG_SUCCESS标识和bitmap对象  

    //          mImageView.setImageBitmap(bm); //出错!不能在非ui线程操作ui元素  

    //          mImageView.post(new Runnable() {//另外一种更简洁的发送消息给ui线程的方法。  
    //                
    //              @Override  
    //              public void run() {//run()方法会在ui线程执行  
    //                  mImageView.setImageBitmap(bm);  
    //              }  
    //          });  
            }  
        };  

    }

3,使用AsyncTask异步更新UI界面

AsyncTask抽象出后台线程运行的五个状态,分别是:1、准备运行,2、正在后台运行,3、进度更新,4、完成后台任务,5、取消任务,对于这五个阶段,AsyncTask提供了五个回调函数:

1、准备运行:onPreExecute(),该回调函数在任务被执行之后立即由UI线程调用。这个步骤通常用来建立任务,在用户接口(UI)上显示进度条。

2、正在后台运行:doInBackground(Params...),该回调函数由后台线程在onPreExecute()方法执行结束后立即调用。通常在这里执行耗时的后台计算。计算的结果必须由该函数返回,并被传递到onPostExecute()中。在该函数内也可以使用publishProgress(Progress...)来发布一个或多个进度单位(unitsof progress)。这些值将会在onProgressUpdate(Progress...)中被发布到UI线程。

3. 进度更新:onProgressUpdate(Progress...),该函数由UI线程在publishProgress(Progress...)方法调用完后被调用。一般用于动态地显示一个进度条。

4. 完成后台任务:onPostExecute(Result),当后台计算结束后调用。后台计算的结果会被作为参数传递给这一函数。

5、取消任务:onCancelled (),在调用AsyncTask的cancel()方法时调用


示例代码:

public class AsyncTaskActivity extends Activity {  

    private ImageView mImageView;  
    private Button mButton;  
    private ProgressBar mProgressBar;  

    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  

        mImageView= (ImageView) findViewById(R.id.imageView);  
        mButton = (Button) findViewById(R.id.button);  
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);  
        mButton.setOnClickListener(new OnClickListener() {  

            @Override  
            public void onClick(View v) {  
                GetCSDNLogoTask task = new GetCSDNLogoTask();  
                task.execute("http://csdnimg.cn/www/images/csdnindex_logo.gif");  
            }  
        });  
    }  

    class GetCSDNLogoTask extends AsyncTask<String,Integer,Bitmap> {//继承AsyncTask  

        @Override  
        protected Bitmap doInBackground(String... params) {//处理后台执行的任务,在后台线程执行  
            publishProgress(0);//将会调用onProgressUpdate(Integer... progress)方法  
            HttpClient hc = new DefaultHttpClient();  
            publishProgress(30);  
            HttpGet hg = new HttpGet(params[0]);//获取csdn的logo  
            final Bitmap bm;  
            try {  
                HttpResponse hr = hc.execute(hg);  
                bm = BitmapFactory.decodeStream(hr.getEntity().getContent());  
            } catch (Exception e) {  

                return null;  
            }  
            publishProgress(100);  
            //mImageView.setImageBitmap(result); 不能在后台线程操作ui  
            return bm;  
        }  

        protected void onProgressUpdate(Integer... progress) {//在调用publishProgress之后被调用,在ui线程执行  
            mProgressBar.setProgress(progress[0]);//更新进度条的进度  
         }  

         protected void onPostExecute(Bitmap result) {//后台任务执行完之后被调用,在ui线程执行  
             if(result != null) {  
                 Toast.makeText(AsyncTaskActivity.this, "成功获取图片", Toast.LENGTH_LONG).show();  
                 mImageView.setImageBitmap(result);  
             }else {  
                 Toast.makeText(AsyncTaskActivity.this, "获取图片失败", Toast.LENGTH_LONG).show();  
             }  
         }  

         protected void onPreExecute () {//在 doInBackground(Params...)之前被调用,在ui线程执行  
             mImageView.setImageBitmap(null);  
             mProgressBar.setProgress(0);//进度条复位  
         }  

         protected void onCancelled () {//在ui线程执行  
             mProgressBar.setProgress(0);//进度条复位  
         }  

    }  


}

下面是对应的xml

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical" android:layout_width="fill_parent"  
    android:layout_height="fill_parent">  
    <ProgressBar android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/progressBar" style="?android:attr/progressBarStyleHorizontal"></ProgressBar>  
    <Button android:id="@+id/button" android:text="下载图片" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>  
    <ImageView android:id="@+id/imageView" android:layout_height="wrap_content"  
        android:layout_width="wrap_content" />  
</LinearLayout>