Android应用程序绑定服务(bindService)的过程源代码分析(3)

简介:
Step 17. ApplicationThread.scheduleBindService
         这个函数定义在frameworks/base/core/java/android/app/ActivityThread.java文件中:
 
 
  1. public final class ActivityThread {   
  2.     ......   
  3.    
  4.     public final void scheduleBindService(IBinder token, Intent intent,   
  5.             boolean rebind) {   
  6.         BindServiceData s = new BindServiceData();   
  7.         s.token = token;   
  8.         s.intent = intent;   
  9.         s.rebind = rebind;   
  10.    
  11.         queueOrSendMessage(H.BIND_SERVICE, s);   
  12.     }   
  13.    
  14.     ......   
  15. }   
    这里像上面的Step 11一样,调用ActivityThread.queueOrSendMessage函数来发送消息。
        Step 18. ActivityThread.queueOrSendMessage

 

        参考上面的Step 11,不过这里的消息类型是H.BIND_SERVICE。

        Step 19. H.sendMessage

        参考上面的Step 12,不过这里最终在H.handleMessage函数中,要处理的消息类型是H.BIND_SERVICE:

 
  
  1. public final class ActivityThread {   
  2.     ......   
  3.    
  4.     private final class H extends Handler {   
  5.         ......   
  6.    
  7.         public void handleMessage(Message msg) {   
  8.             ......   
  9.             switch (msg.what) {   
  10.             ......   
  11.             case BIND_SERVICE:   
  12.                 handleBindService((BindServiceData)msg.obj);   
  13.                 break;   
  14.             ......   
  15.             }   
  16.         }   
  17.     }   
  18.    
  19.     ......   
  20. }   

       这里调用ActivityThread.handleBindService函数来进一步处理。

 

         Step 20. ActivityThread.handleBindService

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

 
 
  1. public final class ActivityThread {   
  2.     ......   
  3.    
  4.     private final void handleBindService(BindServiceData data) {   
  5.         Service s = mServices.get(data.token);   
  6.         if (s != null) {   
  7.             try {   
  8.                 data.intent.setExtrasClassLoader(s.getClassLoader());   
  9.                 try {   
  10.                     if (!data.rebind) {   
  11.                         IBinder binder = s.onBind(data.intent);   
  12.                         ActivityManagerNative.getDefault().publishService(   
  13.                             data.token, data.intent, binder);   
  14.                     } else {   
  15.                         ......   
  16.                     }   
  17.                     ......   
  18.                 } catch (RemoteException ex) {   
  19.                 }   
  20.             } catch (Exception e) {   
  21.                 ......   
  22.             }   
  23.         }   
  24.     }   
  25.    
  26.     ......   
  27. }   

 

        在前面的Step 13执行ActivityThread.handleCreateService函数中,已经将这个CounterService实例保存在mServices中,因此,这里首先通过data.token值将它取回来,保存在本地变量s中,接着执行了两个操作,一个操作是调用s.onBind,即CounterService.onBind获得一个Binder对象,另一个操作就是把这个Binder对象传递给ActivityManagerService。

 

        我们先看CounterService.onBind操作,然后再回到ActivityThread.handleBindService函数中来。

        Step 21. CounterService.onBind

        这个函数定义在Android系统中的广播(Broadcast)机制简要介绍和学习计划中一文中所介绍的应用程序Broadcast的工程目录下的src/shy/luo/broadcast/CounterService.java文件中:

 
 
  1. public class CounterService extends Service implements ICounterService {   
  2.     ......   
  3.    
  4.     private final IBinder binder = new CounterBinder();     
  5.    
  6.     public class CounterBinder extends Binder {     
  7.         public CounterService getService() {     
  8.             return CounterService.this;     
  9.         }     
  10.     }     
  11.    
  12.     @Override     
  13.     public IBinder onBind(Intent intent) {     
  14.         return binder;     
  15.     }     
  16.    
  17.     ......   
  18. }   

 

        这里的onBind函数返回一个是CounterBinder类型的Binder对象,它里面实现一个成员函数getService,用于返回CounterService接口。

 

        至此,应用程序绑定服务过程中的第二步CounterService.onBind就完成了。

        回到ActivityThread.handleBindService函数中,获得了这个CounterBinder对象后,就调用ActivityManagerProxy.publishService来通知MainActivity,CounterService已经连接好了。
        Step 22. ActivityManagerProxy.publishService

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

 
 
  1. class ActivityManagerProxy implements IActivityManager   
  2. {   
  3.     ......   
  4.    
  5.     public void publishService(IBinder token,   
  6.     Intent intent, IBinder service) throws RemoteException {   
  7.         Parcel data = Parcel.obtain();   
  8.         Parcel reply = Parcel.obtain();   
  9.         data.writeInterfaceToken(IActivityManager.descriptor);   
  10.         data.writeStrongBinder(token);   
  11.         intent.writeToParcel(data, 0);   
  12.         data.writeStrongBinder(service);   
  13.         mRemote.transact(PUBLISH_SERVICE_TRANSACTION, data, reply, 0);   
  14.         reply.readException();   
  15.         data.recycle();   
  16.         reply.recycle();   
  17.     }   
  18.    
  19.     ......   
  20. }   

 

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

 

         Step 23. ActivityManagerService.publishService

         这个函数定义在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 void publishService(IBinder token, Intent intent, IBinder service) {   
  6.         ......   
  7.         synchronized(this) {   
  8.             ......   
  9.             ServiceRecord r = (ServiceRecord)token;   
  10.             ......   
  11.    
  12.             ......   
  13.             if (r != null) {   
  14.                 Intent.FilterComparison filter   
  15.                     = new Intent.FilterComparison(intent);   
  16.                 IntentBindRecord b = r.bindings.get(filter);   
  17.                 if (b != null && !b.received) {   
  18.                     b.binder = service;   
  19.                     b.requested = true;   
  20.                     b.received = true;   
  21.                     if (r.connections.size() > 0) {   
  22.                         Iterator<ArrayList<ConnectionRecord>> it   
  23.                             = r.connections.values().iterator();   
  24.                         while (it.hasNext()) {   
  25.                             ArrayList<ConnectionRecord> clist = it.next();   
  26.                             for (int i=0; i<clist.size(); i++) {   
  27.                                 ConnectionRecord c = clist.get(i);   
  28.                                 ......   
  29.                                 try {   
  30.                                     c.conn.connected(r.name, service);   
  31.                                 } catch (Exception e) {   
  32.                                     ......   
  33.                                 }   
  34.                             }   
  35.                         }   
  36.                     }   
  37.                 }   
  38.    
  39.                 ......   
  40.             }   
  41.         }   
  42.     }   
  43.    
  44.     ......   
  45. }   

 

      这里传进来的参数token是一个ServiceRecord对象,它是在上面的Step 6中创建的,代表CounterServi

 
 
  1.    ServiceRecord s = res.record;   
  2.    
  3.    ......   
  4.    
  5.    ConnectionRecord c = new ConnectionRecord(b, activity,   
  6.     connection, flags, clientLabel, clientIntent);   
  7.    
  8.    IBinder binder = connection.asBinder();   
  9.    ArrayList<ConnectionRecord> clist = s.connections.get(binder);   
  10.    
  11.    if (clist == null) {   
  12. clist = new ArrayList<ConnectionRecord>();   
  13. s.connections.put(binder, clist);   
  14.    }   

   因此,这里可以从r.connections中将这个ConnectionRecord取出来:

 
 
  1.    Iterator<ArrayList<ConnectionRecord>> it   
  2. = r.connections.values().iterator();   
  3.    while (it.hasNext()) {   
  4. ArrayList<ConnectionRecord> clist = it.next();   
  5. for (int i=0; i<clist.size(); i++) {   
  6.         ConnectionRecord c = clist.get(i);   
  7.     ......   
  8.     try {   
  9.         c.conn.connected(r.name, service);   
  10.     } catch (Exception e) {   
  11.         ......   
  12.     }   
  13. }   
  14.    }   

        每一个ConnectionRecord里面都有一个成员变量conn,它的类型是IServiceConnection,是一个Binder对象的远程接口,这个Binder对象又是什么呢?这就是我们在Step 
