I'm developing an app that handles sound and vibration of apps' notifications. I am listening to notifications using NotificationListenerService
. I am able to turn on or off notification's sound using AudioManager
as follows:
// It turns off notification's sound
myAudioManager.setStreamMute(AudioManager.STREAM_NOTIFICATION, true);
// It turns on notification's sound
myAudioManager.setStreamMute(AudioManager.STREAM_NOTIFICATION, false);
I have also tried to turn on or off notification's vibration with following code but it didn't work on my phone which has Android KitKat 4.4.4
// to turn off notification's vibration
myAudioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
// to turn on notification's vibration
myAudioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
Here's what I did. In my NotificationListenerService, I cancel the original notification, turn off its vibration, and send it out again. Code like this should work:
Integer key = 1;
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
Notification n = sbn.getNotification();
if (doINeedToDisableVibration(sbn)) {
cancelNotification(sbn.getKey());
n.defaults &= ~Notification.DEFAULT_VIBRATE;
n.vibrate = null;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
synchronized(key) {
nm.notify(key++, n);
}
}
}
In doINeedToDisableVibration(sbn), either make sure that vibration is on in the notification, or else check that sbn.packageName is NOT the same as your own package name, or you have a danger of generating an endless loop.
I am not sure this will work with all notifications. But it did work with MMS notifications on my HTC One A9 with 6.0.
setVibrateSetting api is deprecated in API 16. As per android developer site,
Applications should maintain their own vibrate policy based on current ringer mode that can be queried via getRingerMode().
So, you try with Ringer mode to enable/disable vibration.
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
for setting silent mode :
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
For normal mode :
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
For ring vibrate mode:
audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
来源:https://stackoverflow.com/questions/35765481/how-to-turn-off-vibration-of-notifications-in-android