android 广播源码分析

源码路径/frameworks/base/core/java/android/content/

frameworks/base/core/java/android/app/

一.android中使用

1>发送

sendBroadcast //发送标准广播
sendOrderedBroadcast  //发送有序广播

源码中为调用ContextImpl中的sendBroadcast ,源码如下

public void sendBroadcast(Intent intent) {
       warnIfCallingFromSystemProcess();
       String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
       try {
           intent.prepareToLeaveProcess(this);
           ActivityManager.getService().broadcastIntent(  //ActivityManagerService
                   mMainThread.getApplicationThread(), intent, resolvedType, null,
                   Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, null, false, false,
                   getUserId());
       } catch (RemoteException e) {
           throw e.rethrowFromSystemServer();
       }
   }

ActivityManagerService中的broadcastIntent
→broadcastIntentLocked, 里面有很多权限判断,这里以自定义广播为例

if ((receivers != null && receivers.size() > 0)
                || resultTo != null) {
            BroadcastQueue queue = broadcastQueueForIntent(intent); //添加到 BroadcastQueue 中
            BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
                    callerPackage, callingPid, callingUid, callerInstantApp, resolvedType,
                    requiredPermissions, appOp, brOptions, receivers, resultTo, resultCode,
                    resultData, resultExtras, ordered, sticky, false, userId,
                    allowBackgroundActivityStarts, timeoutExempt);
 
            if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r);
 
            final BroadcastRecord oldRecord =
                    replacePending ? queue.replaceOrderedBroadcastLocked(r) : null;
            if (oldRecord != null) {
                // Replaced, fire the result-to receiver.
                if (oldRecord.resultTo != null) {
                    final BroadcastQueue oldQueue = broadcastQueueForIntent(oldRecord.intent);
                    try {
                        oldQueue.performReceiveLocked(oldRecord.callerApp, oldRecord.resultTo,
                                oldRecord.intent,
                                Activity.RESULT_CANCELED, null, null,
                                false, false, oldRecord.userId);
                    } catch (RemoteException e) {
                        Slog.w(TAG, "Failure ["
                                + queue.mQueueName + "] sending broadcast result of "
                                + intent, e);
 
                    }
                }
            } else {
                queue.enqueueOrderedBroadcastLocked(r);
                queue.scheduleBroadcastsLocked(); //发出
            }
        } else {
            // There was nobody interested in the broadcast, but we still want to record
            // that it happened.
            if (intent.getComponent() == null && intent.getPackage() == null
                    && (intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
                // This was an implicit broadcast... let's record it for posterity.
                addBroadcastStatLocked(intent.getAction(), callerPackage, 0, 0, 0);
            }
        }

查看BroadcastQueue 中的scheduleBroadcastsLocked

public void scheduleBroadcastsLocked() {
        if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Schedule broadcasts ["
                + mQueueName + "]: current="
                + mBroadcastsScheduled);
 
        if (mBroadcastsScheduled) {
            return;
        }
        mHandler.sendMessage(mHandler.obtainMessage(BROADCAST_INTENT_MSG, this)); //这里使用了Handler机制,mHandler为BroadcastHandler
        mBroadcastsScheduled = true;
    }
//handleMessage
public void handleMessage(Message msg) {
            switch (msg.what) {
                case BROADCAST_INTENT_MSG: {
                    if (DEBUG_BROADCAST) Slog.v(
                            TAG_BROADCAST, "Received BROADCAST_INTENT_MSG ["
                            + mQueueName + "]");
                    processNextBroadcast(true);//执行这
                } break;
                case BROADCAST_TIMEOUT_MSG: {
                    synchronized (mService) {
                        broadcastTimeoutLocked(true);
                    }
                } break;
            }
        }

重点关注processNextBroadcast

后续逻辑参考https://www.jianshu.com/p/adc4faa000b9
2>注册监听

receiver =new MyReceicer();
        IntentFilter fliter =new IntentFilter("send");
        registerReceiver(receiver,fliter);
public class MyReceicer extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: " +intent);
        }
    }

源码逻辑与sendBroadcast 相似,调用到ActivityManagerService中的registerReceiver
3>整个过程逻辑图
在这里插入图片描述
堆栈打印
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值