Implementing exit app button in the persistent notification

Tags: , , , ,



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?

Answer

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
        intentAction.putExtra("action","actionName");

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

    }

Now the receiver which will receive this Intent

        public class StopServerBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            //Toast.makeText(context,"recieved",Toast.LENGTH_SHORT).show();

            String action=intent.getStringExtra("action");
            if(action.equals("action1")){
                performAction1();
                /*
                
                    Code that will stop your service
                    
                */
            }
          
        }

    }

Register Receiver in Manifest

<receiver
    android:name=".StopServerBroadcast"
    android:enabled="true" />


Source: stackoverflow