4中创建的LoadedApk.ServiceDispatcher.InnerConnection对象了。因此,这里执行c.conn.connected函数后就会进入到LoadedApk.ServiceDispatcher.InnerConnection.connected函数中去了。

 

        Step 24. InnerConnection.connected

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

 
 
  1. final class LoadedApk {   
  2.     ......   
  3.    
  4.     static final class ServiceDispatcher {   
  5.         ......   
  6.    
  7.         private static class InnerConnection extends IServiceConnection.Stub {   
  8.             ......   
  9.    
  10.             public void connected(ComponentName name, IBinder service) throws RemoteException {   
  11.                 LoadedApk.ServiceDispatcher sd = mDispatcher.get();   
  12.                 if (sd != null) {   
  13.                     sd.connected(name, service);   
  14.                 }   
  15.             }   
  16.             ......   
  17.         }   
  18.    
  19.         ......   
  20.     }   
  21.    
  22.     ......   
  23. }   

 

     这里它将操作转发给ServiceDispatcher.connected函数。

 

         Step 25. ServiceDispatcher.connected

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

 
 
  1. final class LoadedApk {   
  2.     ......   
  3.    
  4.     static final class ServiceDispatcher {   
  5.         ......   
  6.    
  7.         public void connected(ComponentName name, IBinder service) {   
  8.             if (mActivityThread != null) {   
  9.                 mActivityThread.post(new RunConnection(name, service, 0));   
  10.             } else {   
  11.                 ......   
  12.             }   
  13.         }   
  14.    
  15.         ......   
  16.     }   
  17.    
  18.     ......   
  19. }   

 

        我们在前面Step 4中说到,这里的mActivityThread是一个Handler实例,它是通过ActivityThread.getHandler函数得到的,因此,调用它的post函数后,就会把一个消息放到ActivityThread的消息队列中去了。

 

        Step 26. H.post

        由于H类继承于Handler类,因此,这里实际执行的Handler.post函数,这个函数定义在frameworks/base/core/java/android/os/Handler.java文件,这里我们就不看了,有兴趣的读者可以自己研究一下,调用了这个函数之后,这个消息就真正地进入到ActivityThread的消息队列去了,与sendMessage把消息放在消息队列不一样的地方是,post方式发送的消息不是由这个Handler的handleMessage函数来处理的,而是由post的参数Runnable的run函数来处理的。这里传给post的参数是一个RunConnection类型的参数,它继承了Runnable类,因此,最终会调用RunConnection.run函数来处理这个消息。

       Step 27. RunConnection.run

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

 
 
  1. final class LoadedApk {   
  2.     ......   
  3.    
  4.     static final class ServiceDispatcher {   
  5.         ......   
  6.    
  7.         private final class RunConnection implements Runnable {   
  8.             ......   
  9.    
  10.             public void run() {   
  11.                 if (mCommand == 0) {   
  12.                     doConnected(mName, mService);   
  13.                 } else if (mCommand == 1) {   
  14.                     ......   
  15.                 }   
  16.             }   
  17.    
  18.             ......   
  19.         }   
  20.    
  21.         ......   
  22.     }   
  23.    
  24.     ......   
  25. }   

 

