【发布时间】:2018-08-23 02:44:41
【问题描述】:
即使手机静音,我也想在通知中强制发出声音。 (是的,我知道,这不是概念,但如果有人闯入我的房子,我希望我的警报系统发出通知)
我在 Android 6.0 和 HTC one A9s 上使用 Android API 23。 根据我的阅读,我唯一的选择是:
- 缓存当前音频设置
- 更改为 RINGER_MODE_NORMAL 并设置 MAX_AUDIO
- 运行通知
- 恢复旧的音频设置
如果我在调试模式下做一个断点并遍历我的代码的每一行,这很好用。 但如果我在没有断点的调试模式下运行(一切都一样),它就不起作用。所以我认为这是一个时间问题,音频管理器/或硬件不会足够快地从静音变为非静音。我不是专家,但这是我的结论。任何建议如何处理?我可以睡一觉之类的,但这似乎可靠且正确。
我当前的代码:
// save current audio settings to restore later
int audio_ringermode = audio_mode.getRingerMode();
audio_old_volume =
audio_mode.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
// set new audio settings
audio_mode.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
audio_mode.setStreamVolume(AudioManager.STREAM_NOTIFICATION,audio_mode.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION),0);
// Notification
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_home_notify)
.setColor(notification_icon)
.setContentTitle(notification_title)
.setContentText(notification_text)
.setAutoCancel(true)
.setSound(defaultSoundUri);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId,notificationBuilder.build());
// restore old audio settings
audio_mode.setRingerMode(audio_ringermode);
audio_mode.setStreamVolume(AudioManager.STREAM_NOTIFICATION, audio_old_volume ,0);
【问题讨论】:
-
我不认为
notificationManager.notify是同步的。也许您需要设置一个更好的policy? -
Set the Policy。确保您已在清单中授予权限。
标签: android android-notifications