首页 > 代码库 > Android4.4 framework分析——广播的注册(BroadcastReceiver)和发送(sendbroadcast)过程分析

Android4.4 framework分析——广播的注册(BroadcastReceiver)和发送(sendbroadcast)过程分析

在Android应用程序框架中,Activity和Service类都继承了ContextWrapper类,因此,我们可以在Activity或者Service的子类中调用registerReceiver函数来注册广播接收器。

下图是在activity中注册广播的过程:



step1~step3,就是一般的调用过程。

step4,registerReceiverInternal()方法如下:

    private Intent registerReceiverInternal(BroadcastReceiver receiver, int userId,
            IntentFilter filter, String broadcastPermission,
            Handler scheduler, Context context) {
        IIntentReceiver rd = null;
        if (receiver != null) {
            if (mPackageInfo != null && context != null) {
                if (scheduler == null) {
                    scheduler = mMainThread.getHandler();
                }
                rd = mPackageInfo.getReceiverDispatcher(
                    receiver, context, scheduler,
                    mMainThread.getInstrumentation(), true);
            } else {
                if (scheduler == null) {
                    scheduler = mMainThread.getHandler();
                }
                rd = new LoadedApk.ReceiverDispatcher(
                        receiver, context, scheduler, null, true).getIIntentReceiver();
            }
        }
        try {
            return ActivityManagerNative.getDefault().registerReceiver(
                    mMainThread.getApplicationThread(), mBasePackageName,
                    rd, filter, broadcastPermission, userId);
        } catch (RemoteException e) {
            return null;
        }
    }

scheduler传下的是null,scheduler = mMainThread.getHandler();将获得H的对象mH,用于后续broadcast的发送。


step6,先从已有的注册列表mReceivers中查找是否由相同的ReceiverDispatcher,若之前没有注册过,则new一个ReceiverDispatcher,并记录在mReceivers中,ReceiverDispatcher创建过程中,同时生成一个InnerReceiver,InnerReceiver用于接收处理sendBroadcast发过来的广播。


step9~step11,通过binder访问ActivityManagerService的registerReceiver,将广播接收器receiver保存起来。



下图是广播发送(sendBroadcast)的过程:



分析步骤参考:http://blog.csdn.net/luoshengyang/article/details/6744448


右键复制图片地址,在浏览器中打开即可查看大图。

未完待续,有不对的地方,请指正。


Android4.4 framework分析——广播的注册(BroadcastReceiver)和发送(sendbroadcast)过程分析