这里的mCommand值为0,于是就执行ServiceDispatcher.doConnected函数来进一步操作了。

 

        Step 28. ServiceDispatcher.doConnected
        这个函数定义在frameworks/base/core/java/android/app/LoadedApk.java文件中:

 
 
  1. final class LoadedApk {   
  2.     ......   
  3.    
  4.     static final class ServiceDispatcher {   
  5.         ......   
  6.    
  7.         public void doConnected(ComponentName name, IBinder service) {   
  8.             ......   
  9.    
  10.             // If there is a new service, it is now connected.   
  11.             if (service != null) {   
  12.                 mConnection.onServiceConnected(name, service);   
  13.             }   
  14.         }   
  15.    
  16.    
  17.         ......   
  18.     }   
  19.    
  20.     ......   
  21. }   

 

       这里主要就是执行成员变量mConnection的onServiceConnected函数,这里的mConnection变量的类型的ServiceConnection,它是在前面的Step 4中设置好的,这个ServiceConnection实例是MainActivity类内部创建的,在调用bindService函数时保存在LoadedApk.ServiceDispatcher类中,用它来换取一个IServiceConnection对象,传给ActivityManagerService。

 

        Step 29. ServiceConnection.onServiceConnected

        这个函数定义在Android系统中的广播(Broadcast)机制简要介绍和学习计划中一文中所介绍的应用程序Broadcast的工程目录下的src/shy/luo/broadcast/MainActivity.java文件中:

 
 
  1. public class MainActivity extends Activity implements OnClickListener {     
  2.     ......   
  3.    
  4.     private ServiceConnection serviceConnection = new ServiceConnection() {     
  5.         public void onServiceConnected(ComponentName className, IBinder service) {     
  6.             counterService = ((CounterService.CounterBinder)service).getService();     
  7.    
  8.             Log.i(LOG_TAG, "Counter Service Connected");     
  9.         }     
  10.         ......   
  11.     };     
  12.        
  13.     ......   
  14. }   

 

        这里传进来的参数service是一个Binder对象,就是前面在Step 21中从CounterService那里得到的ConterBinder对象,因此,这里可以把它强制转换为CounterBinder引用,然后调用它的getService函数。

 

        至此,应用程序绑定服务过程中的第三步MainActivity.ServiceConnection.onServiceConnection就完成了。

        Step 30. CounterBinder.getService

        这个函数定义在Android系统中的广播(Broadcast)机制简要介绍和学习计划中一文中所介绍的应用程序Broadcast的工程目录下的src/shy/luo/broadcast/CounterService.java文件中:

 
 
  1. public class CounterService extends Service implements ICounterService {     
  2.     ......   
  3.    
  4.     public class CounterBinder extends Binder {     
  5.         public CounterService getService() {     
  6.             return CounterService.this;     
  7.         }     
  8.     }     
  9.    
  10.     ......   
  11. }   

 

        这里就把CounterService接口返回给MainActivity了。

 

        至此,应用程序绑定服务过程中的第四步CounterService.CounterBinder.getService就完成了。

        这样,Android应用程序绑定服务(bindService)的过程的源代码分析就完成了,总结一下这个过程:

        1. Step 1 -  Step 14,MainActivity调用bindService函数通知ActivityManagerService,它要启动CounterService这个服务,ActivityManagerService于是在MainActivity所在的进程内部把CounterService启动起来,并且调用它的onCreate函数;

        2. Step 15 - Step 21,ActivityManagerService把CounterService启动起来后,继续调用CounterService的onBind函数,要求CounterService返回一个Binder对象给它;

        3. Step 22 - Step 29,ActivityManagerService从CounterService处得到这个Binder对象后,就把它传给MainActivity,即把这个Binder对象作为参数传递给MainActivity内部定义的ServiceConnection对象的onServiceConnected函数;

        4. Step 30,MainActivity内部定义的ServiceConnection对象的onServiceConnected函数在得到这个Binder对象后,就通过它的getService成同函数获得CounterService接口。







