Android应用程序注册广播接收器(registerReceiver)的过程分析

简介:

       前面我们介绍了Android系统的广播机制,从本质来说,它是一种消息订阅/发布机制,因此,使用这种消息驱动模型的第一步便是订阅消息;而对Android应用程序来说,订阅消息其实就是注册广播接收器,本文将探讨Android应用程序是如何注册广播接收器以及把广播接收器注册到哪里去的。

        在Android的广播机制中,ActivityManagerService扮演着广播中心的角色,负责系统中所有广播的注册和发布操作,因此,Android应用程序注册广播接收器的过程就把是广播接收器注册到ActivityManagerService的过程。Android应用程序是通过调用ContextWrapper类的registerReceiver函数来把广播接收器BroadcastReceiver注册到ActivityManagerService中去的,而ContextWrapper类本身又借助ContextImpl类来注册广播接收器。

        在Android应用程序框架中,Activity和Service类都继承了ContextWrapper类,因此,我们可以在Activity或者Service的子类中调用registerReceiver函数来注册广播接收器。Activity、Service、ContextWrapper和ContextImpl这四个类的关系可以参考前面Android系统在新进程中启动自定义服务过程(startService)的原理分析一文中描述的Activity类图。

        这篇文章还是继续以实例来进行情景分析,所用到的例子便是上一篇文章Android系统中的广播(Broadcast)机制简要介绍和学习计划里面介绍的应用程序了,所以希望读者在继续阅读本文之前,先看看这篇文章;又由于Android应用程序是把广播接器注册到ActivityManagerService中去的,因此,这里又会涉入到Binder进程间通信机制,所以希望读者对Android系统的Binder进程间通信机制有所了解,具体请参考Android进程间通信(IPC)机制Binder简要介绍和学习计划一文。

        开始进入主题了,在Android系统中的广播(Broadcast)机制简要介绍和学习计划一文所介绍的例子中,注册广播接收器的操作是MainActivity发起的,我们先来看看注册过程的序列图:

      在分析这个序列图之前,我们先来看一下MainActivity是如何调用registerReceiver函数来注册广播接收器的:

 
 
  1. public class MainActivity extends Activity implements OnClickListener {     
  2.     ......   
  3.    
  4.     @Override      
  5.     public void onResume() {     
  6.         super.onResume();     
  7.    
  8.         IntentFilter counterActionFilter = new IntentFilter(CounterService.BROADCAST_COUNTER_ACTION);     
  9.         registerReceiver(counterActionReceiver, counterActionFilter);     
  10.     }    
  11.    
  12.     ......   
  13.    
  14. }   

       MainActivity在onResume函数里,通过其父类ContextWrapper的registerReceiver函数注册了一个BroadcastReceiver实例counterActionReceiver,并且通过IntentFilter实例counterActionFilter告诉ActivityManagerService,它要订阅的广播是CounterService.BROADCAST_COUNTER_ACTION类型的,这样,ActivityManagerService在收到CounterService.BROADCAST_COUNTER_ACTION类型的广播时,就会分发给counterActionReceiver实例的onReceive函数。

 

        接下来,就开始分析注册过程中的每一个步骤了。

        Step 1. ContextWrapper.registerReceiver

        这个函数实现在frameworks/base/core/java/android/content/ContextWrapper.java文件中:

 
 
  1. public class ContextWrapper extends Context {   
  2.     Context mBase;   
  3.     ......   
  4.    
  5.     @Override   
  6.     public Intent registerReceiver(   
  7.         BroadcastReceiver receiver, IntentFilter filter) {   
  8.         return mBase.registerReceiver(receiver, filter);   
  9.     }   
  10.    
  11.     ......   
  12.    
  13. }   

 

        这里的成员变量mBase是一个ContextImpl实例,想知道为什么,可以回过头去看看Android应用程序启动过程源代码分析这篇文章>~<。

 

        Step 2. ContextImpl.registerReceiver

        这个函数实现在frameworks/base/core/java/android/app/ContextImpl.java文件中:

 
 
  1. class ContextImpl extends Context {   
  2.     ......   
  3.    
  4.     @Override   
  5.     public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {   
  6.         return registerReceiver(receiver, filter, nullnull);   
  7.     }   
  8.    
  9.     @Override   
  10.     public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,   
  11.             String broadcastPermission, Handler scheduler) {   
  12.         return registerReceiverInternal(receiver, filter, broadcastPermission,   
  13.             scheduler, getOuterContext());   
  14.     }   
  15.    
  16.     private Intent registerReceiverInternal(BroadcastReceiver receiver,   
  17.             IntentFilter filter, String broadcastPermission,   
  18.             Handler scheduler, Context context) {   
  19.         IIntentReceiver rd = null;   
  20.         if (receiver != null) {   
  21.             if (mPackageInfo != null && context != null) {   
  22.                 if (scheduler == null) {   
  23.                     scheduler = mMainThread.getHandler();   
  24.                 }   
  25.                 rd = mPackageInfo.getReceiverDispatcher(   
  26.                     receiver, context, scheduler,   
  27.                     mMainThread.getInstrumentation(), true);   
  28.             } else {   
  29.                 ......   
  30.             }   
  31.         }   
  32.         try {   
  33.             return ActivityManagerNative.getDefault().registerReceiver(   
  34.                     mMainThread.getApplicationThread(),   
  35.                     rd, filter, broadcastPermission);   
  36.         } catch (RemoteException e) {   
  37.                 return null;   
  38.         }   
  39.     }   
  40.    
  41.     ......   
  42.    
  43. }   

 

        通过两个函数的中转,最终就进入到ContextImpl.registerReceiverInternal这个函数来了。这里的成员变量mPackageInfo是一个LoadedApk实例,它是用来负责处理广播的接收的,在后面一篇文章讲到广播的发送时(sendBroadcast),会详细描述。参数broadcastPermission和scheduler都为null,而参数context是上面的函数通过调用函数getOuterContext得到的,这里它就是指向MainActivity了,因为MainActivity是继承于Context类的,因此,这里用Context类型来引用。

 

        由于条件mPackageInfo != null和context != null都成立,而且条件scheduler == null也成立,于是就调用mMainThread.getHandler来获得一个Handler了,这个Hanlder是后面用来分发ActivityManagerService发送过的广播用的。这里的成员变量mMainThread是一个ActivityThread实例,在前面Android应用程序启动过程源代码分析这篇文章也描述过了。我们先来看看ActivityThread.getHandler函数的实现,然后再回过头来继续分析ContextImpl.registerReceiverInternal函数。

        Step 3. ActivityThread.getHandler

        这个函数实现在frameworks/base/core/java/android/app/ActivityThread.java文件中:

 
 
  1. public final class ActivityThread {   
  2.     ......   
  3.    
  4.     final H mH = new H();   
  5.    
  6.     private final class H extends Handler {   
  7.         ......   
  8.    
  9.         public void handleMessage(Message msg) {   
  10.             ......   
  11.    
  12.             switch (msg.what) {   
  13.             ......   
  14.             }   
  15.    
  16.             ......   
  17.         }   
  18.    
  19.         ......   
  20.    
  21.     }   
  22.    
  23.     ......   
  24.    
  25.     final Handler getHandler() {   
  26.         return mH;   
  27.     }   
  28.    
  29.     ......   
  30.    
  31. }   

 

       有了这个Handler之后,就可以分发消息给应用程序处理了。

 

        再回到上一步的ContextImpl.registerReceiverInternal函数中,它通过mPackageInfo.getReceiverDispatcher函数获得一个IIntentReceiver接口对象rd,这是一个Binder对象,接下来会把它传给ActivityManagerService,ActivityManagerService在收到相应的广播时,就是通过这个Binder对象来通知MainActivity来接收的。

        我们也是先来看一下mPackageInfo.getReceiverDispatcher函数的实现,然后再回过头来继续分析ContextImpl.registerReceiverInternal函数。

        Step 4. LoadedApk.getReceiverDispatcher

        这个函数实现在frameworks/base/core/java/android/app/LoadedApk.java文件中:

 
 
  1. final class LoadedApk {   
  2.     ......   
  3.    
  4.     public IIntentReceiver getReceiverDispatcher(BroadcastReceiver r,   
  5.             Context context, Handler handler,   
  6.             Instrumentation instrumentation, boolean registered) {   
  7.         synchronized (mReceivers) {   
  8.             LoadedApk.ReceiverDispatcher rd = null;   
  9.             HashMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> map = null;   
  10.             if (registered) {   
  11.                 map = mReceivers.get(context);   
  12.                 if (map != null) {   
  13.                     rd = map.get(r);   
  14.                 }   
  15.             }   
  16.             if (rd == null) {   
  17.                 rd = new ReceiverDispatcher(r, context, handler,   
  18.                     instrumentation, registered);   
  19.                 if (registered) {   
  20.                     if (map == null) {   
  21.                         map = new HashMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher>();   
  22.                         mReceivers.put(context, map);   
  23.                     }   
  24.                     map.put(r, rd);   
  25.                 }   
  26.             } else {   
  27.                 rd.validate(context, handler);   
  28.             }   
  29.             return rd.getIIntentReceiver();   
  30.         }   
  31.     }   
  32.    
  33.     ......   
  34.    
  35.     static final class ReceiverDispatcher {   
  36.    
  37.         final static class InnerReceiver extends IIntentReceiver.Stub {   
  38.             final WeakReference<LoadedApk.ReceiverDispatcher> mDispatcher;   
  39.             ......   
  40.    
  41.             InnerReceiver(LoadedApk.ReceiverDispatcher rd, boolean strong) {   
  42.                 mDispatcher = new WeakReference<LoadedApk.ReceiverDispatcher>(rd);   
  43.                 ......   
  44.             }   
  45.    
  46.             ......   
  47.         }   
  48.    
  49.         ......   
  50.    
  51.         final IIntentReceiver.Stub mIIntentReceiver;   
  52.         final Handler mActivityThread;   
  53.    
  54.         ......   
  55.    
  56.         ReceiverDispatcher(BroadcastReceiver receiver, Context context,   
  57.                 Handler activityThread, Instrumentation instrumentation,   
  58.                 boolean registered) {   
  59.             ......   
  60.    
  61.             mIIntentReceiver = new InnerReceiver(this, !registered);   
  62.             mActivityThread = activityThread;   
  63.                
  64.             ......   
  65.         }   
  66.    
  67.         ......   
  68.    
  69.         IIntentReceiver getIIntentReceiver() {   
  70.             return mIIntentReceiver;   
  71.         }   
  72.    
  73.     }   
  74.    
  75.     ......   
  76.    
  77. }   

 

 

      在LoadedApk.getReceiverDispatcher函数中,首先看一下参数r是不是已经有相应的ReceiverDispatcher存在了,如果有,就直接返回了,否则就新建一个ReceiverDispatcher,并且以r为Key值保在一个HashMap中,而这个HashMap以Context,这里即为MainActivity为Key值保存在LoadedApk的成员变量mReceivers中,这样,只要给定一个Activity和BroadcastReceiver,就可以查看LoadedApk里面是否已经存在相应的广播接收发布器ReceiverDispatcher了。

        在新建广播接收发布器ReceiverDispatcher时,会在构造函数里面创建一个InnerReceiver实例,这是一个Binder对象,实现了IIntentReceiver接口,可以通过ReceiverDispatcher.getIIntentReceiver函数来获得,获得后就会把它传给ActivityManagerService,以便接收广播。在ReceiverDispatcher类的构造函数中,还会把传进来的Handle类型的参数activityThread保存下来,以便后面在分发广播的时候使用。

        现在,再回到ContextImpl.registerReceiverInternal函数,在获得了IIntentReceiver类型的Binder对象后,就开始要把它注册到ActivityManagerService中去了。

        Step 5. ActivityManagerProxy.registerReceiver

        这个函数实现在frameworks/base/core/java/android/app/ActivityManagerNative.java文件中:

 
 
  1. class ActivityManagerProxy implements IActivityManager   
  2. {   
  3.     ......   
  4.    
  5.     public Intent registerReceiver(IApplicationThread caller,   
  6.             IIntentReceiver receiver,   
  7.             IntentFilter filter, String perm) throws RemoteException   
  8.     {   
  9.         Parcel data = Parcel.obtain();   
  10.         Parcel reply = Parcel.obtain();   
  11.         data.writeInterfaceToken(IActivityManager.descriptor);   
  12.         data.writeStrongBinder(caller != null ? caller.asBinder() : null);   
  13.         data.writeStrongBinder(receiver != null ? receiver.asBinder() : null);   
  14.         filter.writeToParcel(data, 0);   
  15.         data.writeString(perm);   
  16.         mRemote.transact(REGISTER_RECEIVER_TRANSACTION, data, reply, 0);   
  17.         reply.readException();   
  18.         Intent intent = null;   
  19.         int haveIntent = reply.readInt();   
  20.         if (haveIntent != 0) {   
  21.             intent = Intent.CREATOR.createFromParcel(reply);   
  22.         }   
  23.         reply.recycle();   
  24.         data.recycle();   
  25.         return intent;   
  26.     }   
  27.    
  28.     ......   
  29.    
  30. }   

 

         这个函数通过Binder驱动程序就进入到ActivityManagerService中的registerReceiver函数中去了。

 

         Step 6. ActivityManagerService.registerReceiver

         这个函数实现在frameworks/base/services/java/com/android/server/am/ActivityManagerService.java文件中:

 
 
  1. public final class ActivityManagerService extends ActivityManagerNative   
  2.         implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {   
  3.     ......   
  4.    
  5.     public Intent registerReceiver(IApplicationThread caller,   
  6.             IIntentReceiver receiver, IntentFilter filter, String permission) {   
  7.         synchronized(this) {   
  8.             ProcessRecord callerApp = null;   
  9.             if (caller != null) {   
  10.                 callerApp = getRecordForAppLocked(caller);   
  11.                 if (callerApp == null) {   
  12.                     ......   
  13.                 }   
  14.             }   
  15.    
  16.             List allSticky = null;   
  17.    
  18.             // Look for any matching sticky broadcasts...   
  19.             Iterator actions = filter.actionsIterator();   
  20.             if (actions != null) {   
  21.                 while (actions.hasNext()) {   
  22.                     String action = (String)actions.next();   
  23.                     allSticky = getStickiesLocked(action, filter, allSticky);   
  24.                 }   
  25.             } else {   
  26.                 ......   
  27.             }   
  28.    
  29.             // The first sticky in the list is returned directly back to   
  30.             // the client.   
  31.             Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;   
  32.    
  33.             ......   
  34.    
  35.             if (receiver == null) {   
  36.                 return sticky;   
  37.             }   
  38.    
  39.             ReceiverList rl   
  40.                 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());   
  41.             if (rl == null) {   
  42.                 rl = new ReceiverList(this, callerApp,   
  43.                     Binder.getCallingPid(),   
  44.                     Binder.getCallingUid(), receiver);   
  45.    
  46.                 if (rl.app != null) {   
  47.                     rl.app.receivers.add(rl);   
  48.                 } else {   
  49.                     ......   
  50.                 }   
  51.                 mRegisteredReceivers.put(receiver.asBinder(), rl);   
  52.             }   
  53.    
  54.             BroadcastFilter bf = new BroadcastFilter(filter, rl, permission);   
  55.             rl.add(bf);   
  56.             ......   
  57.             mReceiverResolver.addFilter(bf);   
  58.    
  59.             // Enqueue broadcasts for all existing stickies that match   
  60.             // this filter.   
  61.             if (allSticky != null) {   
  62.                 ......   
  63.             }   
  64.    
  65.             return sticky;   
  66.         }   
  67.     }   
  68.    
  69.     ......   
  70.    
  71. }   

 

     函数首先是获得调用registerReceiver函数的应用程序进程记录块:

 
 
  1.    ProcessRecord callerApp = null;   
  2.    if (caller != null) {   
  3. callerApp = getRecordForAppLocked(caller);   
  4. if (callerApp == null) {   
  5.     ......   
  6.        }   
  7.    }   

        这里得到的便是上一篇文章Android系统中的广播(Broadcast)机制简要介绍和学习计划里面介绍的应用程序Broadcast的进程记录块了,MainActivity就是在里面启动起来的。

 
 
  1.    List allSticky = null;   
  2.    
  3.    // Look for any matching sticky broadcasts...   
  4.    Iterator actions = filter.actionsIterator();   
  5.    if (actions != null) {   
  6. while (actions.hasNext()) {   
  7.     String action = (String)actions.next();   
  8.     allSticky = getStickiesLocked(action, filter, allSticky);   
  9. }   
  10.    } else {   
  11. ......   
  12.    }   
  13.    
  14.    // The first sticky in the list is returned directly back to   
  15.    // the client.   
  16.    Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;   

       这里传进来的filter只有一个action,就是前面描述的CounterService.BROADCAST_COUNTER_ACTION了,这里先通过getStickiesLocked函数查找一下有没有对应的sticky intent列表存在。什么是Sticky Intent呢?我们在最后一次调用sendStickyBroadcast函数来发送某个Action类型的广播时,系统会把代表这个广播的Intent保存下来,这样,后来调用registerReceiver来注册相同Action类型的广播接收器,就会得到这个最后发出的广播。这就是为什么叫做Sticky Intent了,这个最后发出的广播虽然被处理完了,但是仍然被粘住在ActivityManagerService中,以便下一个注册相应Action类型的广播接收器还能继承处理。

 

        这里,假设我们不使用sendStickyBroadcast来发送CounterService.BROADCAST_COUNTER_ACTION类型的广播,于是,这里得到的allSticky和sticky都为null了。

        继续往下看,这里传进来的receiver不为null,于是,继续往下执行:

 
 
  1.    ReceiverList rl   
  2. = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());   
  3.    if (rl == null) {   
  4. rl = new ReceiverList(this, callerApp,   
  5.     Binder.getCallingPid(),   
  6.     Binder.getCallingUid(), receiver);   
  7.    
  8. if (rl.app != null) {   
  9.     rl.app.receivers.add(rl);   
  10. else {   
  11.     ......   
  12. }   
  13. mRegisteredReceivers.put(receiver.asBinder(), rl);   
  14.    }   

 

        这里其实就是把广播接收器receiver保存一个ReceiverList列表中,这个列表的宿主进程是rl.app,这里就是MainActivity所在的进程了,在ActivityManagerService中,用一个进程记录块来表示这个应用程序进程,它里面有一个列表receivers,专门用来保存这个进程注册的广播接收器。接着,又把这个ReceiverList列表以receiver为Key值保存在ActivityManagerService的成员变量mRegisteredReceivers中,这些都是为了方便在收到广播时,快速找到对应的广播接收器的。

 

        再往下看:

 
 
  1. BroadcastFilter bf = new BroadcastFilter(filter, rl, permission);   
  2. rl.add(bf);   
  3. ......   
  4. mReceiverResolver.addFilter(bf);   

 

        上面只是把广播接收器receiver保存起来了,但是还没有把它和filter关联起来,这里就创建一个BroadcastFilter来把广播接收器列表rl和filter关联起来,然后保存在ActivityManagerService中的成员变量mReceiverResolver中去。

 

        这样,广播接收器注册的过程就介绍完了,比较简单,但是工作又比较琐碎,主要就是将广播接收器receiver及其要接收的广播类型filter保存在ActivityManagerService中,以便以后能够接收到相应的广播并进行处理,在下一篇文章,我们将详细分析这个过程,敬请关注。







本文转自 Luoshengyang 51CTO博客,原文链接:http://blog.51cto.com/shyluo/966376,如需转载请自行联系原作者
目录
相关文章
|
20天前
|
移动开发 Java Android开发
构建高效Android应用:探究Kotlin与Java的性能差异
【4月更文挑战第3天】在移动开发领域,性能优化一直是开发者关注的焦点。随着Kotlin的兴起,其在Android开发中的地位逐渐上升,但关于其与Java在性能方面的对比,尚无明确共识。本文通过深入分析并结合实际测试数据,探讨了Kotlin与Java在Android平台上的性能表现,揭示了在不同场景下两者的差异及其对应用性能的潜在影响,为开发者在选择编程语言时提供参考依据。
|
21天前
|
数据库 Android开发 开发者
构建高效Android应用:Kotlin协程的实践指南
【4月更文挑战第2天】随着移动应用开发的不断进步,开发者们寻求更流畅、高效的用户体验。在Android平台上,Kotlin语言凭借其简洁性和功能性赢得了开发社区的广泛支持。特别是Kotlin协程,作为一种轻量级的并发处理方案,使得异步编程变得更加简单和直观。本文将深入探讨Kotlin协程的核心概念、使用场景以及如何将其应用于Android开发中,以提高应用性能和响应能力。通过实际案例分析,我们将展示协程如何简化复杂任务,优化资源管理,并为最终用户提供更加流畅的体验。
|
21天前
|
开发框架 安全 Android开发
探索安卓系统的新趋势:智能家居应用的蓬勃发展
随着智能家居概念的兴起,安卓系统在智能家居应用领域的应用日益广泛。本文将探讨安卓系统在智能家居应用开发方面的最新趋势和创新,以及其对用户生活的影响。
14 2
|
24天前
|
缓存 监控 Java
构建高效Android应用:从优化用户体验到提升性能
在竞争激烈的移动应用市场中,为用户提供流畅和高效的体验是至关重要的。本文深入探讨了如何通过多种技术手段来优化Android应用的性能,包括UI响应性、内存管理和多线程处理。同时,我们还将讨论如何利用最新的Android框架和工具来诊断和解决性能瓶颈。通过实例分析和最佳实践,读者将能够理解并实施必要的优化策略,以确保他们的应用在保持响应迅速的同时,还能够有效地利用系统资源。
|
25天前
|
Java Android开发
Android 开发获取通知栏权限时会出现两个应用图标
Android 开发获取通知栏权限时会出现两个应用图标
12 0
|
28天前
|
搜索推荐 Android开发 iOS开发
安卓与iOS系统的用户界面设计对比分析
本文通过对安卓和iOS两大操作系统的用户界面设计进行对比分析,探讨它们在设计理念、交互方式、视觉风格等方面的差异及各自特点,旨在帮助读者更好地理解和评估不同系统的用户体验。
19 1
|
29天前
|
编解码 算法 Java
构建高效的Android应用:内存优化策略详解
随着智能手机在日常生活和工作中的普及,用户对移动应用的性能要求越来越高。特别是对于Android开发者来说,理解并实践内存优化是提升应用程序性能的关键步骤。本文将深入探讨针对Android平台的内存管理机制,并提供一系列实用的内存优化技巧,以帮助开发者减少内存消耗,避免常见的内存泄漏问题,并确保应用的流畅运行。
|
22天前
|
Java Android开发 开发者
构建高效Android应用:Kotlin协程的实践与优化
在响应式编程范式日益盛行的今天,Kotlin协程作为一种轻量级的线程管理解决方案,为Android开发带来了性能和效率的双重提升。本文旨在探讨Kotlin协程的核心概念、实践方法及其在Android应用中的优化策略,帮助开发者构建更加流畅和高效的应用程序。通过深入分析协程的原理与应用场景,结合实际案例,本文将指导读者如何优雅地解决异步任务处理,避免阻塞UI线程,从而优化用户体验。
|
27天前
|
Java 编译器 Android开发
构建高效Android应用:探究Kotlin与Java的性能差异
在开发高性能的Android应用时,选择合适的编程语言至关重要。近年来,Kotlin因其简洁性和功能性受到开发者的青睐,但其性能是否与传统的Java相比有所不足?本文通过对比分析Kotlin与Java在Android平台上的运行效率,揭示二者在编译速度、运行时性能及资源消耗方面的具体差异,并探讨在实际项目中如何做出最佳选择。
17 4
|
5天前
|
缓存 移动开发 Android开发
构建高效Android应用:从优化用户体验到提升性能表现
【4月更文挑战第18天】 在移动开发的世界中,打造一个既快速又流畅的Android应用并非易事。本文深入探讨了如何通过一系列创新的技术策略来提升应用性能和用户体验。我们将从用户界面(UI)设计的简约性原则出发,探索响应式布局和Material Design的实践,再深入剖析后台任务处理、内存管理和电池寿命优化的技巧。此外,文中还将讨论最新的Android Jetpack组件如何帮助开发者更高效地构建高质量的应用。此内容不仅适合经验丰富的开发者深化理解,也适合初学者构建起对Android高效开发的基础认识。
2 0