最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android Handler 原理分析及實(shí)例代碼

 更新時(shí)間:2017年02月04日 11:48:32   投稿:lqh  
這篇文章主要介紹了Android Handler 原理分析及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下

Android Handler 原理分析

Handler一個(gè)讓無(wú)數(shù)android開發(fā)者頭疼的東西,希望我今天這邊文章能為您徹底根治這個(gè)問(wèn)題

今天就為大家詳細(xì)剖析下Handler的原理

Handler使用的原因

1.多線程更新Ui會(huì)導(dǎo)致UI界面錯(cuò)亂
2.如果加鎖會(huì)導(dǎo)致性能下降
3.只在主線程去更新UI,輪詢處理

Handler使用簡(jiǎn)介

其實(shí)關(guān)鍵方法就2個(gè)一個(gè)sendMessage,用來(lái)接收消息

另一個(gè)是handleMessage,用來(lái)處理接收到的消息

下面是我參考瘋狂android講義,寫的一個(gè)子線程和主線程之間相互通信的demo

對(duì)原demo做了一定修改

public class MainActivity extends AppCompatActivity { 
  public final static String UPPER_NUM="upper_num"; 
  private EditText editText; 
  public jisuanThread jisuan; 
  public Handler mainhandler; 
  private TextView textView; 
  class jisuanThread extends Thread{ 
    public Handler mhandler; 
    @Override 
    public void run() { 
      Looper.prepare(); 
      final ArrayList<Integer> al=new ArrayList<>(); 
      mhandler=new Handler(){ 
        @Override 
        public void handleMessage(Message msg) { 
 
          if(msg.what==0x123){ 
            Bundle bundle=msg.getData(); 
            int up=bundle.getInt(UPPER_NUM); 
            outer: 
            for(int i=3;i<=up;i++){ 
              for(int j=2;j<=Math.sqrt(i);j++){ 
                if(i%j==0){ 
                  continue outer; 
                } 
              } 
              al.add(i); 
            } 
            Message message=new Message(); 
            message.what=0x124; 
            Bundle bundle1=new Bundle(); 
            bundle1.putIntegerArrayList("Result",al); 
            message.setData(bundle1); 
            mainhandler.sendMessage(message); 
          } 
        } 
      }; 
      Looper.loop(); 
    } 
  } 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    editText= (EditText) findViewById(R.id.et_num); 
    textView= (TextView) findViewById(R.id.tv_show); 
    jisuan=new jisuanThread(); 
    jisuan.start(); 
    mainhandler=new Handler(){ 
      @Override 
      public void handleMessage(Message msg) { 
        if(msg.what==0x124){ 
          Bundle bundle=new Bundle(); 
          bundle=msg.getData(); 
          ArrayList<Integer> al=bundle.getIntegerArrayList("Result"); 
          textView.setText(al.toString()); 
        } 
      } 
    }; 
    findViewById(R.id.bt_jisuan).setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
        Message message=new Message(); 
        message.what=0x123; 
        Bundle bundle=new Bundle(); 
        bundle.putInt(UPPER_NUM, Integer.parseInt(editText.getText().toString())); 
        message.setData(bundle); 
        jisuan.mhandler.sendMessage(message); 
      } 
    }); 
  } 
} 

Hanler和Looper,MessageQueue原理分析

1.Handler發(fā)送消息處理消息(一般都是將消息發(fā)送給自己),因?yàn)閔anler在不同線程是可使用的

2.Looper管理MessageQueue

Looper.loop死循環(huán),不斷從MessageQueue取消息,如果有消息就處理消息,沒(méi)有消息就阻塞

public static void loop() { 
    final Looper me = myLooper(); 
    if (me == null) { 
      throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); 
    } 
    final MessageQueue queue = me.mQueue; 
    // Make sure the identity of this thread is that of the local process, 
    // and keep track of what that identity token actually is. 
    Binder.clearCallingIdentity(); 
    final long ident = Binder.clearCallingIdentity(); 
 
    for (;;) { 
      Message msg = queue.next(); // might block 
      if (msg == null) { 
        // No message indicates that the message queue is quitting. 
        return; 
      } 
      // This must be in a local variable, in case a UI event sets the logger 
      Printer logging = me.mLogging; 
      if (logging != null) { 
        logging.println(">>>>> Dispatching to " + msg.target + " " + 
            msg.callback + ": " + msg.what); 
      } 
      msg.target.dispatchMessage(msg); 
 
      if (logging != null) { 
        logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); 
      } 
      // Make sure that during the course of dispatching the 
      // identity of the thread wasn't corrupted. 
      final long newIdent = Binder.clearCallingIdentity(); 
      if (ident != newIdent) { 
        Log.wtf(TAG, "Thread identity changed from 0x" 
            + Long.toHexString(ident) + " to 0x" 
            + Long.toHexString(newIdent) + " while dispatching to " 
            + msg.target.getClass().getName() + " " 
            + msg.callback + " what=" + msg.what); 
      } 
 
      msg.recycleUnchecked(); 
    } 
  } 

