【问题标题】:Implementing exit app button in the persistent notification在持久通知中实现退出应用程序按钮
【发布时间】:2020-11-08 08:54:22
【问题描述】:

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

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

我如何做到这一点?

请注意,我有两个不同的 java 文件,一个用于 NotificationService 另一个是 MainActivity。切换属于 MainActivity。

edit:如果我使用挂起的意图,可以调用 System.exit(0) BroadCastReceiver 完全退出应用?

【问题讨论】:

    标签: java android service android-service android-notifications


    【解决方案1】:

    您必须将 PendingIntent 与 BroadcastReceiver 或 Service 一起使用才能执行此操作。这是一个带有 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" />
    

    【讨论】:

    • 好吧,这看起来很有希望。但是我仍然有一个问题,因为开/关切换在 MainActivity 中,如果我使用 BroadcastReceiver 创建这个新类,那么我将如何从这个类访问该切换?
    • 可以调用 System.exit(0) 还是违反 Play 商店政策?
    • 制作一个静态布尔变量 isActive = true 或 false 并在后台服务中继续检查其 true 或 false 是否被广播接收者关闭,然后停止服务器并验证该变量
    • 这真是天才!谢谢兄弟,你救了我的命。
    猜你喜欢
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多