2014-11-14 74 views
2

我已經嘗試了幾乎所有可用的答案在網站上,但不知何故我不能讓通知聲音工作。當前的代碼我測試是這個(通知是建立在報警reciever):Android:自定義通知聲音不播放

public class AlarmReceiver extends BroadcastReceiver { 

private static final int NOTIFICATION_ID = 0; 

@Override 
public void onReceive(Context context, Intent intent) { 


    NotificationCompat.Builder builder = new NotificationCompat.Builder(context) 
      .setContentTitle(context.getString(R.string.app_name)) 
      .setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MainActivity_.class), 0)) 
      .setContentText("temporary text") 
      .setAutoCancel(true) 
      .setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE 
        + "://" + context.getPackageName() + "/raw/alert")) 
      .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE) 
      .setPriority(NotificationCompat.PRIORITY_DEFAULT) 
      .setWhen(System.currentTimeMillis()) 
      .setSmallIcon(R.drawable.ic_stat_notification); 

    Notification notification = builder.build(); 
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
    notificationManager.notify(NOTIFICATION_ID, notification); 

聲音然而,可以通過MediaPlayer的播放,所以這裏的格式不是問題。 它可能與聲音的長度(30秒)有關嗎? 謝謝你的幫助!

+0

什麼是聲音格式?例如,我可能通過MediaPlayer播放的聲音出現問題,但無法從通知中播放...嘗試用wmv替換聲音文件。 (我不記得確切的文件格式,我有問題) – 2014-11-14 14:01:59

+0

刪除/原 – eduyayo 2014-11-14 14:04:19

+0

我換成了一個WAV,並試圖刪除原料,不工作。 這裏有一點輸出,也許你們可以找出路徑錯誤的東西。 D/NotificationManager:notify:notification.sound android.resource:// * packagename(我必須隱藏它)*/raw/alert – 2014-11-14 14:14:06

回答

5

試着改變你的.setSound()這個

.setSound(Uri.parse("android.resource://" 
          + context.getPackageName() + "/" 
          + R.raw.alert)) 

希望這將工作

+0

R.raw.sound嘗試過,也沒有運氣:/ – 2014-11-14 14:12:27

+0

你的音頻格式是什麼? – 2014-11-14 14:15:32

+0

到目前爲止,嘗試了mp3和wma。我必須更具體一些,我不太瞭解編解碼器等 – 2014-11-14 14:19:31

1

讀到這裏如果從穆克什正確答案不爲你工作!

從Mukesh發佈的答案是正確的,但對我來說,它不工作,直到我發現我配置通知錯誤! (或有一個Android BUG)

該片段不起作用

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context) 
    .setDefaults(DEFAULT_VIBRATE | FLAG_SHOW_LIGHTS) 
    .setContentTitle(title) 
    .setContentText(message) 

    .setSound("android.resource://" 
         + context.getPackageName() + "/" 
         + R.raw.alert)).build(); 

-

這個片段WORKS

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context) 
    .setContentTitle(title) 
    .setContentText(message) 
    .setSound("android.resource://" 
         + context.getPackageName() + "/" 
         + R.raw.alert)).build(); 

-

.setDefaults(DEFAULT_VIBRATE | FLAG_SHOW_LIGHTS) 

觀察:就像你看到上面的行我沒有使用常量DEFAULT_SOUND,但仍然沒有工作。

+0

謝謝!!!!!因爲它不是在播放我選擇的聲音,只有系統通知聲音而感到非常沮喪。即使設置爲SOUND,也可以關閉setDefaults,瞧,完美! – Ben987654 2017-05-29 02:17:57

+0

如果這個答案對你有幫助,請注意。 – Tano 2017-08-31 18:59:58