欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Broadcast机制源码详解-发送

程序员文章站 2022-07-14 17:36:10
...

1.基本的广播相关的结构

  • ReceiverDispatcher 连接BroadcastReceiver和InnerReceiver.ReceiverDispatcher的内部类InnerReceiver为binder对象,用于与AMS的传递与通信。三者是一对一的关系.
  • BroadcastFilter 继承自IntentFilter,是对IntentFilter的封装.是动态广播节点。
  • ReceiverList,继承自ArrayList.存放某一receiverd 对应的BroadcastFilter,
  • ResolveInfo:Parcelable子类,描述静态广播,是静态广播节点。
  • IntentResolver: 解析Intent,在addFilter时即进行解析。其内部有mSchemeToFilter,mActionToFilter,mTypedActionToFilter三个map对象。key为对应的action(scheme或者type),value为Filte
  • BroadcastQueue: BroadcastQueue为Broadcast处理队列,分为前台队列mFgBroadcastQueue和后台队列mBgBroadcastQueue,mFgBroadcastQueue会有更高的权限,被优先处理。mFgBroadcastQueue和mBgBroadcastQueue两个队列中都含有mOrderedBroadcasts和mParallelBroadcasts两个列表用来表示有序广播列表和无序广播列表

接上文.最后把消息封装成BroadcastRecord.并加入到BroadcastQueue中,并通过scheduleBroadcastsLocked发送

2.源码详解

  1. BroadcastQueue.scheduleBroadcastsLocked,
    就是把广播用handler发送
    public void scheduleBroadcastsLocked() {
        if (DEBUG_BROADCAST) Slog.v(TAG, "Schedule broadcasts ["
                + mQueueName + "]: current="
                + mBroadcastsScheduled);
       //1.mBroadcastsScheduled参数是用来标记是否已经向消息队列发送了一个类型为BROADCAST_INTENT_MSG消息
        if (mBroadcastsScheduled) {
            return;
        }
//2.其实就是把消息发送给handler处理
        mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this));
        mBroadcastsScheduled = true;
    }
  1. mHandler是BroadcastQueue的内部类BroadcastHandler,在创建BroacdcastQueue时,传入的一个Lopper.
    这个Lopper是AMS中的MainHandler的lopper,所以消息运行在Ams线程的Lopper中
    public ActivityManagerService(Context systemContext) {
        //1.开启Ams线程.得到mHandler
        mHandlerThread = new ServiceThread(TAG,
                android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
        mHandlerThread.start();
        mHandler = new MainHandler(mHandlerThread.getLooper());
        //2.把ServiceThread的handler传给queue.这两个queue是前提队列和后台队列
        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "foreground", BROADCAST_FG_TIMEOUT, false);
        mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "background", BROADCAST_BG_TIMEOUT, true);
}
再看 BroadcastQueue的构造函数
   BroadcastQueue(ActivityManagerService service, Handler handler,
            String name, long timeoutPeriod, boolean allowDelayBehindServices) {
        mService = service;
        mHandler = new BroadcastHandler(handler.getLooper());//用传入的lopper来构造自己的handler
        mQueueName = name;
        mTimeoutPeriod = timeoutPeriod;
        mDelayBehindServices = allowDelayBehindServices;
    }

最后的结果就是BroadcastQueue里的handler发送的事件最后进入Ams中mHandlerThread 的队列.

  1. BroadcastQueue内部类 BroadcastHandler的处理
    private final class BroadcastHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BROADCAST_INTENT_MSG: {
                    if (DEBUG_BROADCAST) Slog.v(
                            TAG, "Received BROADCAST_INTENT_MSG");
//1.这行是主要的
                    processNextBroadcast(true);
                } break;
                case BROADCAST_TIMEOUT_MSG: {
                    synchronized (mService) {
                        broadcastTimeoutLocked(true);
                    }
                } break;
            }
        }
    

3.handler调用了BroadcastQueue的方法 processNextBrodacast,这个方法有点长
3.1、处理并行广播
3.2、处理Pending广播
3.3、处理有序广播
3.4、获取下一条广播
3.5、检查是否是动态广播
3.6、检查是否是静态广播
3.7、启动进程,处理未发送的静态广播

