点击每个通知按钮的触发器不同

时间:2017-09-14 12:02:54

标签: android notifications

我正在创建媒体通知,需要根据点击的按钮触发不同的功能。有没有办法区分按钮或我需要创建4-5个单独的Intents和PendingIntents?这是有效的代码,但不完全是如何:

编辑:我添加了一个新函数来初始化新的待处理意图但是这就是事情,当我按下播放时触发了playIntent但是当我按下暂停意图时,再次触发了playIntent。

 private void showNotification(boolean persistent) {
        String channel_id = "TEST_CHANNEL";
        NotificationManager manager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE
        );

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel testChannel = new NotificationChannel(
                    channel_id,
                    "TEST_CHANNEL",
                    NotificationManager.IMPORTANCE_DEFAULT
            );

            testChannel.setLightColor(Color.GREEN);

            assert manager != null;
            manager.createNotificationChannel(testChannel);
        }


        PendingIntent pauseIntent = initIntent("pause");
        PendingIntent playIntent = initIntent("play");

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this, channel_id)
                        .setSmallIcon(R.drawable.ic_remote_control)
                        .addAction(R.drawable.ic_play_button, "Play", playIntent)
                        .addAction(R.drawable.ic_round_pause_button, "Pause", pauseIntent)
                        .addAction(R.drawable.ic_forward, "Title", null)
                        .addAction(R.drawable.ic_back_left_arrow_circular_button, "Title", null)
                        .setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle())
                        .setOngoing(persistent)
                        .setAutoCancel(true);


        assert manager != null;
        manager.notify(123, mBuilder.build());
    }

    private PendingIntent initIntent(String action) {
        Intent tempIntent = new Intent(this, ActionReceiver.class);

        tempIntent.putExtra("action", action);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

        stackBuilder.addNextIntent(tempIntent);


        return PendingIntent.getBroadcast(
                this,
                1,
                tempIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );
    }

1 个答案:

答案 0 :(得分:0)

您需要为每个操作创建不同的待处理意图。即使您可以使用相同的类来处理基于每个待处理意图的不同操作的所有操作。