Android error: Stopping service due to app idle


Cause: Starting from Android O there is limitation on how freely app can access background Service.

Solution: use Foreground Service

Step 1: in service:

    @Override
    public void onCreate() {
        Log.i("AService", "Service onCreate");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String CHANNEL_ID = "my_channel_id";
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    "my_channel_title",
                    NotificationManager.IMPORTANCE_DEFAULT);

            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

            Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("")
                    .setContentText("")
                    .setColor(ContextCompat.getColor(this, R.color.transparentColor))
                    .build();

            startForeground(1, notification);
        }
    }

Step 2: Start service:

                        Intent intent = new Intent(mContext, AService.class);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            mContext.startForegroundService(intent);
                        } else {
                            mContext.startService(intent);
                        }

Step 3: AndroidManifest.xml

Add permission:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

Leave a Reply