Android 5.0 Lollipop通知完整的声音不播放

时间:2015-01-05 13:19:29

标签: android audio notifications android-notifications android-5.0-lollipop

我有一个警报应用程序,当闹钟响起时播放声音(类似警报的连续音频)。不幸的是,在Lollipop中,声音并没有完全播放,而是在几秒钟之后停止播放。但是,如果手机连接到电源,这不会发生,并且声音实际上是完全播放的。该代码适用于以前版本的Android。有人可以帮忙吗?这是我的通知代码:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                .setAutoCancel(true)
                .setPriority(Integer.MAX_VALUE)
                .setContentTitle(someTitle)
                .setWhen(now)
                .setIcon(R.drawable.some_icon);

Notification notif = mBuilder.build();

if(Build.VERSION.SDK_INT >= 21) {
    notif.sound = audioFileUri;
    notif.category = Notification.CATEGORY_ALARM;

    AudioAttributes.Builder attrs = new AudioAttributes.Builder();
    attrs.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION);
    attrs.setUsage(useAlarm ? AudioAttributes.USAGE_ALARM : AudioAttributes.USAGE_NOTIFICATION_EVENT);
    notif.audioAttributes = attrs.build();
} else  {
    mBuilder.setSound(audioFileUri, useAlarm ? AudioManager.STREAM_ALARM : AudioManager.STREAM_NOTIFICATION);
    notif = mBuilder.build();
}

NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFICATION_ID, notif);

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,很可能这是由于Lollipop中新的省电设置,因此设备会在播放声音时进入睡眠状态。

我对此问题的解决方案是使用MediaPlayer类播放声音,因为它允许设置唤醒模式。为此,您还需要在清单中将wake_lock添加到您的权限中。

<uses-permission android:name="android.permission.WAKE_LOCK"/>

以下是使用MediaPlayer的方法:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setAutoCancel(true)
            .setPriority(Integer.MAX_VALUE)
            .setContentTitle(someTitle)
            .setWhen(now)
            .setIcon(R.drawable.some_icon);

Notification notif = mBuilder.build();

MediaPlayer player = MediaPlayer.create(context, audioFileUri);
player.setAudioStreamType(am.STREAM_MUSIC);
player.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK); //<< the important part
player.start();

NotificationManager mNotificationManager = (NotificationManager)    context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFICATION_ID, notif);