I've created a personal (not public!) application long ago which receives notifications. Now I'm rewriting this application and I'm using notification channels. I already implemented a custom vibration pattern and all the things I need, but one thing is still missing:
The app should bypass DND mode. As far as I came, this works now. But if the phone is silent (STREAM_*
levels 0), the sound is not played - but it should. Is there any possibility, to set the Volume for this notification to MAX? And yes, it's not a problem if the notification is received in foreground, but it also should play the sound in the background.
What I've got so far:
My NotificationUtils.java
class which creates the Notification channel(s). This is the one that should bypass DND:
SharedPreferences mSharedPreferences = this.getSharedPreferences(Constants.PREFERENCES_NAME, Context.MODE_PRIVATE);
Boolean prefVibration = mSharedPreferences.getBoolean(Constants.PREFERENCES_NOTIFICATION_VIBRATE, false);
Boolean prefSound = mSharedPreferences.getBoolean(Constants.PREFERENCES_NOTIFICATION_WITH_SOUND, false);
String prefSoundfile = mSharedPreferences.getString(Constants.PREFERENCES_NOTIFICATION_SOUNDFILE, "not");
String channelId = getString(R.string.default_notification_channel_id);
NotificationChannel alarmsChannel = new NotificationChannel(channelId, getString(R.string.channel_title_alarms), NotificationManager.IMPORTANCE_HIGH);
alarmsChannel.enableLights(true);
alarmsChannel.enableVibration(true);
alarmsChannel.setLightColor(Color.RED);
alarmsChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
alarmsChannel.setBypassDnd(true);
alarmsChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
alarmsChannel.shouldShowLights();
alarmsChannel.canBypassDnd();
if (prefVibration) {
alarmsChannel.setVibrationPattern(mVibratePattern);
alarmsChannel.shouldVibrate();
}
if (prefSound) {
Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + this.getPackageName() + "/" + getResId(prefSoundfile, R.raw.class));
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
alarmsChannel.setSound(soundUri, audioAttributes);
}
getManager().createNotificationChannel(alarmsChannel);
When a user enables the Constants.PREFERENCES_NOTIFICATION_WITH_SOUND
preference, he is asked for the correct permissions:
ActivateDndAllowance mDndAllowance = new ActivateDndAllowance(this.getContext());
mDndAllowance.check();
In the notification receiver class, where I use the NotificationCompat.Builder
, I can just use a MediaPlayer
instance and AudioManager
to set the volumes. But this only works in foreground... or did I miss something?
How is it possible to adjust the volume (just for this notification), even in background?
Thanks a lot!