這個(gè)是Looper.loop的源碼,實(shí)質(zhì)就是一個(gè)死循環(huán),不斷讀取自己的MessQueue的消息

3.MessQueue一個(gè)消息隊(duì)列,Handler發(fā)送的消息會(huì)添加到與自己內(nèi)聯(lián)的Looper的MessQueue中,受Looper管理

private Looper(boolean quitAllowed) { 
    mQueue = new MessageQueue(quitAllowed); 
    mThread = Thread.currentThread(); 
  } 

這個(gè)是Looper構(gòu)造器,其中做了2個(gè)工作,

1.生成與自己關(guān)聯(lián)的Message

2.綁定到當(dāng)前線程

主線程在初始化的時(shí)候已經(jīng)生成Looper,

其他線程如果想使用handler需要通過(guò)Looper.prepare()生成一個(gè)自己線程綁定的looper

這就是Looper.prepare()源碼,其實(shí)質(zhì)也是使用構(gòu)造器生成一個(gè)looper

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)); 
  } 

4.handler發(fā)送消息會(huì)將消息保存在自己相關(guān)聯(lián)的Looper的MessageQueue中,那它是如何找到這個(gè)MessageQueue的呢

public Handler(Callback callback, boolean async) { 
    if (FIND_POTENTIAL_LEAKS) { 
      final Class<? extends Handler> klass = getClass(); 
      if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && 
          (klass.getModifiers() & Modifier.STATIC) == 0) { 
        Log.w(TAG, "The following Handler class should be static or leaks might occur: " + 
          klass.getCanonicalName()); 
      } 
    } 
 
    mLooper = Looper.myLooper(); 
    if (mLooper == null) { 
      throw new RuntimeException( 
        "Can't create handler inside thread that has not called Looper.prepare()"); 
    } 
    mQueue = mLooper.mQueue; 
    mCallback = callback; 
    mAsynchronous = async; 
  } 

這個(gè)是Handler的構(gòu)造方法,它會(huì)找到一個(gè)自己關(guān)聯(lián)的一個(gè)Looper

public static Looper myLooper() { 
    return sThreadLocal.get(); 
  } 

沒(méi)錯(cuò),他們之間也是通過(guò)線程關(guān)聯(lián)的,得到Looper之后自然就可以獲得它的MessageQueue了

5.我們?cè)倏聪耯andler如發(fā)送消息,又是如何在發(fā)送完消息后,回調(diào)HandlerMessage的

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { 
    msg.target = this; 
    if (mAsynchronous) { 
      msg.setAsynchronous(true); 
    } 
    return queue.enqueueMessage(msg, uptimeMillis); 
  } 

這個(gè)就是Handler發(fā)送消息的最終源碼,可見就是將一個(gè)message添加到MessageQueue中,那為什么發(fā)送完消息又能及時(shí)回調(diào)handleMessage方法呢

大家請(qǐng)看上邊那個(gè)loop方法,其中的for循環(huán)里面有一句話msg.target.dispatchMessage(msg);

public void dispatchMessage(Message msg) { 
    if (msg.callback != null) { 
      handleCallback(msg); 
    } else { 
      if (mCallback != null) { 
        if (mCallback.handleMessage(msg)) { 
          return; 
        } 
      } 
      handleMessage(msg); 
    } 
  } 

