SimpleCoder SimpleCoder - 1 month ago 21
Android Question

How to stop service from its own foreground notification

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.

Please check FLAG_CANCEL_CURRENT or FLAG_UPDATE_CURRENT for more explanation.

Comments