標籤:
1.Android制定了一條簡單的原則:只允許UI線程(亦即主線程)修改Activity中的UI組件。當一個程式第一次啟動時,Android會同時啟動一條主線程,主線程主要負責處理與UI相關的事件,如使用者的按鍵事件、使用者接觸螢幕的事件、螢幕繪圖事件,並把相關的事件分發到相應的組件進行處理,所以主線程通常又叫做UI線程。Handler存在的意義就是一個訊息機制, 可以在一個線程中建立並在另一個線程中觸發2.Handler的作用:
- (1)在一個線程中發送訊息。
- (2)在另一個線程中擷取、處理訊息。
3.Handler類包含如下方法用於發送、處理訊息(這裡只列出了常用的部分,還有更多可以自己去找):
- ? void handlerMessage(Message msg):處理訊息的方法,該方法通常用於被重寫。
- ? final boolean hasMessage(int what):檢查訊息佇列中是否包含what屬性為指定值的訊息。
- ? sendEmptyMessage(int what):發送空訊息
- ? final boolean sendMessage(Message msg):立即發送訊息,注意這塊傳回值,如果message成功的被放到message queue裡面則返回true,反之,返回false;
4.在被調用線程中完成以下內容:(1)調用 Looper的prepare()方法為當前線程建立Looper對象,建立Looper對象時,它的構造器會建立與之配套的MessageQueue。(2)有了Looper之後,建立Handler子類的執行個體,重寫HandlerMessage()方法,該方法負責處理來自其它線程的訊息。(3)調用Looper的loop()方法啟動Looper。註:若被調用線程是主線程類,由於系統自動為主線程建立了Looper的執行個體,因此第一、三步驟可省略,而只需要做第2步即可。在調用線程中完成:(1)建立message,並填充內容。(2)使用被調用類建立的Handler執行個體,調用sendMessage(Message msg)方法。5.下面這個例子是Handler在主線程中擷取,處理訊息,在子線程中發送訊息,這個例子handler寫在主線程中。main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.dragon.testfuction.Main"> <ImageView android:id="@+id/show" android:layout_width="wrap_content" android:layout_height="wrap_content" /></RelativeLayout>
main.java
package com.dragon.testfuction;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.Toast;import java.util.Timer;import java.util.TimerTask;public class Main extends AppCompatActivity {// 定義圖片顯示ID int[] imageIds = new int[]{ R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.four }; int currentImageId = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final ImageView show = (ImageView) findViewById(R.id.show); final Handler myHandler = new Handler(){ @Override public void handleMessage(Message msg){// 檢查訊息發送來源,如果是本程式發送的 if(msg.what == 0x1233){// 動態修改圖片 show.setImageResource(imageIds[currentImageId++%imageIds.length]); } } };//定義一個定時器,周期性的執行指定任務 new Timer().schedule(new TimerTask(){ @Override public void run(){ //在子線程中拿到父線程中建立的handle對象,通過該對象來向父線程的訊息佇列發送訊息(通過這種方式,可以在其它子線程中與主線程通訊來由UI線程更新介面) myHandler.sendEmptyMessage(0x1233); } },0,1200);}}
6。為避免ANR,應該在子線程中執行耗時較長的操作,而此操作完成後,有可能需要通知主線程修改UI。在子線程中執行耗時任務後,通知主線程修改UI組件的例子:使用新進程計算質數,並用Toast顯示這個例子是在主線程中發送訊息,在子線程中擷取,處理訊息(例子來自瘋狂java講義),這個例子handle寫在子線程中。main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.dragon.testfuction.Main"> <EditText android:id="@+id/etNum" android:inputType="number" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="please input upper number"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="cal" android:text="calculate"/></LinearLayout>
main.java
package com.dragon.testfuction;import android.os.Handler;import android.os.Looper;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.Toast;import java.util.ArrayList;import java.util.List;public class Main extends AppCompatActivity { static final String UPPER_NUM = "upper"; EditText etNum; CalThread calThread;// 定義一個線程類 class CalThread extends Thread { public Handler mHandler; public void run(){// 建立looper對象,每一個線程使用Handle都要有一個looper對象 Looper.prepare();// 子線程中定義handler擷取處理訊息 mHandler = new Handler(){// 定義處理資訊的方法 @Override public void handleMessage(Message msg){ if(msg.what == 0x123){ int upper = msg.getData().getInt(UPPER_NUM); List<Integer> nums = new ArrayList<Integer>(); outer:// 質數也是素數,除了1和它本身外,不能被其它整除 for(int i =2;i <=upper;i++){ for(int j=2; j<= Math.sqrt(i);j++){// 如果可以整除,說明不是質數 if(i!=2 && i%j==0){ continue outer; } } nums.add(i); }// 用Toast顯示所有統計出來的質數 Toast.makeText(Main.this,nums.toString(),Toast.LENGTH_LONG).show(); } } }; Looper.loop();//啟動looper } } @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); etNum = (EditText) findViewById(R.id.etNum); calThread = new CalThread(); calThread.start();//啟動新線程 }//按鈕事件點擊處理函數 public void cal(View source){// 建立訊息 Message msg = new Message(); msg.what = 0x123; Bundle bundle = new Bundle(); bundle.putInt(UPPER_NUM,Integer.parseInt(etNum.getText().toString())); msg.setData(bundle);// 在主線程中想新線程中的Handler發送訊息 calThread.mHandler.sendMessage(msg);//在主線程中發送訊息 }}
7.總結:
8.注意
- UI線程:就是我們的主線程,系統在建立UI線程的時候會初始化一個Looper對象,同時也會建立一個與其關聯的MessageQueue;
- Handler:作用就是發送與處理資訊,如果希望Handler正常工作,在當前線程中要有一個Looper對象
- Message:Handler接收與處理的訊息對象
- MessageQueue:訊息佇列,先進先出管理Message,在初始化Looper對象時會建立一個與之關聯的MessageQueue;
- Looper:每個線程只能夠有一個Looper,管理MessageQueue,不斷地從中取出Message分發給對應的Handler處理!
looper.prepare提供源碼如下:
/** Initialize the current thread as a looper. * This gives you a chance to create handlers that then reference * this looper, before actually starting the loop. Be sure to call * {@link #loop()} after calling this method, and end it by calling * {@link #quit()}. */ public static void prepare() { prepare(true); } private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); }
9.根據上面兩個例子,大家注意區分寫在主線程中和子線程中的區別,如有問題歡迎大家留言,另有從事AR原生開發的可以加入下面的群或是關注公眾號AR引路人。
Reference:
1.http://www.runoob.com/w3cnote/android-tutorial-handler-message.html
2.http://www.nljb.net/default/Android%E4%B9%8BHandler%E6%B6%88%E6%81%AF%E4%BC%A0%E9%80%92%E6%9C%BA%E5%88%B6%E4%BD%BF%E7%94%A8/
3.http://www.itmmd.com/201502/575.html
4.http://www.kancloud.cn/digest/tttkkk/125281
android studio for android learning (十九 ) 最新Handler訊息傳遞機制全解