Остановка службы Foreground с помощью кнопки NotificationCompat .addAction - PullRequest
1 голос
/ 23 января 2020

Как мне остановить службу переднего плана, используя уведомление, которое она создает в классе?

Intent stopnotificationIntent = new Intent(this, HelloIntentService.class);
//Not sure which is the current action to set
stopnotificationIntent.setAction("ACTION.STOPFOREGROUND_ACTION"); 
PendingIntent pIntent = PendingIntent.getService(this, 0, stopnotificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)            
.addAction(0, "Cancel", pIntent);

startForeground(1111, notificationBuilder.build());

enter image description here

кнопка создана с .addAction и я хочу остановить текущую службу переднего плана

1 Ответ

2 голосов
/ 23 января 2020
String ACTION_STOP_SERVICE= "STOP";

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

        if (ACTION_STOP_SERVICE.equals(intent.getAction())) {
            Log.d(Statics.LOG_TAG,"called to cancel service");
            stopSelf();
        }

Intent stopSelf = new Intent(this, HelloIntentService.class);
        stopSelf.setAction(ACTION_STOP_SERVICE);

  PendingIntent pStopSelf = PendingIntent
            .getService(this, 0, stopSelf
                    ,PendingIntent.FLAG_CANCEL_CURRENT);  // That you should change this part in your code

notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentText("Bla Bla Bla")
            .setSmallIcon(R.drawable.ic_notification)
            .setContentIntent(pendingNotificationIntent)
            .addAction(R.drawable.xxxx,"Close", pStopSelf)
            .setSound(null)
            .build();

    startForeground(REQUEST_CODE, notification);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...