Android通知操作按钮点击监听器

3
我正在开发一个事件计划应用程序,目前正在开发一个功能,用于将物品分配给客人。 当物品被分配时,会向客人推送通知,询问他是否能带来所需的物品。根据用户输入,将向服务器发送HTTP请求,更新物品状态(带/不带)。
我遇到了一些问题需要解决。当我点击通知操作按钮时,我不太明白它是如何工作的。我设法显示操作按钮,但无法弄清如何响应单击它们。从网上看到的信息,通知操作按钮的响应由PendingIntent管理,但我无法理解它的工作原理,也不知道如何使用它根据单击的按钮发送HTTP请求。
如果能得到一些帮助和建议,我会非常高兴。
[这是向用户发送的通知示例。]
以下是通知用户的方法:
    private void notifyUser(Bundle data) {
    ...
    //Notification configuration.
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(...)
            .setLargeIcon(...)
            .setContentTitle(...)
            .setContentText(...)
            .setAutoCancel(...)
            .setSound(...);

        //Get the item data from the request sent to the GCM server.
        Item item = GsonFactory.getGson()
                .fromJson(data.getString("data"), Item.class);

        //This is the part that I do not understand...
        notificationBuilder
                .addAction(R.drawable.ic_close_black, "No", null)
                .addAction(R.drawable.ic_done_black, "Yes", null);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0, notificationBuilder.build());
}

感谢您的提前感谢!
2个回答

0

希望这可以帮到你

//带按钮的通知示例

private static void scheduleNotificationWithButton(Context context, String message) {

    int notifReCode = 1;

    //What happen when you will click on button
    Intent intent = new Intent(context, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_ONE_SHOT);

    //Button
    NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.mipmap.ic_launcher, "Go", pendingIntent).build();

    //Notification
    Notification notification = new NotificationCompat.Builder(context)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText("Back to Application ?")
            .setContentTitle("Amazing news")
            .addAction(action) //add buton
            .build();

    //Send notification
    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1, notification);
}

-1
你必须为你的操作设置一个PendingIntent对象,这样当用户在通知按钮上执行任何操作时,该特定意图就会被触发。 PendingIntent可以设置为Activity、Broadcast Receiver或Service。 如果你想在用户点击通知按钮时显示一个活动,则可以使用-
    Intent intent = new Intent(this, NotificationReceiverActivity.class);
    intent.putExtra(<key>, item ); //If you wan to send data also
    PendingIntent pIntent = PendingIntent.getActivity(this, <notification_id>, intent, 0); //<notification_id> may be any number

将此意图设置为您的通知操作 -
notificationBuilder
                .addAction(R.drawable.ic_close_black, "No", pIntent)
                .addAction(R.drawable.ic_done_black, "Yes", pIntent);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接