【发布时间】: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