android 中的LocalBroadcastManager

原创 2016年08月30日 16:05:44

对于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,源码解析

在Android系统中,BroadcastReceiver的设计初衷就是从全局考虑的,可以方便应用程序和系统、应用程序之间、应用程序内的通信,所以对单个应用程序而言BroadcastReceiver是...

Android 本地广播LocalBroadcastManager原理分析

LocalBroadcastManager是Android Support包提供了一个工具,是用来在同一个应用内的不同组件间发送Broadcast的。

我是如何成为一名python大咖的?

人生苦短,都说必须python,那么我分享下我是如何从小白成为Python资深开发者的吧。2014年我大学刚毕业..

Android编程之LocalBroadcastManager源码详解

LocalBroadcastManager 是V4包中的一个类,主要负责程序内部广播的注册与发送。也就是说,它只是适用代码中注册发送广播,对于在AndroidManifest中注册的广播接收,则不适用...

Android LocalBroadcastManager 的使用总结

前言在Android中,Broadcast是一种广泛运用的在应用程序之间传输信息的机制。我们拿广播电台来做个比方。我们平常使用收音机收音是这样的:许许多多不同的广播电台通过特定的频率来发送他们的内容,...

学习笔记 Android LocalBroadcastManager的使用

LocalBroadcastManager简介 LocalBroadcastManager是Google官方AndroidSupport包提供的一个工具,用来管理广播的类。只能用来在同一个应用的不同...

Android 之使用LocalBroadcastManager解决BroadcastReceiver安全问题

[Android Pro]  参考博客: http://blog.csdn.net/t12x3456/article/details/9256609 http://b...

Android LocalBroadcastManager

原文地址http://cashow.github.io/Android-content-localbroadcastmanager.htmlLocalBroadcastManager是android ...

android中LocalBroadcastManager的使用

今天遇到一个acitivity之间通信的问题,由于我们是用TabActivity包裹了Activity(我们称之为A),所以这两个Activity是同时存在的。当在TabActivity中启动其他Ac...

Android LocalBroadcastManager与BroadcastReceiver

在Android系统中,BroadcastReceiver的设计初衷就是从全局考虑的,可以方便应用程序和系统、应用程序之间、应用程序内的通信,所以对单个应用程序而言BroadcastReceiver是...

本地广播LocalBroadcastManager与Android.support.v4.jar导入

发出的广播只能在应用内部进行传递,广播接收器也只能接收程序内部的广播。这样就不存在系统全局广播的安全性问题。 修改BroadcastTest的MainActivity代码:public class ...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)