ServiceTracker 的作用

如果您的服务消费者需要了解某一接口下的服务对象何时注册、何时取消注册,这时,您应使用 ServiceTracker 类:

 

下面,我们看看如何使用服务跟踪器来修改我们的示例代码,具体步骤如下。

1) 修改HelloWorldBundle的MANIFEST.MF文件,让它导入org.osgi.util.tracker包;

2) 新建类HelloServiceTracker.java,其源代码参见清单11。

源代码清单11.HelloServiceTracker.java

Java代码  收藏代码
  1. public   class  HelloServiceTracker  extends  ServiceTracker {    
  2.    
  3.     public  HelloServiceTracker(BundleContext context) {    
  4.    
  5.         super (context, HelloService. class .getName(), null );    
  6.    
  7.     }    
  8.    
  9.     public  Object addingService(ServiceReference reference) {    
  10.    
  11.         System.out.println("Inside HelloServiceTracker.addingService "  + reference.getBundle());    
  12.    
  13.         return   super .addingService(reference);    
  14.    
  15.     }    
  16.    
  17.     public   void  removedService(ServiceReference reference, Object service) {    
  18.    
  19.         System.out.println("Inside HelloServiceTracker.removedService "  + reference.getBundle());    
  20.    
  21.         super .removedService(reference, service);    
  22.    
  23.     }    
  24.    
  25. }    

 

在上面的HelloSerivceTracker类的构造函数中,您可以看到,我们把HelloService接口名传入其父类中,这相当于说,HelloServiceTracker应跟踪注册到HelloService接口名下的所有服务,HelloServiceTracker继承自ServiceTracker 类,实现了下面两个方法:

a) addingService()方法:当Bundle使用 接口名注册服务时,该方法将会被调用;

b)removedService()方法:当Bundle取消注册某个接口名下的服务时,该方法将会被调用。

3) 用HelloServiceTracker类更新我们的Activator.java类,以便让它来管理服务,而不是直接去查找它们,源代码请参见清单12。

源代码清单12. 使用 了HelloServiceTracker的Activator.java

Java代码  收藏代码
  1. public   class  Activator  implements  BundleActivator {    
  2.    
  3.     HelloServiceTracker helloServiceTracker;    
  4.    
  5.     public   void  start(BundleContext context)  throws  Exception {    
  6.    
  7.         System.out.println("Hello World!!" );    
  8.    
  9.         helloServiceTracker= new  HelloServiceTracker(context);    
  10.    
  11.         helloServiceTracker.open();    
  12.    
  13.         HelloService helloService = (HelloService)helloServiceTracker.getService();    
  14.    
  15.         System.out.println(helloService.sayHello());    
  16.    
  17.      
  18.    
  19.     }    
  20.    
  21.     public   void  stop(BundleContext context)  throws  Exception {    
  22.    
  23.         System.out.println("Goodbye World!!" );    
  24.    
  25.         helloServiceTracker.close();    
  26.    
  27.     }    
  28.    
  29. }   

 

我们看到,在初始的start()方法中,我们首先新建一个HelloServiceTracker对象,然后要求这个对象跟踪HelloService接口下的服务。这时,我们可以调用getService()方法获得HelloService对象。

如果您试运行上面的示例代码,您会注意到,在启动或停止HelloSerivceBundle时,OSGi 容器都会调用HelloServiceTracker对象的addingService()方法或removedService()方法。

 

总结: 由此可见ServiceTracker与context.getService(reference)的最大区别是,ServcieTracker封装了ServiceListener可以在Service发生变化时被触发,比较适合热插拔。

