Android:自定义通知声音不播放

问题描述:

我已经尝试了几乎所有可用的答案在网站上,但不知何故我不能让通知声音工作。当前的代码我测试是这个(通知是建立在报警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

试着改变你的.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

读到这里如果从穆克什正确答案不为你工作!

从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