本文转自 Luoshengyang 51CTO博客,原文链接:http://blog.51cto.com/shyluo/966474,如需转载请自行联系原作者
目录
相关文章
|
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
|
1天前
|
Android开发
Android 11 添加Service服务SELinux问题
Android 11 添加Service服务SELinux问题
7 1
|
5天前
|
缓存 移动开发 Android开发
构建高效Android应用:从优化用户体验到提升性能表现
【4月更文挑战第18天】 在移动开发的世界中,打造一个既快速又流畅的Android应用并非易事。本文深入探讨了如何通过一系列创新的技术策略来提升应用性能和用户体验。我们将从用户界面(UI)设计的简约性原则出发,探索响应式布局和Material Design的实践,再深入剖析后台任务处理、内存管理和电池寿命优化的技巧。此外,文中还将讨论最新的Android Jetpack组件如何帮助开发者更高效地构建高质量的应用。此内容不仅适合经验丰富的开发者深化理解,也适合初学者构建起对Android高效开发的基础认识。
3 0
|
5天前
|
移动开发 Android开发 开发者
构建高效Android应用:采用Kotlin进行内存优化的策略
【4月更文挑战第18天】 在移动开发领域,性能优化一直是开发者关注的焦点。特别是对于Android应用而言,由于设备和版本的多样性,确保应用流畅运行且占用资源少是一大挑战。本文将探讨使用Kotlin语言开发Android应用时,如何通过内存优化来提升应用性能。我们将从减少不必要的对象创建、合理使用数据结构、避免内存泄漏等方面入手,提供实用的代码示例和最佳实践,帮助开发者构建更加高效的Android应用。
5 0
|
7天前
|
缓存 移动开发 Java
构建高效的Android应用:内存优化策略
【4月更文挑战第16天】 在移动开发领域,尤其是针对资源有限的Android设备,内存优化是提升应用性能和用户体验的关键因素。本文将深入探讨Android应用的内存管理机制,分析常见的内存泄漏问题,并提出一系列实用的内存优化技巧。通过这些策略的实施,开发者可以显著减少应用的内存占用,避免不必要的后台服务,以及提高垃圾回收效率,从而延长设备的电池寿命并确保应用的流畅运行。
|
9天前
|
搜索推荐 开发工具 Android开发
安卓即时应用(Instant Apps)开发指南
【4月更文挑战第14天】Android Instant Apps让用户体验部分应用功能而无需完整下载。开发者需将应用拆分成模块,基于已上线的基础应用构建。使用Android Studio的Instant Apps Feature Library定义模块特性,优化代码与资源以减小模块大小,同步管理即时应用和基础应用的版本。经过测试,可发布至Google Play Console,提升用户便利性,创造新获客机会。
|
10天前
|
Java API 调度
安卓多线程和并发处理:提高应用效率
【4月更文挑战第13天】本文探讨了安卓应用中多线程和并发处理的优化方法,包括使用Thread、AsyncTask、Loader、IntentService、JobScheduler、WorkManager以及线程池。此外,还介绍了RxJava和Kotlin协程作为异步编程工具。理解并恰当运用这些技术能提升应用效率,避免UI卡顿,确保良好用户体验。随着安卓技术发展,更高级的异步处理工具将助力开发者构建高性能应用。
|
10天前
|
编解码 人工智能 测试技术
安卓适配性策略:确保应用在不同设备上的兼容性
【4月更文挑战第13天】本文探讨了提升安卓应用兼容性的策略,包括理解平台碎片化、设计响应式UI(使用dp单位,考虑横竖屏)、利用Android SDK的兼容工具(支持库、资源限定符)、编写兼容性代码(运行时权限、设备特性检查)以及优化性能以适应低端设备。适配性是安卓开发的关键,通过这些方法可确保应用在多样化设备上提供一致体验。未来,自动化测试和AI将助力应对设备碎片化挑战。