美文网首页
android 中的LocalBroadcastManager

android 中的LocalBroadcastManager

作者: 码码Master | 来源:发表于2016-08-30 21:09 被阅读0次

对于LocalBroadcastManager在google官方文档中也说得很清楚,比较简短,也很好看懂,可以去看看。
Helper to register for and send broadcasts of Intents to local objects within your process. This has a number of advantages over sending global broadcasts with sendBroadcast(Intent):

  • You know that the data you are broadcasting won't leave your app, so don't need to worry about leaking private data.
  • It is not possible for other applications to send these broadcasts to your app, so you don't need to worry about having security holes they can exploit.
  • It is more efficient than sending a global broadcast through the system.

大体介绍就是这些,顾名思义,本地广播(注册),数据安全,其他app也不能给你发广播(接收)。也比系统广播高效。

使用十分简单:
注册(接收)

protected void onCreate(Bundle savedInstanceState) { 
// TODO Auto-generated method stub
       super.onCreate(savedInstanceState);
        if(savedInstanceState!=null) { 
            if(mLocalBroadcastManager!=null && mBoradCast!=null) { 
              mLocalBroadcastManager.unregisterReceiver(mBoradCast);
              mLocalBroadcastManager=null; 
              mBoradCast=null;
              }
         }
     
     mLocalBroadcastManager=LocalBroadcastManager.getInstance(this); 
     mBoradCast = new MyBroadCast(); IntentFilter intentFilter = new IntentFilter(); 
     //重点在这里,本地注册,本地接收。
     mLocalBroadcastManager.registerReceiver(mBoradCast, intentFilter);
}


@Override 
protected void onDestroy() { 
        super.onDestroy();
        if(mLocalBroadcastManager!=null && mBoradCast!=null) { 
           mLocalBroadcastManager.unregisterReceiver(mBoradCast); 
           mLocalBroadcastManager=null; 
          mBoradCast=null; 
        } 
}

发送:

LocalBroadcastManager lcm=LocalBroadcastManager.getInstance(mContext); 
lcm.sendBroadcast(new Intent(ACTION_LOCATION));//发送

以上则是简单的使用。那么来说说为何呢:有兴趣去看看LocalBroadcastManager

注册这里可以看到,它其实是一个单例,针对本应用进程的。:

public static LocalBroadcastManager More ...getInstance(Context context) { 
      synchronized (mLock) { 
         if (mInstance == null) {
             mInstance = new LocalBroadcastManager(context.getApplicationContext());//应用的上下文
         } 
           return mInstance;
       } 
} 
private More ...LocalBroadcastManager(Context context) { 
           mAppContext = context; 
           //用主线程注册
           handler mHandler = new Handler(context.getMainLooper()) { 
                @Override public void More ...handleMessage(Message msg) { 
                        switch (msg.what) { 
                              case MSG_EXEC_PENDING_BROADCASTS: 
                                       executePendingBroadcasts(); 
                              break; 
                              default:
                                     super.handleMessage(msg); 
                        } 
                   }
           };
 }```

注册的代码:

private final HashMap<BroadcastReceiver, ArrayList<IntentFilter>> mReceivers = new HashMap<BroadcastReceiver, ArrayList<IntentFilter>>();
public void More ...registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
synchronized (mReceivers) {
ReceiverRecord entry = new ReceiverRecord(filter, receiver);
ArrayList<IntentFilter> filters = mReceivers.get(receiver);
if (filters == null) {
filters = new ArrayList<IntentFilter>(1);
//这里很明显是用的一个HashMap来装的我们注册的receiver和filter mReceivers.put(receiver, filters);
}
filters.add(filter);
for (int i=0; i<filter.countActions(); i++) {
String action = filter.getAction(i);
ArrayList<ReceiverRecord> entries = mActions.get(action);
if (entries == null) {
entries = new ArrayList<ReceiverRecord>(1);
mActions.put(action, entries);
}
entries.add(entry);
}
}
}


取消注册:

public void More ...unregisterReceiver(BroadcastReceiver receiver) {
synchronized (mReceivers) {
ArrayList<IntentFilter> filters = mReceivers.remove(receiver);
if (filters == null) {
return;8
}
for (int i=0; i<filters.size(); i++) {
IntentFilter filter = filters.get(i);
for (int j=0; j<filter.countActions(); j++) {
String action = filter.getAction(j);
ArrayList<ReceiverRecord> receivers = mActions.get(action);
if (receivers != null) {
for (int k=0; k<receivers.size(); k++) {
if (receivers.get(k).receiver == receiver) {
//从Map里移除
receivers.remove(k);
k--;
}
}
if (receivers.size() <= 0) {
mActions.remove(action);
}
}
}
}
}
}```

发送广播,截取一部分:

if (receivers != null) {
  for (int i=0; i<receivers.size(); i++) { 
    receivers.get(i).broadcasting = false;
  }  
mPendingBroadcasts.add(new BroadcastRecord(intent, receivers)); 
  if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) { 
    mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS); 
  }
 return true;
}

private void More ...executePendingBroadcasts() {
    while (true) {
       BroadcastRecord[] brs = null;
       synchronized (mReceivers) {
         final int N = mPendingBroadcasts.size();
           if (N <= 0) {
              return; 
           } 
         brs = new BroadcastRecord[N]; 
         mPendingBroadcasts.toArray(brs); 
         mPendingBroadcasts.clear();
       }
     for (int i=0; i<brs.length; i++) {
        BroadcastRecord br = brs[i]; 
        for (int j=0; j<br.receivers.size(); j++) {
          //重点在这里,每个注册的都调用了我们注册的onReceive方法(让其自行接收处理)。
          br.receivers.get(j).receiver.onReceive(mAppContext, br.intent);
        }
     } 
    } 
}

这就大致了解了工作原理了。使用起来是很方便的,单例效率也高。所以如果不是非本地注册本地接收的,还是使用LocalBroadcastManager更好。如果是更新图库等,需要系统接收的除外。

相关文章

网友评论

      本文标题:android 中的LocalBroadcastManager

      本文链接:https://www.haomeiwen.com/subject/racqettx.html