Home > Mobile >  unable to stop the last sound track using AudioManager in android studio
unable to stop the last sound track using AudioManager in android studio

Time:11-11

I am implemented 5mins alarm app, where we can set alarm at increment of 5mins. Ex, If I open app at 01:00PM and press button three time the alarm is set for 01:05PM, 01:10PM and 01:15PM. I used AlarmManager to set the pending intent for future broadcast and in broadcast receiver I used Notification to show notification at the same time app default ringtone using MediaPlayer. While using MediaPlayer I faced issue to stop the last alarm because when first alarm starts it is okay but if first alarm rings continuously and second alarm start then multiple alarm rings at same time. How to get the same MediaPlayer Instance in all Broadcast or is any better way to handel it?

Unable to stop the last alarm ring because of different instances of MediaPlayer Class. So if i wanted to stop the last alarm ring and start another ring then what should i do?

CodePudding user response:

To make a Media Player instance available across multiple Broadcasts, you could make a class which contains a static Media Player, meaning it'll be the same instance across all Broadcasts.

First you should make a class that contains the Media Player, and create a static method to fetch it.

class MediaPlayerHandler {

    private static MediaPlayer mediaPlayer;

    public MediaPlayerHandler() {
        mediaPlayer = new MediaPlayer();
    }

    public static MediaPlayer getMediaPlayerInstance() {
        return mediaPlayer;
    }
}

Then with the static Media Player available, you can then access it from anywhere by referencing it like below.

MediaPlayer mediaPlayer = MediaPlayerHandler.getMediaPlayerInstance();

With this implementation you should be able to access your Media Player from anywhere. Allowing you to stop and reset the alarm sound so no alarms will be overlapping.

I hope this helps. Happy coding!

CodePudding user response:

public class mediaPlayerInstance { private static MediaPlayer mediaPlayer;

public mediaPlayerInstance(MainActivity mainActivity, Uri defaultRingtoneUri) {
    mediaPlayer = MediaPlayer.create(mainActivity, defaultRingtoneUri);
}

public static MediaPlayer getMediaPlayerInstance() {
    return mediaPlayer;
}

}

And declare the this class somewhere in a code which will call once.

  • Related