Put an off service button on notification of an Android App

Asked

Viewed 326 times

1

In my application I have a Service running in the background, which puts a notification in the user’s Status Bar, I would like to add a button to turn off the service, as the Waze map app does.

1 answer

1


Create a Broadcastreceiver with the code needed to stop the service.
When creating the notification use the method addAction() of Notification.Builder passing a Pendigintent what’s up with this one Broadcastreceiver.

Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

Notification n  = new Notification.Builder(this)
    ...
    ...
    ...
    .setAutoCancel(true)
    .addAction(R.drawable.icon, "Parar serviço", pIntent).build();

NotificationManager notificationManager = 
  (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

notificationManager.notify(0, n);

Another way would be the Pendigintent be constructed in order to launch the service by passing a 'Extra' indicating that the service must be stopped.
The method onStartCommand() of the service checks that 'Extra' and flame stopSelf().

The Pendigintent to be used in the addAction() would be so:

Intent intent = new Intent(this, oSeuServico.class);
Intent.putExtra("Parar","Sim");
PendingIntent pIntent = PendingIntent.getService(this, 0, intent, 0);
  • Right, and the off icon in the notification how can I do?

  • I edited the question with another way of doing. The icon is a drawable. The code I posted is R.drawable.icon, the first parameter of addAction.

  • Got it, thank you very much! I’m already implementing here, I believe it will work :)

  • Something else, there’s a time when the action shows, there’s a time when you don’t, when you have a lot of notifications, there’s a way to always show the action?

  • What doesn’t show? Turn off icon or whole notification?

  • Exactly, I put the top priority on the notification now appears.

  • I managed to implement until the part of Broadcastreceiver, now I would like to close all application, on broadcast.. Something like Finish(); to close every app.

  • If Broadcastreceiver is a inner class of his Activity you have access to the method finish(). However it doesn’t make much sense to use Notifications to "stop" the service if its Activity has to be maintained while the service is in operation.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.