【问题标题】:how to setClickListener on action in notification [closed]如何在通知中的操作上设置单击侦听器[关闭]
【发布时间】:2021-04-17 21:25:40
【问题描述】:

当按下通知中的操作时,我需要运行代码 不想打开新活动 我想运行代码以在 sharedPrefrencess 中保存值或删除通知表单 stat bar ...oct 按下停止操作时,我需要删除通知并在 sharedPrefrenccess 中保存值 如何做到这一点

请帮帮我

【问题讨论】:

    标签: java android android-studio kotlin


    【解决方案1】:

    这是执行您在您的问题中描述的一种方法,但要获得更复杂的答案,您必须更新您的问题并添加更多详细信息,例如您自己的代码。

    为了执行您描述的操作,在创建您的通知时,您必须添加与该操作相关的 ActionPendingIntent。它将创建一个操作按钮供您点击以执行某些操作。例如,您可以使用BroadcastReceiver 接收对操作按钮的点击:

    ActionReceiver.java

    public class ActionReceiver extends BroadcastReceiver {
    
        public ActionReceiver() {}
    
        @Override
        public void onReceive(Context context, Intent intent) {
            SharedPreferences preferences = context.getSharedPreferences(PREFERENCE_FILE_KEY, MODE_PRIVATE);
            SharedPreferences.Editor = preferences.edit();
            // ...
            // Here You do whatever is supposed to happen
            // after clicking the button on the notification
        }
    }
    

    无论您在哪里创建通知,都必须在通知生成器上调用 addAction,这会将按钮添加到您的通知中:

    Intent actionIntent = new Intent(this, ActionReceiver.class);
    actionIntent.setAction(ACTION_NAME);
    PendingIntent actionPendingIntent =
    PendingIntent.getBroadcast(this, NOTIFICATION_ID,
                               actionIntent, PendingIntent.FLAG_ONE_SHOT);
    
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    ...
                    .addAction(R.drawable.ic_action, 
                               getString(R.string.action_name), actionPendingIntent)
                    ...
                    .build();
    
    

    同样使用BroadcastReceiver 需要您注册它。您应该将其注册到您正在创建通知的类中,并关联接收者:

    actionReceiver = new ActionReceiver();
    registerReceiver(actionReceiver, new IntentFilter(ACTION_NAME));
    

    【讨论】:

    • 感谢您的解决方案,请问 snoozeIntent 对象是什么
    • 哦,对不起,这是我的一些代码的剩余部分,我已经复制并忘记更改(现在已编辑):D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-15
    • 2014-09-10
    相关资源
    最近更新 更多