在持久通知中实现退出应用程序按钮

Implementing exit app button in the persistent notification

我的应用程序运行由持久通知指示的后台服务。用户需要使用 MainActivity 中的切换按钮来打开 on/off 此服务,从而删除持久通知。

现在我想实现一个 notification action 可以关闭此服务并在 MainActivity 中进行切换。总而言之,直接从通知中关闭我的应用程序和后台服务应该是an exit button

如何实现?

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?

您必须将 PendingIntent 与 BroadcastReceiver 或服务一起使用才能执行此操作。这是一个带有 BroadcastReciever 的 PendingIntent 示例。

建立通知

        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);
        ...

    }

现在将接收此 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
                    
                */
            }
          
        }

    }

在清单中注册接收器

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