Android 5.0 Lollipop full notification sound not playing

I have an alarm clock app that plays a sound (continuous beep sound) when the alarm goes off. Unfortunately, in Lollipop, the sound does not play completely, instead it stops after a couple of seconds. But if the phone is connected to a power source, this does not happen and the sound is played in full. The code works fine on previous Android versions. Can anyone please help? Here's my code for notification:

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

      

+3


source to share


1 answer


I ran into the same problem and it is most likely due to the new power saving settings in Lollipop, so the device goes to sleep while audio is playing.

My solution to this problem is to use the MediaPlayer class to play audio as it allows wakemode to be set. To do this, you also need to add wake_lock to your permission in the manifest.

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

      



Here's how to use 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);

      

0


source







All Articles