How to solve the error: Not allowed to start service Intent : app is in background uid?

How to solve the error: Not allowed to start service Intent : app is in background uid?

我有一项服务是通过启动完成事件启动的,但应用程序崩溃并显示上述错误消息。请帮助我如何在 Boot_Completed.

的 BroadCast 接收器事件上启动我的服务

MyService.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)
        }
    }
}

后台应用有限制。显然,如果设备刚刚启动,所有应用程序都是 "in the background"。您不能从后台应用启动 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")
        }
    }
}