Is it possible to adjust notification sound volume dynamically in Android O and above?
This is merely a hack, a way to get it to do so, and it will achieve your required behavior. In my application, targeting API 26; i have implemented a sound and vibration customization but manually.
NotificationCompat.Builder notification = new NotificationCompat.Builder(this, "Channel1");
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Vibrations
Vibrator vib = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(VibrationEffect.createWaveform(new long[] {200,300,500,100,100}, 1));
//Sound
Intent soundIntent = new Intent(this, PlaySound.class);
serviceIntent.setAction("ACTION_START_PLAYBACK");
serviceIntent.putExtra("UriSound", soundUri.toString());
context.startForegroundService(soundIntent);
// if notification is outted, just delete notification; thus delete intent
Intent outNotification = new Intent(context, PlaySound.class);
deleteIntent.setAction("ACTION_STOP_PLAYBACK");
PendingIntent pendingOutNotification =
PendingIntent.getService(this, 0, outNotification, 0);
builder.setDeleteIntent(pendingOutNotification);
} else {
builder.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
builder.setSound(uri);
}
notificationManager.notify(0, builder.build());
In your PlaySound.class extend service
, Play your sound on a media player
, and control volume or the particular sound based on the intent
of that particular channel
...
Target the volume or the uri based on the users input from the slider, and then send via intent
or save it in a key-value pair using sharedpreference
s.
You can achieve this by following steps Check for appropriate permission
isNotificationPolicyAccessGranted()
returns boolean and is a part of NotificationManager. It is required Android N onwards as it can mend "do not disturb" If not provided ask for the permission explicitly
Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS
set up AudioManager in your activity create a custom view with slider to fetch an int between getStreamMinVolume(5) and getStreamMaxVolume(5)
then set desired volume with
setStreamVolume(5, yourdesiredvalue in int , 0)
I hope it will help!