這就是這句話,看到了吧里面會(huì)調(diào)用hanlerMessage,一切都聯(lián)系起來(lái)了吧

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

  • Android實(shí)現(xiàn)圓角Button按鈕

    Android實(shí)現(xiàn)圓角Button按鈕

    這篇文章主要介紹了Android實(shí)現(xiàn)圓角Button按鈕,利用xml文件中 shape實(shí)現(xiàn)圓角效果,感興趣的小伙伴們可以參考一下
    2015-12-12
  • DataBinding onClick的七種點(diǎn)擊方式

    DataBinding onClick的七種點(diǎn)擊方式

    這篇文章主要給大家介紹了關(guān)于DataBinding onClick的七種點(diǎn)擊方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)各位Android開發(fā)者們具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • Android自定義Dialog原理實(shí)例解析

    Android自定義Dialog原理實(shí)例解析

    這篇文章主要介紹了Android自定義Dialog原理實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-07-07
  • Android開發(fā) Bundle傳值的理解與使用小結(jié)

    Android開發(fā) Bundle傳值的理解與使用小結(jié)

    這篇文章主要介紹了Android開發(fā) Bundle傳值的理解與使用小結(jié),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧
    2024-07-07
  • Android自定義View實(shí)現(xiàn)雪花特效

    Android自定義View實(shí)現(xiàn)雪花特效

    這篇文章主要為大家詳細(xì)介紹了Android自定義View實(shí)現(xiàn)雪花特效,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-02-02
  • Android實(shí)現(xiàn)文字翻轉(zhuǎn)動(dòng)畫的效果

    Android實(shí)現(xiàn)文字翻轉(zhuǎn)動(dòng)畫的效果

    本文實(shí)現(xiàn)了Android程序文字翻轉(zhuǎn)動(dòng)畫的實(shí)現(xiàn),具有一定的參考價(jià)值,有需要的朋友可以了解一下。
    2016-10-10
  • Android編程實(shí)現(xiàn)畫板功能的方法總結(jié)【附源碼下載】

    Android編程實(shí)現(xiàn)畫板功能的方法總結(jié)【附源碼下載】

    這篇文章主要介紹了Android編程實(shí)現(xiàn)畫板功能的方法,結(jié)合實(shí)例形式總結(jié)分析了Android基于自定義View與Canvas類實(shí)現(xiàn)畫板功能的具體操作步驟與相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2018-02-02
  • 關(guān)于Android Activity之間跳轉(zhuǎn)問(wèn)題(Intent)

    關(guān)于Android Activity之間跳轉(zhuǎn)問(wèn)題(Intent)

    這篇文章主要介紹了Android Activity之間跳轉(zhuǎn)Intent,當(dāng)一個(gè)Acitivity需要啟動(dòng)另一個(gè)Activity時(shí),通過(guò)Intent來(lái)表達(dá)自己的意圖,告知系統(tǒng)啟動(dòng)哪個(gè)Activity,本文給大家詳細(xì)講解,需要的朋友可以參考下
    2022-10-10
  • 詳解Android如何實(shí)現(xiàn)好的彈層體驗(yàn)效果

    詳解Android如何實(shí)現(xiàn)好的彈層體驗(yàn)效果

    當(dāng)前?App?的設(shè)計(jì)趨勢(shì)越來(lái)越希望給用戶沉浸式體驗(yàn),這種設(shè)計(jì)會(huì)讓用戶盡量停留在當(dāng)前的界面,而不需要太多的跳轉(zhuǎn),這就需要引入彈層。本篇我們就來(lái)講講彈層這塊需要注意哪些用戶體驗(yàn)
    2022-11-11
  • AndroidStudio升級(jí)4.1坑(無(wú)法啟動(dòng)、插件plugin不好用、代碼不高亮)

    AndroidStudio升級(jí)4.1坑(無(wú)法啟動(dòng)、插件plugin不好用、代碼不高亮)

    這篇文章主要介紹了AndroidStudio升級(jí)4.1坑(無(wú)法啟動(dòng)、插件plugin不好用、代碼不高亮),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10

最新評(píng)論

桃园县| 石首市| 舟山市| 始兴县| 永德县| 卢湾区| 康保县| 阿巴嘎旗| 农安县| 五河县| 格尔木市| 宁武县| 鲜城| 凤冈县| 老河口市| 合江县| 甘德县| 巫山县| 桑日县| 临澧县| 吉林省| 龙南县| 科技| 平昌县| 临澧县| 西吉县| 汾阳市| 师宗县| 新郑市| 台东县| 望城县| 米易县| 瓦房店市| 阳新县| 杂多县| 甘孜县| 浏阳市| 永平县| 杭锦后旗| 陆河县| 随州市|