[英]Android 11 - java.lang.IllegalStateException Not allowed to start service Intent : app is in background uid UidRecord{}
[英]How to solve the error: Not allowed to start service Intent : app is in background uid?
我有一項服務,它在啟動完成事件時啟動,但應用程序崩潰並顯示上述錯誤消息。 請幫助我如何在 Boot_Completed 的廣播接收器事件上啟動我的服務。
我的服務.kt
class MyService : Service() {
override fun onCreate() {
Log.d(TAG, "onCreate")
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onDestroy() {
Log.d(TAG, "DO SOME STAFF")
}
}
MyBroadCaster.kt
class StartRelayServiceAtBootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (Intent.ACTION_BOOT_COMPLETED == intent.action) {
val serviceIntent = Intent(context, MyService::class.java)
context.startService(serviceIntent)
}
}
}
后台應用程序有限制。 顯然,如果設備剛剛啟動,所有應用程序都“在后台”。 您不能從后台應用程序啟動Service
。 您可能需要使用JobScheduler
來滿足您的需求。
有關后台應用程序限制以及如何遷移到允許的其他解決方案的討論,請參閱此文檔:
https://developer.android.com/about/versions/oreo/background
經過一番搜索,我得到了答案,我必須檢查 SDK 版本,然后我可以將其作為前台服務或僅使用 starteService 啟動;
class StartRelayServiceAtBootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (Intent.ACTION_BOOT_COMPLETED == intent.action) {
val intent = Intent(context, MyService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
} else {
context.startService(intent)
}
Log.i("Autostart", "started")
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.