Put a power off button on notification of an Android App

1

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

    
asked by anonymous 11.05.2015 / 19:21

1 answer

1

Create a BroadcastReceiver with the code needed to stop the service. When creating the notification use the addAction () from Notification.Builder by passing a PendigIntent that throws 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 PendigIntent be built in order to launch the service by passing an 'Extra' that would indicate that the service should be stopped. The onStartCommand() service method checks this 'Extra' and calls stopSelf() .

The PendigIntent to use in addAction() would look like this:

Intent intent = new Intent(this, oSeuServico.class);
Intent.putExtra("Parar","Sim");
PendingIntent pIntent = PendingIntent.getService(this, 0, intent, 0);
    
11.05.2015 / 19:42