09-22 10:52:32.825 1000 1732 15380 E subsystem_ramdump: write successful for ramdump fd for /data/vendor/bsplog/wlan/ssr_dump/2025-09-22-10:52:27/ramdump_wpss_2025-09-22_10-52-27.elf 09-22 10:52:32.825 1000 2494 3538 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.825 1000 1732 15380 E subsystem_ramdump: read /proc/last_mcrash :adrastea/wpss.mdt: cmnos_thread.c:4003:Asserted in wal_power_debug.c:wal_power_debug_trigger_crash_c 09-22 10:52:32.826 1000 2494 5294 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.826 10182 14289 15285 D JavaheapMonitor: Java heap used=2M max=256M, proc: com.google.android.syncadapters.calendar 09-22 10:52:32.826 10182 14289 15285 V JavaheapMonitor: Check java heap usage finished! Next check delay: 300000 09-22 10:52:32.826 1000 2494 5317 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.827 1000 2494 5717 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.827 6102 8908 8908 E SysUtils: cancelNotificationById: 1,showRedDot:-1 09-22 10:52:32.827 1000 2494 5317 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.828 6102 8908 8908 E SysUtils: cancelNotificationById: 9,showRedDot:-1 09-22 10:52:32.828 1000 2494 4130 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.828 10182 14289 14289 W BpBinder: PerfMonitor binderTransact: time=412ms interface=android.app.job.IJobCallback code=4 09-22 10:52:32.829 1000 2494 5690 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.829 1000 2494 4399 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.829 1000 2494 3181 E AlarmManager: not align this alarm: Alarm{fb905b6 type 2 origWhen 428776 whenElapsed 428776 android}, reason=0 09-22 10:52:32.830 1000 2494 5432 W system_server: PerfMonitor async binderTransact : time=293ms interface=android.security.rkp.IRemoteProvisioning code=1 09-22 10:52:32.830 1000 2494 3181 I WifiScanningService: Received a request to enable scanning, UID = 1000 09-22 10:52:32.830 1000 2494 3181 I WifiScanningService: scanner impls already exists 09-22 10:52:32.830 1000 2494 3181 E WifiScanningService: wifi driver loaded received while already loaded 09-22 10:52:32.830 1000 2494 5432 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.830 1000 2494 4399 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.830 10203 13984 15211 D JavaheapMonitor: Java heap used=4M max=256M, proc: com.google.android.apps.tachyon 09-22 10:52:32.831 10203 13984 15211 V JavaheapMonitor: Check java heap usage finished! Next check delay: 300000 09-22 10:52:32.831 6102 8908 8908 E SysUtils: cancelNotificationById: 2,showRedDot:-1 09-22 10:52:32.832 1000 2494 5679 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.832 1000 2494 5317 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.832 10163 11576 11645 E Finsky : [61] Error when retrieving FCM instance id 09-22 10:52:32.832 1000 2494 2844 D BatteryStatsManagerStub: noteWifiScanStartedLocked 1010 09-22 10:52:32.832 1000 2494 2844 E PowerInsightPolicy: sPowerInsightService null! 09-22 10:52:32.832 1000 2494 5679 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.833 1000 2494 5317 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.833 1000 2494 5245 I HidlServiceManagement: Trying to get transport of vendor.qti.hardware.servicetracker@1.0::IServicetracker/default without hwservicemanager 09-22 10:52:32.833 1000 2494 5317 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.834 1000 2494 4399 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.834 1000 2494 5679 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.835 1000 2494 4130 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.835 1000 2494 5679 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.836 1000 2494 5317 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.836 6102 8908 8908 E SysUtils: cancelNotificationById: 12,showRedDot:-1 09-22 10:52:32.836 10182 14289 14364 I WM-WorkerWrapper: Work [ id=68f77028-5abb-48a1-a63b-b75a088c3834, tags={ com.google.android.libraries.notifications.platform.entrypoints.job.GnpWorker,GNP_SDK_JOB } ] was cancelled 09-22 10:52:32.836 10182 14289 14364 I WM-WorkerWrapper: androidx.work.impl.WorkerStoppedException 09-22 10:52:32.836 10182 14289 14364 I WM-WorkerWrapper: at androidx.work.impl.Processor.interrupt(Processor.java:6) 09-22 10:52:32.836 10182 14289 14364 I WM-WorkerWrapper: at androidx.work.impl.utils.StopWorkRunnable.run(StopWorkRunnable.kt:101) 09-22 10:52:32.836 10182 14289 14364 I WM-WorkerWrapper: at androidx.work.impl.utils.SerialExecutorImpl$Task.run(SerialExecutorImpl.java:3) 09-22 10:52:32.836 10182 14289 14364 I WM-WorkerWrapper: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1156) 09-22 10:52:32.836 10182 14289 14364 I WM-WorkerWrapper: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:651) 09-22 10:52:32.836 10182 14289 14364 I WM-WorkerWrapper: at java.lang.Thread.run(Thread.java:1119) 09-22 10:52:32.836 root 1280 15479 I resolv : GetAddrInfoHandler::run: {0 786432 0 983040 10161 0} 09-22 10:52:32.837 1000 2494 5679 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.837 1000 2494 4130 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.838 1000 2494 5245 I SmartPower: com.indus.appstore/10238(14241): idle->background(3915ms) R(service create com.indus.appstore/com.google.firebase.sessions.SessionLifecycleService) adj=905. 09-22 10:52:32.838 1000 2494 5245 I HidlServiceManagement: Trying to get transport of vendor.qti.hardware.servicetracker@1.0::IServicetracker/default without hwservicemanager 09-22 10:52:32.838 6102 8908 8908 E SysUtils: cancelNotificationById: 11,showRedDot:-1 09-22 10:52:32.838 10182 14289 14364 D WM-WorkerWrapper: Status for 68f77028-5abb-48a1-a63b-b75a088c3834 is RUNNING; not doing any work and rescheduling for later execution 09-22 10:52:32.839 1000 2494 5245 D CompatChangeReporter: Compat change id reported: 319471980; UID 10238; state: ENABLED 09-22 10:52:32.839 10286 11721 11761 D WM-GreedyScheduler: Cancelling work ID 247f0c8c-2d5a-493c-81e1-da8554a0dc37 09-22 10:52:32.839 1000 2494 5245 D ActivityManager: Logging bindService for com.indus.appstore, stopped=false, firstLaunch=false 09-22 10:52:32.839 1000 2494 5710 I ActivityManager: unbindService com.android.server.am.ActiveServices@778b2f3 conn=android.os.BinderProxy@d3c798a callingPid=14241 09-22 10:52:32.839 1000 2494 5710 I HidlServiceManagement: Trying to get transport of vendor.qti.hardware.servicetracker@1.0::IServicetracker/default without hwservicemanager 09-22 10:52:32.840 1000 2494 4130 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.840 1000 2494 5679 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.842 6102 8908 8908 E SysUtils: cancelNotificationById: 3,showRedDot:-1 09-22 10:52:32.842 6102 8908 8908 E SysUtils: cancelSettingsSuperscript: 09-22 10:52:32.842 10161 4593 13954 W hsbr : [{0}] Failed to resolve name. status={1} 09-22 10:52:32.845 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.845 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.845 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.845 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.846 1000 2494 4399 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.846 1000 12988 12988 D MiuiWifiEntryPreference: updateConnectAnimation* state: DISCONNECTED, animationHelperState: 0, hashCode: 98302149 09-22 10:52:32.847 1000 12988 12988 D SettingsFeatures: isFoldDevice: false 09-22 10:52:32.847 10161 4593 13954 W hsbr : [{0}] Failed to resolve name. status={1} 09-22 10:52:32.847 1000 2494 5432 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.848 1000 2494 4399 I WifiService: getCurrentNetwork uid=1000 09-22 10:52:32.849 1000 2494 2603 D UidStateManager: uid state changed, uid=10240 09-22 10:52:32.849 1000 2494 5280 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.850 1000 2494 5679 I ActivityManager: unbindService com.android.server.am.ActiveServices@778b2f3 conn=android.os.BinderProxy@97a2f58 callingPid=14289 09-22 10:52:32.851 1000 2494 5690 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.851 1000 2494 5679 I HidlServiceManagement: Trying to get transport of vendor.qti.hardware.servicetracker@1.0::IServicetracker/default without hwservicemanager 09-22 10:52:32.851 1000 2494 2603 D UidStateManager: uid state changed, uid=10238 09-22 10:52:32.851 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.852 1000 2494 3160 I MiuiNetworkPolicy: updateUidState uid = 10240, uidState = 10 09-22 10:52:32.853 10286 11721 11761 W JobInfo : Requested important-while-foreground flag for job18 is ignored and takes no effect 09-22 10:52:32.853 10286 11721 11761 D WM-SystemJobScheduler: Scheduling work ID 247f0c8c-2d5a-493c-81e1-da8554a0dc37Job ID 18 09-22 10:52:32.854 1000 2494 3160 I MiuiNetworkPolicy: updateUidState uid = 10238, uidState = 10 09-22 10:52:32.854 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.855 1000 12988 12988 D MiuiNearbyApPreference: isSlavePage:false 09-22 10:52:32.855 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.855 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.855 10203 13984 14375 W JobInfo : Requested important-while-foreground flag for job35 is ignored and takes no effect 09-22 10:52:32.856 1000 2494 5679 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.856 10182 14289 14289 D WM-Processor: Processor 68f77028-5abb-48a1-a63b-b75a088c3834 executed; reschedule = true 09-22 10:52:32.857 1000 2494 5280 I WifiService: getVerboseLoggingLevel uid=1000 09-22 10:52:32.858 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.859 1000 2494 2799 D BroadcastQueue: Logging broadcast for com.xiaomi.hypercomm, stopped=false, firstLaunch=false 09-22 10:52:32.859 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.859 1000 2494 2799 D BroadcastQueue: Logging broadcast for org.codeaurora.ims, stopped=false, firstLaunch=false 09-22 10:52:32.860 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.860 1000 2494 2799 D BroadcastQueue: Logging broadcast for com.android.phone, stopped=false, firstLaunch=false 09-22 10:52:32.859 radio 3669 3669 I HyperComm_BroadcastReceiver: receive action: android.intent.action.BATTERY_CHANGED 09-22 10:52:32.860 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.860 radio 3669 3669 D HyperComm_BroadcastReceiver: handleBatteryLevelChanged, batteryLevel = 25 09-22 10:52:32.860 10263 3661 3661 D QtiCarrierConfigHelper: WARNING, no carrier configs on phone Id: 0 09-22 10:52:32.861 10263 3661 3661 D QtiCarrierConfigHelper: WARNING, no carrier configs on phone Id: 1 09-22 10:52:32.862 1000 2494 2799 D BroadcastQueue: Logging broadcast for com.android.phone, stopped=false, firstLaunch=false 09-22 10:52:32.862 1000 2494 2799 D BroadcastQueue: Logging broadcast for com.qualcomm.qti.telephonyservice, stopped=false, firstLaunch=false 09-22 10:52:32.864 10179 3625 3625 D DeviceStatisticsService: onReceive: action= android.intent.action.BATTERY_CHANGED 09-22 10:52:32.865 1000 2494 5317 I ActivityManager: unbindService com.android.server.am.ActiveServices@778b2f3 conn=android.os.BinderProxy@def84ea callingPid=14011 09-22 10:52:32.865 1000 2494 5317 I HidlServiceManagement: Trying to get transport of vendor.qti.hardware.servicetracker@1.0::IServicetracker/default without hwservicemanager 09-22 10:52:32.865 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.865 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.866 1000 2494 5317 I HidlServiceManagement: Trying to get transport of vendor.qti.hardware.servicetracker@1.0::IServicetracker/default without hwservicemanager 09-22 10:52:32.866 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.866 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.866 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.866 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode 09-22 10:52:32.866 1000 12988 12988 V AutofillManager: notifyViewVisibilityChanged(): ignoring on augmented only mode
09-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值