我們在Android系統發送一條Notification的時候,經常需要通過震動或聲音來提醒用戶。如何為Notification設置聲音和震動了。大致思路有:
- AndroidNotification系統默認的聲音和震動
- 為AndroidNotification設置自定義的聲音和震動
- 自己使用Vibrator和SoundPool來產生聲音和震動
使用震動需要注意添加權限:
<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)
自己調用震動和聲音播放
使用震動
http://stackoverflow.com/questions/13950338/how-to-make-an-android-device-vibrate