Skip to content

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?


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

Build a Notification

        public static void createNotif(Context context){

        Intent intentAction = new Intent(context,StopServerBroadcast.class);

        //This is optional if you have more than one buttons and want to differentiate between two

        pIntent = PendingIntent.getBroadcast(context,1,intentAction,PendingIntent.FLAG_UPDATE_CURRENT);
        drivingNotifBldr = (NotificationCompat.Builder) new NotificationCompat.Builder(context, CHANNEL_NAME)
                .setContentTitle("Stop Service")
                .setContentText("Example Text")
                .addAction(R.drawable.smallmanwalking, "On/off", pIntent)


Now the receiver which will receive this Intent

        public class StopServerBroadcast extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {


            String action=intent.getStringExtra("action");
                    Code that will stop your service


Register Receiver in Manifest

    android:enabled="true" />