【问题标题】:Android 5.0 Lollipop notification full sound doesn't playAndroid 5.0 Lollipop 通知完整的声音不播放
【发布时间】:2015-01-05 13:19:29
【问题描述】:

我有一个闹钟应用程序,它会在闹钟响起时播放声音(类似闹钟的连续音频)。不幸的是,在 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);

【问题讨论】:

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


    【解决方案1】:

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

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

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

    媒体播放器的使用方法如下:

    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);
    

    【讨论】:

      猜你喜欢
      • 2012-01-14
      • 1970-01-01
      • 2012-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多