Android Notification 的声音和震动


使用震动需要注意添加权限:

<uses-permission android:name="android.permission.VIBRATE"/>

使用系统默认的声音和震动

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设置自定义的声音和震动

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)

Sound

Notification的声音参数,要求类型为Uri.关于Uri的规范,可参考 http://www.ietf.org/rfc/rfc2396.txt.

1.获取uri

//从raw Uri sound=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notificationsound ); or Uri sound=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/notificationsound"); or 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())); //从ContentResolver

2.设置uri

notification.sound =Uri sound; NotificationCompat.Builder.setSound(Uri sound)


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM