用于getRunningServices的Android O替换

时间:2017-08-16 14:11:43

标签: android android-service

在Android的早期版本中,我使用此方法查找来自其他应用的服务是否已启动并正在运行。它对我来说可靠:

ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
List<RunningServiceInfo> services = manager.getRunningServices(Integer.MAX_VALUE);

但是,对于Android O,现在不推荐使用,只会返回有关调用应用服务的信息。我已经研究过其他解决方案,但我不想要求用户提供更多权限,(UsageStatsManager,NotificationManager等)。

是否有另一种解决方案可以获取Android O中是否有其他应用的服务正在运行?

3 个答案:

答案 0 :(得分:0)

此功能故意没有没有替代。从文档中还不太清楚,但是from the docs

注意:此方法仅用于调试或实现服务管理类型的用户界面。

基本上,使用该方法检查其他应用程序服务是意外的副作用,因此Google决定将其删除。可能出于隐私/安全目的,避免应用“嗅探”用户设备上的其他应用/服务。

您没有提到用例,但是您想要避免向用户询问权限。但是,Google故意强迫开发人员明确请求他们所需的权限,这种哲学可以在here中找到。

答案 1 :(得分:0)

服务类:

 override fun onBind(intent: Intent?): IBinder? {
        return mBinder
    }

    inner class LocalBinder : Binder() {
        val serviceInstance: ServiceClass
            get() = this@ServiceClass
    }

活动中:

 var mConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) 
      {
            val binder = service as LocalBinder
            myService = binder.serviceInstance //Get instance of your service!
          
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            TODO("Not yet implemented")
        }

    }

将服务与活动绑定:

 val intent = Intent(this, ServiceClass::class.java)
 bindService(intent, mConnection, Context.BIND_AUTO_CREATE)

答案 2 :(得分:-1)

根据文档:

As of O, this method is no longer available to third party applications.
For backwards compatibility, it will still return the caller's own services.

但是此解决方案可能会有所帮助:How to check if a service is running on Android?

相关问题