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

Viewed 3827

I have a service which started by on booted completed event it, but the app crashes with the error message as in above. Please help on how can I start my Service on BroadCast receiver event of Boot_Completed.

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)
        }
    }
}
2 Answers

Upon some searching I got the answer that I had to check the SDK version that I can then start it as foreground service or just with 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")
        }
    }
}

There are limitations on apps in the background. Obviously, if the device just booted, all apps are "in the background". You cannot start a Service from a background app. You probably need to use JobScheduler to to what you want.

See this document for a discussion about the limitations on background apps and how to migrate to other solutions that are allowed:

https://developer.android.com/about/versions/oreo/background

Related