How to stop service from its own foreground notification Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to stop service from its own foreground notification without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a Service running. and in its onStartCommand I am doing startforeground to avoid killing by system.

public int onStartCommand(Intent intent, int flags, int startId) {
    if (ACTION_STOP_SERVICE.equals(intent.getAction())) {
        Log.d(TAG,"called to cancel service");
        manager.cancel(NOTIFCATION_ID);
        stopSelf();
    }
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle("abc");
    builder.setContentText("Press below button to stoP.");
    builder.setPriority(NotificationCompat.PRIORITY_HIGH);
    builder.setSmallIcon(R.drawable.ic_launcher);

    Intent stopSelf = new Intent(this, SameService.class);
    stopSelf.setAction(this.ACTION_STOP_SERVICE);
    PendingIntent pStopSelf = PendingIntent.getService(this, 0, stopSelf,0);
    builder.addAction(R.drawable.ic_launcher, "Stop", pStopSelf);
    manager.notify(NOTIFCATION_ID, builder.build());
}

but after pressing button , PendingIntent is not working and my activity is not getting stopped by it.

Can someone please tell, what wrong am I doing here or any other solution to stop service from the foreground notification made by self.

Thanks

Answer

Answering my own question for sake of other finders like me.

Problem was in the line below

 PendingIntent pStopSelf = PendingIntent.getService(this, 0, stopSelf,0);

This 0 in the end was cause of the problem . I have replaced this with PendingIntent.FLAG_CANCEL_CURRENT and it worked now.

The corrected code is :

PendingIntent pStopSelf = PendingIntent.getService(this, 0, stopSelf,PendingIntent.FLAG_CANCEL_CURRENT);

Please check FLAG_CANCEL_CURRENT or FLAG_UPDATE_CURRENT for more explanation.

We are here to answer your question about How to stop service from its own foreground notification - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji