Уведомление о службе переднего плана удаляется при повторном открытии приложения, но служба все еще работает

#android #android-service #foreground-service

Вопрос:

У меня есть служба переднего плана, которая показывает уведомление, когда она запущена, и может быть остановлена действием пользователя.

после того, как я начал запрашивать разрешение пользователя на оптимизацию батареи ovveride и позволил службе работать в фоновом режиме, уведомление о службе начало исчезать всякий раз, когда приложение закрывалось и открывалось снова, но служба продолжала работать без уведомления на переднем плане.

это код, который я использую для запуска уведомления на переднем плане :

  @Override
public int onStartCommand(Intent intent, int flags, int startId) {


    return START_STICKY;
}
 

Я вызываю startForeground в методе onCreate ().

 public void startForeground() {

    String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel("my_service", "My Background Service") : "";


    Intent stopButton = new Intent(this, StopServicesActivity.class);
    stopButton.putExtra(StopServicesActivity.STOP_SERVICE_INDEX, GPS_SERVICE_INDEX);

    PendingIntent stopIntent = PendingIntent.getActivity(this, 0, stopButton, 0);


    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent =
            PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Notification.Action action = new Notification.Action.Builder(null, "STOP", stopIntent).build();

    Notification a =
            new Notification.Builder(this, channelId)
                    .setContentTitle("Safe Kids")
                    .setContentText("Monitoring your gps")
                    .setSmallIcon(R.drawable.ic_delete_safe_1)
                    .setContentIntent(pendingIntent)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .addAction(action)
                    .setOngoing(true)
                    .build();

    startForeground(101, a);
}

@RequiresApi(Build.VERSION_CODES.O)
public String createNotificationChannel(String channelId, String channelName) {
    NotificationChannel chan = new NotificationChannel(channelId,
            channelName, NotificationManager.IMPORTANCE_HIGH);

    chan.setLightColor(Color.BLUE);
    chan.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);

    NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    service.createNotificationChannel(chan);
    return channelId;
}
 

это код, который я использую, чтобы запросить разрешение на чрезмерную оптимизацию батареи :

 Intent intent = new Intent();
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:"   getApplicationContext().getPackageName()));
batteryActivityResultLauncher.launch(intent);
 

кто — нибудь знает, в чем причина этого ? Я не смог найти часть кода, которая удаляет уведомление.

Спасибо