final void processNextBroadcast(boolean fromMsg) {
        synchronized(mService) {
            BroadcastRecord r;

          //1.ams更新cup状态
            mService.updateCpuStats();
 //2.设置该参数为false,表示前面发送到消息队列中的BROADCAST_INTENT_MSG消息已经被处理了
            if (fromMsg) {
                mBroadcastsScheduled = false;
            }

            // First, deliver any non-serialized broadcasts right away.
//3.把无序广播在这里直接处理掉
            while (mParallelBroadcasts.size() > 0) {
                r = mParallelBroadcasts.remove(0);
                r.dispatchTime = SystemClock.uptimeMillis();
                r.dispatchClockTime = System.currentTimeMillis();
                final int N = r.receivers.size();
                for (int i=0; i<N; i++) {
                    Object target = r.receivers.get(i);
     //4.无序播都是从deliverToRegisteredReceiverLocked发送出去的,此时r.receivers里面的都是BroadcastFilter  
                    deliverToRegisteredReceiverLocked(r, (BroadcastFilter)target, false);
                }
                addBroadcastToHistoryLocked(r);
               
            }

            // Now take care of the next serialized one...

            // If we are waiting for a process to come up to handle the next
            // broadcast, then do nothing at this point.  Just in case, we
            // check that the process we're waiting for still exists.
//5.检查线程继续存活
如果一个广播在发送的时候,进程还没有启动起来,那么会将它存在mPendingBroadcast中。由于动态广播是不会保证一定能够收到的,
所以mPendingBroadcast是用来描述一个正在等待静态注册的目标广播接收者启动的广播。
            if (mPendingBroadcast != null) {

                boolean isDead;
                synchronized (mService.mPidsSelfLocked) {
  //6. 检查这个静态注册的目标广播接收者所运行在的应用程序进程是否已经启动起来  
                    ProcessRecord proc = mService.mPidsSelfLocked.get(mPendingBroadcast.curApp.pid);
                    isDead = proc == null || proc.crashing;
                }
                if (!isDead) {    //7. 如果这个应用程序进程还活着,就会继续等待,否则就不等了
                    // It's still alive, so keep waiting
                    return;
                } else {
                    mPendingBroadcast.state = BroadcastRecord.IDLE;
                    mPendingBroadcast.nextReceiver = mPendingBroadcastRecvIndex;
                    mPendingBroadcast = null;
                }
            }

            boolean looped = false;
            
            do {
  //8.有序广播队列为0,不用处理,返回
                if (mOrderedBroadcasts.size() == 0) {
                    // No more broadcasts pending, so all done!
                    mService.scheduleAppGcsLocked();
                    if (looped) {
                        // If we had finished the last ordered broadcast, then
                        // make sure all processes have correct oom and sched
                        // adjustments.
                        mService.updateOomAdjLocked();
                    }
                    return;
                }
   //9.获取一个有序广播(最顶部的BroadcastRecord)
                r = mOrderedBroadcasts.get(0);
                boolean forceReceive = false;

                // Ensure that even if something goes awry with the timeout
                // detection, we catch "hung" broadcasts here, discard them,
                // and continue to make progress.
                //
                // This is only done if the system is ready so that PRE_BOOT_COMPLETED
                // receivers don't get executed with timeouts. They're intended for
                // one time heavy lifting after system upgrades and can take
                // significant amounts of time.
                int numReceivers = (r.receivers != null) ? r.receivers.size() : 0;
 //10广播超时处理 ,结束掉超时的广播
                if (mService.mProcessesReady && r.dispatchTime > 0) {
                    long now = SystemClock.uptimeMillis();
                    if ((numReceivers > 0) &&
                            (now > r.dispatchTime + (2*mTimeoutPeriod*numReceivers))) {
                        broadcastTimeoutLocked(false); // forcibly finish this broadcast
                        forceReceive = true;
                        r.state = BroadcastRecord.IDLE;
                    }
                }

                if (r.state != BroadcastRecord.IDLE) {
                    if (DEBUG_BROADCAST) Slog.d(TAG,
                            "processNextBroadcast("
                            + mQueueName + ") called when not idle (state="
                            + r.state + ")");
                    return;
                }
// 11.一:广播没有接收者了,二: 所有接受者都收到了广播,三:
广播是否已经被拦截了,四:广播是否已经被强制结束。
                if (r.receivers == null || r.nextReceiver >= numReceivers
                        || r.resultAbort || forceReceive) {
                    // No more receivers for this broadcast!  Send the final
                    // result if requested...
                    if (r.resultTo != null) {
                        try {
//12.处理广播消息消息,调用到onReceive()
                            performReceiveLocked(r.callerApp, r.resultTo,
                                new Intent(r.intent), r.resultCode,
                                r.resultData, r.resultExtras, false, false, r.userId);
                            r.resultTo = null;
                        } catch (RemoteException e) {
                            r.resultTo = null;
                    }
//13.解除超时统计,统计是通过Handler发送超时msg来实现的,这里取消发送msg
                    cancelBroadcastTimeoutLocked();

  // 14.处理下一条消息,并将当前消息从有序表里删除
                    addBroadcastToHistoryLocked(r);
                    mOrderedBroadcasts.remove(0);
                    r = null;
                    looped = true;
                    continue;
                }
            } while (r == null);

            // Get the next receiver...
            int recIdx = r.nextReceiver++;
            // Keep track of when this receiver started, and make sure there
            // is a timeout message pending to kill it if need be.
            r.receiverTime = SystemClock.uptimeMillis();
            if (recIdx == 0) {
                r.dispatchTime = r.receiverTime;
                r.dispatchClockTime = System.currentTimeMillis();
                if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG, "Processing ordered broadcast ["
                        + mQueueName + "] " + r);
            }
//15.这里就是上边提到的超时消息的发送.发送了一个BROADCAST_TIMEOUT_MSG的延时消息,延时的时长是timeoutTime 字段.
            if (! mPendingBroadcastTimeoutMessage) {
                long timeoutTime = r.receiverTime + mTimeoutPeriod;
                if (DEBUG_BROADCAST) Slog.v(TAG,
                        "Submitting BROADCAST_TIMEOUT_MSG ["
                        + mQueueName + "] for " + r + " at " + timeoutTime);
                setBroadcastTimeoutLocked(timeoutTime);
            }
  //16检查是否是动态广播
            Object nextReceiver = r.receivers.get(recIdx);
            if (nextReceiver instanceof BroadcastFilter) {
                // Simple case: this is a registered receiver who gets
                // a direct call.
                BroadcastFilter filter = (BroadcastFilter)nextReceiver;
  //17.动态注册的广播给deliverToRegisteredReceiverLocked处理
                deliverToRegisteredReceiverLocked(r, filter, r.ordered);
                if (r.receiver == null || !r.ordered) {
                    // The receiver has already finished, so schedule to
                    // process the next one.
//将 r.state设置为IDLE,表示不需要等待它的前一个目标广播接收者处理完成一个广播,  
         // 就可以将该广播继续发送给它的下一个目标广播接收者处理  
          r.state = BroadcastRecord.IDLE;
      //执行下一个广播,内部也是发送消息
          scheduleBroadcastsLocked();
                }
                return;     //有序广播一次只处理一个,直接返回就行
            }

 //18.这里是静态广播的处理.  这个ComponentName会一直传递到ActivityThread,用来反射new广播接收者对象的
            ResolveInfo info =
                (ResolveInfo)nextReceiver;
            ComponentName component = new ComponentName(
                    info.activityInfo.applicationInfo.packageName,
                    info.activityInfo.name);
  //19很多的条件判断,skip不满足就为true
            boolean skip = false;
            int perm = mService.checkComponentPermission(info.activityInfo.permission,
                    r.callingPid, r.callingUid, info.activityInfo.applicationInfo.uid,
                    info.activityInfo.exported);
            if (perm != PackageManager.PERMISSION_GRANTED) {//权限验证
                if (!info.activityInfo.exported) {
                    Slog.w(TAG, "Permission Denial: broadcasting "
                            + r.intent.toString()
                            + " from " + r.callerPackage + " (pid=" + r.callingPid
                            + ", uid=" + r.callingUid + ")"
                            + " is not exported from uid " + info.activityInfo.applicationInfo.uid
                            + " due to receiver " + component.flattenToShortString());
                } else {
                    Slog.w(TAG, "Permission Denial: broadcasting "
                            + r.intent.toString()
                            + " from " + r.callerPackage + " (pid=" + r.callingPid
                            + ", uid=" + r.callingUid + ")"
                            + " requires " + info.activityInfo.permission
                            + " due to receiver " + component.flattenToShortString());
                }
                skip = true;
            }
            if (info.activityInfo.applicationInfo.uid != Process.SYSTEM_UID &&//进场验证
                r.requiredPermission != null) {
                try {
                    perm = AppGlobals.getPackageManager().
                            checkPermission(r.requiredPermission,
                                    info.activityInfo.applicationInfo.packageName);
                } catch (RemoteException e) {
                    perm = PackageManager.PERMISSION_DENIED;
                }
                if (perm != PackageManager.PERMISSION_GRANTED) {
                    Slog.w(TAG, "Permission Denial: receiving "
                            + r.intent + " to "
                            + component.flattenToShortString()
                            + " requires " + r.requiredPermission
                            + " due to sender " + r.callerPackage
                            + " (uid " + r.callingUid + ")");
                    skip = true;
                }
            }
            if (r.appOp != AppOpsManager.OP_NONE) {
                int mode = mService.mAppOpsService.noteOperation(r.appOp,
                        info.activityInfo.applicationInfo.uid, info.activityInfo.packageName);
                if (mode != AppOpsManager.MODE_ALLOWED) {
                    if (DEBUG_BROADCAST)  Slog.v(TAG,
                            "App op " + r.appOp + " not allowed for broadcast to uid "
                            + info.activityInfo.applicationInfo.uid + " pkg "
                            + info.activityInfo.packageName);
                    skip = true;
                }
            }
            if (!skip) {
                skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
                        r.callingPid, r.resolvedType, info.activityInfo.applicationInfo.uid);
            }
            boolean isSingleton = false;
            try {
                isSingleton = mService.isSingleton(info.activityInfo.processName,
                        info.activityInfo.applicationInfo,
                        info.activityInfo.name, info.activityInfo.flags);
            } catch (SecurityException e) {
                Slog.w(TAG, e.getMessage());
                skip = true;
            }
            if ((info.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
                if (ActivityManager.checkUidPermission(
                        android.Manifest.permission.INTERACT_ACROSS_USERS,
                        info.activityInfo.applicationInfo.uid)
                                != PackageManager.PERMISSION_GRANTED) {
                    Slog.w(TAG, "Permission Denial: Receiver " + component.flattenToShortString()
                            + " requests FLAG_SINGLE_USER, but app does not hold "
                            + android.Manifest.permission.INTERACT_ACROSS_USERS);
                    skip = true;
                }
            }
            if (r.curApp != null && r.curApp.crashing) {
                // If the target process is crashing, just skip it.
                Slog.w(TAG, "Skipping deliver ordered [" + mQueueName + "] " + r
                        + " to " + r.curApp + ": process crashing");
                skip = true;
            }
            if (!skip) {
                boolean isAvailable = false;
                try {
                    isAvailable = AppGlobals.getPackageManager().isPackageAvailable(
                            info.activityInfo.packageName,
                            UserHandle.getUserId(info.activityInfo.applicationInfo.uid));
                } catch (Exception e) {
                    // all such failures mean we skip this receiver
                    Slog.w(TAG, "Exception getting recipient info for "
                            + info.activityInfo.packageName, e);
                }
                if (!isAvailable) {
                    if (DEBUG_BROADCAST) {
                        Slog.v(TAG, "Skipping delivery to " + info.activityInfo.packageName
                                + " / " + info.activityInfo.applicationInfo.uid
                                + " : package no longer available");
                    }
                    skip = true;
                }
            }

            if (skip) {//20.这里说明不满足.所以执行下条广播.
                if (DEBUG_BROADCAST)  Slog.v(TAG,
                        "Skipping delivery of ordered ["
                        + mQueueName + "] " + r + " for whatever reason");
                r.receiver = null;
                r.curFilter = null;
                r.state = BroadcastRecord.IDLE;
                scheduleBroadcastsLocked();
                return;
            }

            r.state = BroadcastRecord.APP_RECEIVE;
            String targetProcess = info.activityInfo.processName;
            r.curComponent = component;
            final int receiverUid = info.activityInfo.applicationInfo.uid;
          
            if (r.callingUid != Process.SYSTEM_UID && isSingleton
                    && mService.isValidSingletonCall(r.callingUid, receiverUid)) {
                info.activityInfo = mService.getActivityInfoForUser(info.activityInfo, 0);
            }
            r.curReceiver = info.activityInfo;

            // Broadcast is being executed, its package can't be stopped.
            try {
                AppGlobals.getPackageManager().setPackageStoppedState(
                        r.curComponent.getPackageName(), false, UserHandle.getUserId(r.callingUid));
            } catch (RemoteException e) {
            } catch (IllegalArgumentException e) {
                Slog.w(TAG, "Failed trying to unstop package "
                        + r.curComponent.getPackageName() + ": " + e);
            }

 
            ProcessRecord app = mService.getProcessRecordLocked(targetProcess,
                    info.activityInfo.applicationInfo.uid, false);
            if (app != null && app.thread != null) {
                try {
                    app.addPackage(info.activityInfo.packageName,
                            info.activityInfo.applicationInfo.versionCode, mService.mProcessStats);
      //21.静态广播都是走processCurBroadcastLocked处理的, 一次处理一个.
                    processCurBroadcastLocked(r, app);
                    return;
                }  catch (RuntimeException e) {
                    logBroadcastReceiverDiscardLocked(r);
                    finishReceiverLocked(r, r.resultCode, r.resultData,
                            r.resultExtras, r.resultAbort, false);
                    scheduleBroadcastsLocked();
                    r.state = BroadcastRecord.IDLE;
                    return;
                }
            }
 //22.程序走到这里,说明进程不存在,那么调用startProcessLocked启动进程,
            if ((r.curApp=mService.startProcessLocked(targetProcess,
                    info.activityInfo.applicationInfo, true,
                    r.intent.getFlags() | Intent.FLAG_FROM_BACKGROUND,
                    "broadcast", r.curComponent,
                    (r.intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0, false, false))
                            == null) {
//23.启动进场失败,   结束这个receiver,执行下一个.
                logBroadcastReceiverDiscardLocked(r);
                finishReceiverLocked(r, r.resultCode, r.resultData,
                        r.resultExtras, r.resultAbort, false);
                scheduleBroadcastsLocked();
                r.state = BroadcastRecord.IDLE;
                return;
            }
            mPendingBroadcast = r;
            mPendingBroadcastRecvIndex = recIdx;
        }
    }

如果是动态广播接收者(无序),会调用deliverToRegisteredReceiverLocked一次性处理,即遍历并行列表(mParallelBroadcasts)的每一个BroadcastRecord以及其中的receivers列表,是一个双重循环。
如果是静态广播接收者(有序),且对应进程已经创建,会调用processCurBroadcastLocked继续处理;
如果是静态广播接收者(有序),且对应进程尚未创建,会调用startProcessLocked创建进程,之后仍然会调用processCurBroadcastLocked继续处理
4.BroadcastQueue.deliverToRegisteredReceiverLocked 处理动态广播
主要是对发送者和接受者的权限检查

private final void deliverToRegisteredReceiverLocked(BroadcastRecord r,
            BroadcastFilter filter, boolean ordered) {
        boolean skip = false;
//1./权限判断,  检查发送者是否有权限,检查接收者是否有发送者所需的权限等等,
  //此处省略,不符合的skip==true,下面就return。
        if (filter.requiredPermission != null) {
            int perm = mService.checkComponentPermission(filter.requiredPermission,
                    r.callingPid, r.callingUid, -1, true);
            if (perm != PackageManager.PERMISSION_GRANTED) {
                skip = true;
            }
        }
        if (!skip && r.requiredPermission != null) {
            int perm = mService.checkComponentPermission(r.requiredPermission,
                    filter.receiverList.pid, filter.receiverList.uid, -1, true);
            if (perm != PackageManager.PERMISSION_GRANTED) {
                skip = true;
            }
        }
        if (r.appOp != AppOpsManager.OP_NONE) {
            int mode = mService.mAppOpsService.noteOperation(r.appOp,
                    filter.receiverList.uid, filter.packageName);
            if (mode != AppOpsManager.MODE_ALLOWED) {
                skip = true;
            }
        }
        if (!skip) {
            skip = !mService.mIntentFirewall.checkBroadcast(r.intent, r.callingUid,
                    r.callingPid, r.resolvedType, filter.receiverList.uid);
        }
        if (filter.receiverList.app == null || filter.receiverList.app.crashing) {
            skip = true;
        }

        if (!skip) {
//2.对有序广播的处理
            if (ordered) {
                r.receiver = filter.receiverList.receiver.asBinder();
                r.curFilter = filter;
                filter.receiverList.curBroadcast = r;
                r.state = BroadcastRecord.CALL_IN_RECEIVE;
                if (filter.receiverList.app != null) {
                    r.curApp = filter.receiverList.app;
                    filter.receiverList.app.curReceiver = r;
                    mService.updateOomAdjLocked(r.curApp);
                }
            }
            try {
                if (DEBUG_BROADCAST_LIGHT) {
                    int seq = r.intent.getIntExtra("seq", -1);
                }
//3.处理广播,filter.receiverList.receiver对应的是客户端ReceiverDispatcher的Binder实体——InnerReceiver
                performReceiveLocked(filter.receiverList.app, filter.receiverList.receiver,
                    new Intent(r.intent), r.resultCode, r.resultData,
                    r.resultExtras, r.ordered, r.initialSticky, r.userId);
                if (ordered) {
                    r.state = BroadcastRecord.CALL_DONE_RECEIVE;
                }
            } catch (RemoteException e) {
            }
        }
    }

5.BroadcastQueue.performReceiveLocked
这个方法会跨进程调用到IIntentReceiver的performReceive方法

 private static void performReceiveLocked(ProcessRecord app, IIntentReceiver receiver,
            Intent intent, int resultCode, String data, Bundle extras,
            boolean ordered, boolean sticky, int sendingUser) throws RemoteException {
        //1.如果app不为空,且app的applicationThread不为空,就跨进程通知applicationThread.
        if (app != null) {
            if (app.thread != null) {
   //2.这里最后也是执行了   receiver.performReceive方法.和第三部是一样的.
                app.thread.scheduleRegisteredReceiver(receiver, intent, resultCode,
                        data, extras, ordered, sticky, sendingUser, app.repProcState);
            } else {
                // Application has died. Receiver doesn't exist.
                throw new RemoteException("app.thread must not be null");
            }
        } else {
      //3.调用IIntentReceiver 的方法.
            receiver.performReceive(intent, resultCode, data, extras, ordered,
                    sticky, sendingUser);
        }
    }

6.LoadedApk.ReceiverDispatcher.InnerReceiver.performReceive

public void performReceive(Intent intent, int resultCode, String data,
                    Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
                LoadedApk.ReceiverDispatcher rd = mDispatcher.get();
                if (ActivityThread.DEBUG_BROADCAST) {
                    int seq = intent.getIntExtra("seq", -1);
                }
                if (rd != null) {
 //1.这里又回调ReceiverDispatcher的performReceive方法.
                    rd.performReceive(intent, resultCode, data, extras,
                            ordered, sticky, sendingUser);
                } else {
                    IActivityManager mgr = ActivityManagerNative.getDefault();
                    try {
                        if (extras != null) {
                            extras.setAllowFds(false);
                        }
                        mgr.finishReceiver(this, resultCode, data, extras, false);
                    } catch (RemoteException e) {
                        Slog.w(ActivityThread.TAG, "Couldn't finish broadcast to unregistered receiver");
                    }
                }
            }
        }

