概述:每個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:
- 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);
- // }
- // });
- }
- };
- }
main.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">
- <Button android:id="@+id/button" android:text="@string/button_name" 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>
strings.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">
- <Button android:id="@+id/button" android:text="@string/button_name" 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>
Manifest.xml:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.zhuozhuo"
- android:versionCode="1"
- android:versionName="1.0">
- <uses-sdk android:minSdkVersion="9" />
- <uses-permission android:name="android.permission.INTERNET"></uses-permission><!--不要忘記設置網絡訪問權限-->
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name=".ThreadHandlerActivity"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- </manifest>
運行結果:
爲了不阻塞ui線程,我們使用mThread從網絡獲取了CSDN的LOGO
,並用bitmap對象存儲了這個Logo的像素信息。
此時,如果在這個線程的run()方法中調用
- mImageView.setImageBitmap(bm)
會出現:CalledFromWrongThreadException:only the original thread that created a view hierarchy can touch its views。原因是run()方法是在新開的線程中執行的,我們上面提到不能直接在非ui線程中操作ui元素。
非UI線程發送消息到UI線程分爲兩個步驟
一、發送消息到UI線程的消息隊列
通過使用Handler的
- Message obtainMessage(int what,Object object)
構造一個Message對象,這個對象存儲了是否成功獲取圖片的標識what和bitmap對象,然後通過message.sendToTarget()方法把這條message放到消息隊列中去。
二、處理髮送到UI線程的消息
在ui線程中,我們覆蓋了handler的
- public void handleMessage (Message msg)
這個方法是處理分發給ui線程的消息,判斷msg.what的值可以知道mThread是否成功獲取圖片,如果圖片成功獲取,那麼可以通過msg.obj獲取到這個對象。
最後,我們通過
- mImageView.setImageBitmap((Bitmap) msg.obj);
設置ImageView的bitmap對象,完成UI的更新。
補充:
事實上,我們還可以調用
View的post方法來更新ui
- mImageView.post(new Runnable() {//另外一種更簡潔的發送消息給ui線程的方法。
- @Override
- public void run() {//run()方法會在ui線程執行
- mImageView.setImageBitmap(bm);
- }
- });
這種方法會把Runnable對象發送到消息隊列,ui線程接收到消息後會執行這個runnable對象。
從例子中我們可以看到handler既有發送消息和處理消息的作用,會誤以爲handler實現了消息循環和消息分發,其實Android爲了讓我們的代碼看起來更加簡潔,與UI線程的交互只需要使用在UI線程創建的handler對象就可以了。