2012-12-07 29 views
35

我複製了MP3(kalimba.mp3)文件輸出到在res文件夾中的文件夾raw。但是當通知被觸發時,它會產生默認聲音。如何設置自定義聲音通知在Android的

這是如何使一個通知:

protected void GenerateNotify() { 

    NotificationManager myNotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 
    Notification notification=new Notification(android.R.drawable.ic_btn_speak_now,"hi",100); 
    Intent intent=new Intent(getApplicationContext(),as.class); 
    PendingIntent contentintent=PendingIntent.getBroadcast(getApplicationContext(),0, intent, 0); 
    notification.setLatestEventInfo(getApplicationContext(), "Hi","date", contentintent); 
    notification.flags |= Notification.FLAG_AUTO_CANCEL; 
    notification.sound = Uri.parse("android.resource://com.example.serviceproject/" + R.raw.kalimba); 
    myNotificationManager.notify(NOTIFICATION_ID,notification); 
} 
+0

您的代碼看起來確定。嘗試重新啓動你的模擬器或手機。 http://stackoverflow.com/questions/5682321/android-notification-sound-defaulting-back-instead-of-playing-custom-sound –

回答

102
notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd); 
notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE; 

如果定義DEFAULT_SOUND,則默認的聲音將覆蓋任何聲音

+0

如何添加.MP3文件通知。 –

+0

把你的mp3文件放到原始文件夾中 – QuokMoon

+2

如果我不寫'notification.defaults',那麼播放自定義聲音的可能性是什麼? –

16

R.raw.kalimba是整數資源ID;你想在Uri聲音資源的。因此,嘗試:

notification.sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE 
     + "://" + getPackageName() + "/raw/kalimba"); 
3

嘗試:

烏里聲音= Uri.parse( 「android.resource://」 + context.getPackageName()+「/原料/ notifysnd); 通知。 setSound(音);

1

,就應該替換該行:

notification.sound = Uri.parse("android.resource://com.example.serviceproject/" + R.raw.kalimba); 

與此:

notification.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/kalimba")); 

或在某些情況下:

notification.sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/kalimba"); 
相關問題