【发布时间】:2017-09-14 12:02:53
【问题描述】:
我正在创建一个媒体通知,它需要根据单击的按钮触发不同的功能。有什么方法可以区分按钮还是我需要创建 4-5 个单独的 Intent 和 PendingIntent?这是有效的代码,但不完全是应该的:
编辑:我添加了一个新函数来初始化新的挂起意图,但事情是这样的,当我按下播放时,会触发 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
);
}
【问题讨论】:
标签: android notifications