WHOATEMYNOODLES
WHOATEMYNOODLES

Reputation: 2631

Stopping Foreground service using NotificationCompat .addAction button

How would I stop the foreground service using the notification it creates in the class?

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

the button is created from .addAction and I want to stop that current foreground service

Upvotes: 4

Views: 1917

Answers (1)

Eren Tüfekçi
Eren Tüfekçi

Reputation: 2511

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

Upvotes: 13

Related Questions