【问题标题】:Check if app can start foreground service in background on Android 12+检查应用程序是否可以在 Android 12+ 的后台启动前台服务
【发布时间】:2021-12-20 16:12:02
【问题描述】:

在应用实际尝试执行并获取ForegroundServiceStartNotAllowedException之前,是否有任何方法可以检查我的应用是否可以在 Android 12 的后台启动前台服务?

一些检查至少满足一个条件https://developer.android.com/guide/components/foreground-services#background-start-restriction-exemptions的方法

我在活动中将后台服务作为前台启动

try {
    context.bindService( // p.s. this context of application, it's bounded to app process instead of activity context
        getServiceIntent(context),
        object : ServiceConnection {
            override fun onServiceConnected(
                className: ComponentName,
                service: IBinder
            ) {
                // service is running in background
                startForegroundService(context)
                // service should be in foreground mode (at least it should be very soon)
                (service as LocalBinder).getService().initialize()
                context.unbindService(this)
                bindServiceInProgress.set(false)
            }

            override fun onServiceDisconnected(arg0: ComponentName) {
                bindServiceInProgress.set(false)
            }
        },
        AppCompatActivity.BIND_AUTO_CREATE
    )
} catch (e: Exception) {
    e.printStackTrace()
    bindServiceInProgress.set(false)
}

但是onServiceConnected 可能会在活动不再可见时触发太晚,但如果此应用允许,我仍然想尝试在前台模式下启动服务,所以我需要一些方法来检查

【问题讨论】:

    标签: android foreground-service android-12


    【解决方案1】:

    我想我们可以试试 catch ForegroundServiceStartNotAllowedException

    private fun makeServiceForeground(context: Context): Boolean {
        val intent = getServiceIntent(context)
        return try {
            ContextCompat.startForegroundService(context, intent)
            true
        } catch (e: Exception) {
            e.printStackTrace()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && e is ForegroundServiceStartNotAllowedException) {
                // TODO: notification to disable battery optimization
            }
            false
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 2014-03-18
      • 1970-01-01
      • 2014-09-14
      • 1970-01-01
      相关资源
      最近更新 更多