Skip to content
Advertisement

Implementing exit app button in the persistent notification

My app runs a background service indicated by the persistent notification. Users need to use the toggle button in MainActivity to turn on/off this service and thus to remove the persistent notification.

Now I want to implement a notification action that can turn this service off & as well as the toggle within MainActivity. All in all, it should be an exit button to close my app and background service directly from the notification.

How do I achieve this?

note that I have two different java files, one for NotificationService and the other is MainActivity. The toggle belongs to MainActivity.

edit: Is this okay to call System.exit(0) if I use pending intent with BroadCastReceiver to exit from the app completely?

Advertisement

Answer

You have to use PendingIntent with BroadcastReceiver or Service to perform this. Here is an example of PendingIntent with BroadcastReciever.

Build a Notification

JavaScript

Now the receiver which will receive this Intent

JavaScript

Register Receiver in Manifest

JavaScript
Advertisement