检查应用程序是否可以在Android 12+后台启动前台服务。

5
有没有方法可以在 Android 12 上检查我的应用程序是否可以在后台启动前台服务,而不是实际尝试并获取 ForegroundServiceStartNotAllowedException
有一些方法可以检查至少满足以下条件之一: https://developer.android.com/guide/components/foreground-services#background-start-restriction-exemptions 我在 Activity 中将后台服务启动为前台。
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)
}

但是当Activity不再可见时,onServiceConnected可能会太晚触发,但我仍然希望尝试在应用程序允许的情况下启动前台模式服务,因此我需要一些方法来检查。

1个回答

2
我想我们可以尝试捕获 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
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接