public void performReceive(Intent intent, int resultCode, String data,
                Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
            if (ActivityThread.DEBUG_BROADCAST) {
                int seq = intent.getIntExtra("seq", -1);
                
            }
            Args args = new Args(intent, resultCode, data, extras, ordered,
                    sticky, sendingUser);
   //2.post了一个消息给主线程
            if (!mActivityThread.post(args)) {
                if (mRegistered && ordered) {
                    IActivityManager mgr = ActivityManagerNative.getDefault();
                    if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
                            "Finishing sync broadcast to " + mReceiver);
                    args.sendFinished(mgr);
                }
            }
        }

6.Args.run Args继承了Runable,他的run方法会在主线程执行.直接看run方法.

  public void run() {
                final BroadcastReceiver receiver = mReceiver;
                final boolean ordered = mOrdered;
 
                final IActivityManager mgr = ActivityManagerNative.getDefault();
                final Intent intent = mCurIntent;
                mCurIntent = null;
                
                if (receiver == null || mForgotten) {
                    if (mRegistered && ordered) {
                        if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
                                "Finishing null broadcast to " + mReceiver);
                        sendFinished(mgr);
                    }
                    return;
                }

                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveReg");
                try {
                    ClassLoader cl =  mReceiver.getClass().getClassLoader();
                    intent.setExtrasClassLoader(cl);
                    setExtrasClassLoader(cl);
                    receiver.setPendingResult(this);
//1.这里最重要.调用了receiver的onReceive方法.实现的广播的发送
                    receiver.onReceive(mContext, intent);
                } catch (Exception e) {
                    if (mRegistered && ordered) {
                        if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
                                "Finishing failed broadcast to " + mReceiver);
                        sendFinished(mgr);
                    }
                    if (mInstrumentation == null ||
                            !mInstrumentation.onException(mReceiver, e)) {
                        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                        throw new RuntimeException(
                            "Error receiving broadcast " + intent
                            + " in " + mReceiver, e);
                    }
                }
                
                if (receiver.getPendingResult() != null) {
                    finish();
                }
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
            }
        }

