Android Foreground service удаляется при смахивании приложения

Запускаю сервис, и затем запускаю foreground в нем. Все работает нормально, появляется не убираемое уведомление, которое говорит о том, что служба запущена на переднем плане. Но когда закрываешь приложение, смахиваешь его из списка запущенных приложений, то закрывается и сам foreground сервис. Как сделать так, чтобы при смахивании foregorund service не закрывался??

Код запуска Foreground сервиса:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            String NOTIFICATION_CHANNEL_ID = getString(R.string.foreground_channel_id);
            String channelName = Constants.DRIVER_SERVICE;
            NotificationChannel chan = null;
            chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
            chan.setLightColor(Color.BLUE);
            chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (manager != null) {
                manager.createNotificationChannel(chan);
            }

            Notification.Builder builder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
                    .setSmallIcon(R.drawable.ic_car)
                    .setOngoing(true)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setVibrate(new long[]{0})
                    .setContentTitle(getString(R.string.app_name))
                    .setAutoCancel(true)
                    .setVisibility(Notification.VISIBILITY_PUBLIC)
                    .setDefaults(Notification.DEFAULT_SOUND);

            Notification notification = builder.build();
            startForeground(2, notification);

        }

Ответы (1 шт):

Автор решения: AlexS

Добавьте в манифест к вашему сервису:

android:stopWithTask="false"

Должно быть что-то вроде этого:

 <service
        android:name=".data.services.MainService"
        android:enabled="true"
        android:exported="false"
        android:foregroundServiceType="location"
        android:stopWithTask="false" />
→ Ссылка