How to stop service from your own foreground notification

Service works for me. and in onStartCommand I do startforeground to avoid system killing.

 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 clicking the button, PendingIntent does not work, and my activity does not stop there.

Can someone please tell me what I'm doing here or some other solution to stop the service from the notification front- notification made by myself.

thanks

+5
source share
2 answers

Answering my own question for the sake of other seekers like me.

The problem was in the line below

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

This 0 eventually caused the problem. I replaced this with PendingIntent.FLAG_CANCEL_CURRENT and it worked now.

Corrected Code:

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

Please see FLAG_CANCEL_CURRENT or FLAG_UPDATE_CURRENT for further clarification.

+10
source

The above idea will not work properly. The service must first stop it, so sometimes you see strange behavior. You must put some flag inside your loop / computation method and call " return; ", and then you can stop the service using stopself() or just wait until it finishes itself. If necessary, I can show. So please ask.

+1
source

All Articles