Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

1 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")
        }
    }
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!