Android中子線程和UI線程之間通訊的詳細解釋
1.在多線程編程這塊,我們經常要使用Handler,Thread和Runnable這三個類,那麼他們之間的關係你是否弄清楚了呢?下面詳解一下。
2.首先在開發Android應用時必須遵守單執行緒模式的原則:
Android UI操作並不是安全執行緒的並且這些操作必須在UI線程中執行。
3.Handler:
(1).概念:
Handler是溝通Activity 與Thread/runnable的橋樑。而Handler是運行在主UI線程中的,它與子線程可以通過Message對象來傳遞資料。
(2).使用:
A:Handler是運行在UI線程中,主要接收子線程發送的資料資訊, 並用此資料配合主線程更新UI,用來跟UI主線程互動用。比如可以用handler發送一個message,然後在handler的線程中來接收、處理該訊息。
B:訊息的處理者。通過Handler對象我們可以封裝Message對象,然後通過sendMessage(msg)把Message對象添加到MessageQueue中;當MessageQueue迴圈到該Message時,就會調用該Message對象對應的handler對象的handleMessage()方法對其進行處理。
C:Handler可以分發Runnable對象,也可以分發Message對象。
4.Message:
訊息對象,顧名思義就是記錄訊息資訊的類。也就是說是資訊的載體,存放資訊內容。這個類有幾個比較重要的欄位:
(1).arg1和arg2:我們可以使用兩個欄位用來存放我們需要傳遞的整型值,在Service中,我們可以用來存放Service的ID。
(2).obj:該欄位是Object類型,我們可以讓該欄位傳遞某個對象到訊息的接受者中。
(3).what:這個欄位可以說是訊息的標誌,判斷是接收了哪個訊息。在訊息處理中,我們可以根據這個欄位的不同的值進行不同的處理,類似於我們在處理Button事件時,通過switch(v.getId())判斷是點擊了哪個按鈕。
Android推薦通過Message.obtain()或者Handler.obtainMessage()擷取Message對象。這並不一定是直接建立一個新的執行個體,而是先從訊息池中看有沒有可用的Message執行個體,存在則直接取出並返回這個執行個體。反之如果訊息池中沒有可用的Message執行個體,則根據給定的參數new一個新Message對象。通過分析源碼可得知,Android系統預設情況下在訊息池中執行個體化10個Message對象。
5.源碼展示:
(1).activity_main.xml布局檔案:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="自訂Thread繼承Thread" /> <Button android:id="@+id/btn2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="自訂Runnable實現Runnable" /> <Button android:id="@+id/btn3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="定時更新UI介面,Handler分發Runnable對象" /> <Button android:id="@+id/btn4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="定時更新UI介面,Handler分發Message對象" /> <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="0" /></LinearLayout>
(2).MainActivity.java
package com.chengdong.su.threaddemo;import com.chengdong.su.threaddemo.util.MyRunnable;import com.chengdong.su.threaddemo.util.MyThread;import android.R.integer;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity implements OnClickListener { /** TAG */ private final String TAG = getClass().getSimpleName(); /** the object of the button */ private Button mButton; /** the object of the button */ private Button mButton2; /** the object of the button */ private Button mButton3; /** the object of the button */ private Button mButton4; /** the object of the TextView */ private TextView mTextView; /** 計數 */ private int mCount = 0; /** 標誌 */ private int MESSAGE_FLAG = 1; /** * Handler分發Runnable對象的方式 */ private Handler mHandler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { mCount++; mHandler.postDelayed(runnable, 1000); mTextView.setText(mCount + ""); } }; /*** * Handler分發Message對象的方式 */ Handler mHandler2 = new Handler() { public void handleMessage(android.os.Message msg) { if (msg.what == 1) { mTextView.setText("Handler分發Message對象的方式"); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } /** * 初始化組件對象 */ private void initView() { mButton = (Button) findViewById(R.id.btn); mButton2 = (Button) findViewById(R.id.btn2); mButton3 = (Button) findViewById(R.id.btn3); mButton4 = (Button) findViewById(R.id.btn4); mButton.setOnClickListener(this); mButton2.setOnClickListener(this); mButton3.setOnClickListener(this); mButton4.setOnClickListener(this); mTextView = (TextView) findViewById(R.id.tv); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn: { // 方法一:繼承的方式:自訂Thread繼承Thread,開啟一個新的線程 new MyThread().start(); break; } case R.id.btn2: { // 方法二:實現的方式:implement Runnable new Thread(new MyRunnable()).start(); break; } // 方法三:handler分發Runnable對象:定時更新UI介面 提交計劃任務馬上執行 case R.id.btn3: { // Handler分發Runnable對象 mHandler.post(runnable); break; } // 方法四:Handler分發Message對象 ,定時更新UI介面 提交計劃任務馬上執行 case R.id.btn4: { // 不推薦這種方式 // Message msg = new Message(); // 推薦使用這種擷取對象的方式:從訊息池中獲得可用的Message對象 Message msg = Message.obtain(); msg.what = MESSAGE_FLAG; mHandler2.sendMessage(msg); break; } default: break; } }}
(3).MyRunnable.java
package com.chengdong.su.threaddemo.util;import android.util.Log;/*** * 自訂一個MyRunnable線程 * * @author scd * */public class MyRunnable implements Runnable { public MyRunnable() { super(); } /** TAG */ private final String TAG = getClass().getSimpleName(); @Override public void run() { for (int i = 0; i < 20; i++) { Log.e(TAG, Thread.currentThread().getName() + ",實現的方法" + i); } }}
(4)MyThread.java
package com.chengdong.su.threaddemo.util;import android.util.Log;/*** * 自訂一個線程 * * @author scd * */public class MyThread extends Thread { public MyThread() { super(); } /** TAG */ private final String TAG = getClass().getSimpleName(); @Override public void run() { super.run(); for (int i = 0; i < 10; i++) { Log.e(TAG, Thread.currentThread().getName() + ",繼承Thread類:" + i); } }}