如何在按音量按钮时关闭通知?

4

我正在使用Alarm Manager创建一个在特定时间触发的通知,它能够正常工作,但是当按下音量按钮时无法停止播放声音,就像接听电话时一样。

以下是我创建通知的方式:

        NotificationCompat.Builder notification = new NotificationCompat.Builder(this);
        notification.setAutoCancel(true);

        notification.setSmallIcon(R.drawable.notification_icon);
        notification.setTicker("This's the ticker");//status bar text
        notification.setContentTitle("title");
        notification.setContentText("text");

        notification.setPriority(1);

        Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysound);
        notification.setSound(sound);

        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager manager = (NotificationManager) this.getSystemService(ns);

        manager.notify(0,notification.build());

希望有人能帮助我解决如何实现这个问题。提前感谢。

我不是安卓开发者,所以不能保证这是最佳解决方案,但你可以创建一个事件监听器,当音量键被按下时触发,从监听器中调整音量。 - Dioxin
我尝试使用监听器,但它没有起作用。谢谢帮助。 - 4mahmoud
1个回答

0

试试这个。首先,构建通知以使用系统闹钟音频流而不是默认(铃声)音频流。

--- 您的通知代码

Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysound);
NotificationCompat builder = NotificationCompat.builder(this)
        .setPriority(NotificationCompat.PRIORITY_HIGH)
        .setCategory(NotificationCompat.CATEGORY_ALARM)
        .setSound(sound, AudioManager.STREAM_ALARM)
        .setAutoCancel(true)
        .setSmallIcon(R.drawable.notification_icon)
        .setTicker("This's the ticker")
        .setContentTitle("title")
        .setContentText("text");
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(NOTIFICATION_ID, builder.build());

也许像这样设置通知的优先级和类别会在电话通话时使您的应用程序闹钟静音。请查看AudioManager
然后,在您的Activity中配置音量控制以调整闹钟音量。
--- MainActivity.java
setVolumeControlStream(AudioManager.STREAM_ALARM);

在这个活动中,音量控制现在将调整闹钟音量,并控制您的通知闹铃。

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