有没有方法可以在 Android 12 上检查我的应用程序是否可以在后台启动前台服务,而不是实际尝试并获取
有一些方法可以检查至少满足以下条件之一: https://developer.android.com/guide/components/foreground-services#background-start-restriction-exemptions 我在 Activity 中将后台服务启动为前台。
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
可能会太晚触发,但我仍然希望尝试在应用程序允许的情况下启动前台模式服务,因此我需要一些方法来检查。