到此.deliverToRegisteredReceiverLocked处理动态广播就结束了.

7.BroadcastQueue.processCurBroadcastLocked
用来处理静态广播

private final void processCurBroadcastLocked(BroadcastRecord r,
            ProcessRecord app) throws RemoteException {
       
        if (app.thread == null) {
            throw new RemoteException();
        }
        r.receiver = app.thread.asBinder();
        r.curApp = app;
        app.curReceiver = r;
//1.更新进程相关信息
        app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_RECEIVER);
        mService.updateLruProcessLocked(app, false, null);
        mService.updateOomAdjLocked();

        // Tell the application to launch this receiver.
//2.告诉客户端启动这个receiver
        r.intent.setComponent(r.curComponent);

        boolean started = false;
        try {
          
            mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
//3.最后调用ActivityThread的相关方法
            app.thread.scheduleReceiver(new Intent(r.intent), r.curReceiver,
                    mService.compatibilityInfoForPackageLocked(r.curReceiver.applicationInfo),
                    r.resultCode, r.resultData, r.resultExtras, r.ordered, r.userId,
                    app.repProcState);
           
            started = true;
        } finally {
            
        }
    }

8.ActivityThread.scheduleReceiver
本质是发送了一个msg给主线程.

    public final void scheduleReceiver(Intent intent, ActivityInfo info,
                CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
                boolean sync, int sendingUser, int processState) {
            updateProcessState(processState, false);
            ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
                    sync, false, mAppThread.asBinder(), sendingUser);
            r.info = info;
            r.compatInfo = compatInfo;
            sendMessage(H.RECEIVER, r);
        }

