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

Check if app can start foreground service in background on Android 12+

有什么方法可以检查我的应用程序是否可以在 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 可能会触发得太晚,但我仍然想尝试在前台模式下启动该服务(如果此应用程序允许),因此我需要一些方法来检查

我想我们可以试着抓住 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
    }
}