Android Notification 的聲音和震動

來源:互聯網
上載者:User

標籤:[]   round   檔案   val   get   car   tis   new   休眠   

我們在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 millisecondslong[] 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
//從rawUri sound=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notificationsound ); orUri sound=Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/notificationsound"); orUri 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

 播放聲音

Android Notification 的聲音和震動

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.