9.ActivityThrad.handleReceiver
反射创建receiver类,然后调用他的onReceive方法.

private void handleReceiver(ReceiverData data) {
     
      // 这个最初就是在processNextBroadcast处理静态注册的ResolveInfo时,new的ComponentName。
       String component = data.intent.getComponent().getClassName();

       LoadedApk packageInfo = getPackageInfoNoCheck(
               data.info.applicationInfo, data.compatInfo);

       IActivityManager mgr = ActivityManagerNative.getDefault();

       BroadcastReceiver receiver;
       try {
       //反射出BroadcastReceiver
           java.lang.ClassLoader cl = packageInfo.getClassLoader();
           data.intent.setExtrasClassLoader(cl);
           data.intent.prepareToEnterProcess();
           data.setExtrasClassLoader(cl);
           receiver = (BroadcastReceiver)cl.loadClass(component).newInstance();
       } catch (Exception e) {    
       }

       try {
           Application app = packageInfo.makeApplication(false, mInstrumentation);
           ContextImpl context = (ContextImpl)app.getBaseContext();
           sCurrentBroadcastIntent.set(data.intent);
           receiver.setPendingResult(data);
       //这个和动态的不一样,静态的广播onReceive方法中的context是RestrictedContext
           receiver.onReceive(context.getReceiverRestrictedContext(),
                   data.intent);
       } catch (Exception e) {
       } finally {
           sCurrentBroadcastIntent.set(null);
       }

       if (receiver.getPendingResult() != null) {
           data.finish();
       }
   }

上一篇: day8字符串

下一篇: Java 8 教程