Android非同步處理一:使用Thread+Handler實現非UI線程更新UI介面

來源:互聯網
上載者:User

概述:每個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
,並用bitmapObject Storage Service了這個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對象,這個Object Storage Service了是否成功擷取圖片的標識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的專欄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.