想在notification中添加几个控制音乐播放的next/prev/play/stop的按键,在网上查了好多方法,可是都没有解决,按键是在notification上面显示出来了,可是点击那些按键都没有响应。应该要怎么把按键和事件响应联系起来啊?
1条回答 默认 最新
- ChatGPTᴼᴾᴱᴺᴬᴵ 2022-12-19 15:20关注
ChatGPT尝试为您解答,仅供参考
为了在 Android 通知中添加可点击的按键,你需要使用 android.app.Notification.Builder 类的 addAction 方法。该方法需要你提供一个 PendingIntent 对象和一个 android.app.RemoteInput 对象。
先来看看 PendingIntent:它是一种用于在未来某个时间执行某个操作的意图。你可以使用 PendingIntent.getService 或 PendingIntent.getBroadcast 方法创建一个 PendingIntent 对象,然后将它传递给 addAction 方法。当用户点击通知中的按键时,系统会执行这个 PendingIntent。
接下来是 android.app.RemoteInput:它是一种可以让用户在通知中输入文本的组件。你可以使用 RemoteInput.Builder 类创建一个 RemoteInput 对象,然后将它传递给 addAction 方法。
综上所述,你可以这样创建和添加按键:
// 创建一个 PendingIntent 对象 Intent intent = new Intent(context, MyReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0); // 创建一个 RemoteInput 对象 RemoteInput remoteInput = new RemoteInput.Builder("key_text_reply") .setLabel("回复") .build(); // 创建一个按键并添加到通知中 NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_reply, "回复", pendingIntent) .addRemoteInput(remoteInput) .build(); // 将按键添加到通知中 NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setContentTitle("标题") .setContentText("内容") .addAction(action); // 发送通知 NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(NOTIFICATION_ID, builder.build());
在上面的代码中,我们创建了一个
PendingIntent
对象,然后使用它创建了一个按键。这个按键有一个图标、标题和PendingIntent
对象。我们还创建了一个RemoteInput
对象,然后将它添加到按键中。最后,我们将这个按键添加到通知中,并使用NotificationManagerCompat
发送通知。
当用户点击通知中的按键时,系统会执行你创建的
PendingIntent
对象。你可以在你的BroadcastReceiver
或Service
中处理这个操作,例如控制音乐播放的 next/prev/play/stop 等。解决 无用评论 打赏 举报
悬赏问题
- ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
- ¥15 微信公众号自制会员卡没有收款渠道啊
- ¥15 stable diffusion
- ¥100 Jenkins自动化部署—悬赏100元
- ¥15 关于#python#的问题:求帮写python代码
- ¥20 MATLAB画图图形出现上下震荡的线条
- ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
- ¥15 perl MISA分析p3_in脚本出错
- ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
- ¥15 ubuntu虚拟机打包apk错误