2025-05-24

概述:每個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     };
75     
76 }

main.xml佈局文件:
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3     android:orientation="vertical" android:layout_width="fill_parent"
4     android:layout_height="fill_parent">
5     <Button android:id="@+id/button" android:text="@string/button_name"android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
6     <ImageView android:id="@+id/imageView" android:layout_height="wrap_content"
7         android:layout_width="wrap_content" />
8 </LinearLayout>

strings.xml
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3     android:orientation="vertical" android:layout_width="fill_parent"
4     android:layout_height="fill_parent">
5     <Button android:id="@+id/button" android:text="@string/button_name"android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
6     <ImageView android:id="@+id/imageView" android:layout_height="wrap_content"
7         android:layout_width="wrap_content" />
8 </LinearLayout>

Manifest.xml:
01 <?xml version="1.0" encoding="utf-8"?>
02 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
03       package="com.zhuozhuo"
04       android:versionCode="1"
05       android:versionName="1.0">
06     <uses-sdk android:minSdkVersion="9" />
07     <uses-permission android:name="android.permission.INTERNET"></uses-permission><!–不要忘記設置網絡訪問權限–>
08 
09     <application android:icon="@drawable/icon" android:label="@string/app_name">
10         <activity android:name=".ThreadHandlerActivity"
11                   android:label="@string/app_name">
12             <intent-filter>
13                 <action android:name="android.intent.action.MAIN" />
14                 <category android:name="android.intent.category.LAUNCHER" />
15             </intent-filter>
16         </activity>
17 
18     </application>
19 </manifest>

運行結果:
 
 

 
為瞭不阻塞ui線程,我們使用mThread從網絡獲取瞭CSDN的LOGO
,並用bitmap對象存儲瞭這個Logo的像素信息。
此時,如果在這個線程的run()方法中調用
1 mImageView.setImageBitmap(bm)
 
會出現:CalledFromWrongThreadException:only the original thread that created a view hierarchy can touch its views。原因是run()方法是在新開的線程中執行的,我們上面提到不能直接在非ui線程中操作ui元素。
非UI線程發送消息到UI線程分為兩個步驟
一、發送消息到UI線程的消息隊列
通過使用Handler的
1 Message obtainMessage(int what,Object object)

構造一個Message對象,這個對象存儲瞭是否成功獲取圖片的標識what和bitmap對象,然後通過message.sendToTarget()方法把這條message放到消息隊列中去。
二、處理發送到UI線程的消息
在ui線程中,我們覆蓋瞭handler的
1 public void handleMessage (Message msg)
這個方法是處理分發給ui線程的消息,判斷msg.what的值可以知道mThread是否成功獲取圖片,如果圖片成功獲取,那麼可以通過msg.obj獲取到這個對象。
最後,我們通過
1 mImageView.setImageBitmap((Bitmap) msg.obj);
設置ImageView的bitmap對象,完成UI的更新。

補充:
事實上,我們還可以調用
View的post方法來更新ui
1 mImageView.post(new Runnable() {//另外一種更簡潔的發送消息給ui線程的方法。
2                 
3                 @Override
4                 public void run() {//run()方法會在ui線程執行
5                     mImageView.setImageBitmap(bm);
6                 }
7             });

這種方法會把Runnable對象發送到消息隊列,ui線程接收到消息後會執行這個runnable對象。
從例子中我們可以看到handler既有發送消息和處理消息的作用,會誤以為handler實現瞭消息循環和消息分發,其實Android為瞭讓我們的代碼看起來更加簡潔,與UI線程的交互隻需要使用在UI線程創建的handler對象就可以瞭。如需深入學習,瞭解消息循環機制的具體實現,請關註《Android異步處理三:Handler+Looper+MessageQueue深入詳解》

摘自  lzc的專欄

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *