Android:Notification 设置声音和震动
一、使用系统默认的声音和震动
1、设置Notification
//使用默认的声音
notif.defaults |= Notification.DEFAULT_SOUND;
//使用默认的震动
notif.defaults |= Notification.DEFAULT_VIBRATE;
//使用默认的声音、振动、闪光
notif.defaults = Notification.DEFAULT_ALL;
2、设置NotificationCompat.Builder
NotificationCompat.Builder setDefaults(int defaults)
//使用默认的声音、振动、闪光
new Notification.Builder(context).setDefaults(Notification.DEFAULT_ALL);
//使用默认的震动和声音
new Notification.Builder(context).setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE)
二、为Notification设置自定义的声音和震动
1、震动(Vibrate)
AndroidNotification 震动实际上是调用Vibrator的vibrate (long[] pattern, int repeat)这个方法,传入的参数是一个long[].
long[]参数的介绍
数组第一个参数表示延迟震动时间
第二个参数表示震动持续时间
第三个参数表示震动后的休眠时间
第四个参数又表示震动持续时间
第五个参数也表示正到休眠时间
以此类推
// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 1000 milliseconds
long[] pattern = {0, 100, 1000};
// Start without a delay
// Each element then alternates between vibrate, sleep, vibrate, sleep...
long[] pattern1 = {0, 100, 1000, 300, 200, 100, 500, 200, 100};
为Notification设置自定义的振动模式
//为Notification设置
notification.vibrate = pattern;
//为Builder设置
NotificationCompat.Builder.setVibrate (pattern)
2、声音(Sound)
Notification 的声音参数,要求类型为Uri.
【1】获取uri
//从raw
Uri sound=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notificationsound );
Uri sound=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/notificationsound");
Uri sound=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/"+R.raw.notificationsound);
//从铃声管理器
Uri sound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//从文件
Uri sound=Uri.fromFile(new File("/sdcard/sound.mp3"))
Uri sound=Uri.parse(new File("/sdcard/sound.mp3").toString()));
【2】设置uri
notification.sound =Uri sound;
NotificationCompat.Builder.setSound(Uri sound)