当前位置:操作系统 > 安卓/Android >>

Android异步处理一:使用Thread+Handler实现非UI线程更新UI界面

概述:每个Android应用程序都运行在一个dalvik虚拟机进程中,进程开始的时候会启动一个主线程(MainThread),主线程负责处理和ui相关的事件,因此主线程通常又叫UI线程。而由于Android采用UI单线程模型,所以只能在主线程中对UI元素进行操作。如果在非UI线程直接对UI进行了操作,则会报错:
CalledFromWrongThreadException:only the original thread that created a view hierarchy can touch its views

Android为我们提供了消息循环的机制,我们可以利用这个机制来实现线程间的通信。那么,我们就可以在非UI线程发送消息到UI线程,最终让Ui线程来进行ui的操作。
对于运算量较大的操作和IO操作,我们需要新开线程来处理这些繁重的工作,以免阻塞ui线程。
例子:下面我们以获取CSDN logo的例子,演示如何使用Thread+Handler的方式实现在非UI线程发送消息通知UI线程更新界面。
ThradHandlerActivity.java:
01 public class ThreadHandlerActivity extends Activity {
02     /** Called when the activity is first created. */
03     
04     private static final int MSG_SUCCESS = 0;//获取图片成功的标识
05     private static final int MSG_FAILURE = 1;//获取图片失败的标识
06     
07     private ImageView mImageView;
08     private Button mButton;
09     
10     private Thread mThread;
11     
12     private Handler mHandler = new Handler() {
13         public void handleMessage (Message msg) {//此方法在ui线程运行
14             switch(msg.what) {
15             case MSG_SUCCESS:
16                 mImageView.setImageBitmap((Bitmap) msg.obj);//imageview显示从网络获取到的logo
17                 Toast.makeText(getApplication(), getApplication().getString(R.string.get_pic_success), Toast.LENGTH_LONG).show();
18                 break;
19 
20             case MSG_FAILURE:
21                 Toast.makeText(getApplication(), getApplication().getString(R.string.get_pic_failure), Toast.LENGTH_LONG).show();
22                 break;
23             }
24         }
25     };
26     
27     @Override
28     public void onCreate(Bundle savedInstanceState) {
29         super.onCreate(savedInstanceState);
30         setContentView(R.layout.main);
31         mImageView= (ImageView) findViewById(R.id.imageView);//显示图片的ImageView
32         mButton = (Button) findViewById(R.id.button);
33         mButton.setOnClickListener(new OnClickListener() {
34             
35             @Override
36             public void onClick(View v) {
37                 if(mThread == null) {
38                     mThread = new Thread(runnable);
39                     mThread.start();//线程启动
40                 }
41                 else {
42                     Toast.makeText(getApplication(), getApplication().getString(R.string.thread_started), Toast.LENGTH_LONG).show();
43                 }
44             }
45         });
46     }
47     
48     Runnable runnable = new Runnable() {
49         
50         @Override
51         public void run() {//run()在新的线程中运行
52             HttpClient hc = new DefaultHttpClient();
53             HttpGet hg = new HttpGet("http://csdnimg.cn/www/images/csdnindex_logo.gif");//获取csdn的logo
54             final Bitmap bm;
55             try {
56                 HttpResponse hr = hc.execute(hg);
57                 bm = BitmapFactory.decodeStream(hr.getEntity().getContent());
58             } catch (Exception e) {
59                 mHandler.obtainMessage(MSG_FAILURE).sendToTarget();//获取图片失败
60                 return;
61             }
62             mHandler.obtainMessage(MSG_SUCCESS,bm).sendToTarget();//获取图片成功,向ui线程发送MSG_SUCCESS标识和bitmap对象
63 
64 //          mImageView.setImageBitmap(bm); //出错!不能在非ui线程操作ui元素
65 
66 //          mImageView.post(new Runnable() {//另外一种更简洁的发送消息给ui线程的方法。
67 //            
68 //              @Override
69 //              public void run() {//run()方易做图在ui线程执行
70 //                  mImageView.setImageBitmap(bm);
71 //              }
72 //          });
73         }
74&

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,