BroadcastReceiver

一、廣播

1、定義

在這裏插入圖片描述
1)、類似觀察者模式

2、場景

1)、同一個app內多個進程的不同組件之間的消息通信
2)、不同的app之間的組件之間消息通信

3、種類

1)、普通廣播:Context.sendBroadcast()
2)、有序廣播:Context.sendOrderedBroadCast()
3)、本地廣播:自在App內傳播

二、實現廣播-receiver

1、靜態註冊:

a、直接把廣播接收者寫在manifast中;
b、註冊完成就一直運行;
c、依賴的activity被銷燬了,仍然接收廣播;
d、甚至app 進程被殺死了後仍能收到廣播;

2、動態註冊:

a、在代碼中調用registerServer();
b、跟隨acticity的生命週期,activity被銷燬了,廣播接收者也就失效了;
c、注意在destory()方法中unRegisterServier()來防止內存泄漏;

三、廣播實現機制

在這裏插入圖片描述
AMS : 貫穿android系統組件的一個核心服務,負責四大組件的啓動,切換和調度,以及應用程序的管理和調度工作;

四、LocalBroadcastManager詳解

在這裏插入圖片描述

1、三個集合類

1、
    private final HashMap<BroadcastReceiver, ArrayList<IntentFilter>> mReceivers 
            = new HashMap<BroadcastReceiver, ArrayList<IntentFilter>>();
  
  key是BroadcastReceiver,value是每個BroadcastReceiver對應可以接收幾個action的廣播; 
    
2、        
    private final HashMap<String, ArrayList<ReceiverRecord>> mActions
            = new HashMap<String, ArrayList<ReceiverRecord>>();
            
  key是action,value 是action 對應的ReceiverRecord的集合;
             
     private static class ReceiverRecord {
              final IntentFilter filter;
              final BroadcastReceiver receiver;
     }
     

3、
    private final ArrayList<BroadcastRecord> mPendingBroadcasts
            = new ArrayList<BroadcastRecord>();
            
mPendingBroadcasts是存儲 和發送的廣播action匹配的 ReceiverRecord集合;
            
     private static class BroadcastRecord {
          final Intent intent;
          final ArrayList<ReceiverRecord> receivers;
      }

2、
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章