Search code examples
androidandroid-activitybroadcastreceiverandroid-mediaplayerandroid-lifecycle

Prevent MediaPlayer from playing multiple audio files in Broadcastreceiver at same time


I have implemented a MediaPlayer that starts playing an audio file in a BroadcastReceiver on receiving a certain Intent. I've tried to use isPlaying() method to check if MediaPlayer is playing something before starting another audio. It works fine if the Intent is fired multiple times within the activity lifecycle.

My Problem is, that the Intent is always fired when the Activity is started, thus making the BroadcastReceiver creating a MediaPlayer object everytime I e.g. go to another activity and come back. I don't want to stop the audio when leaving the current activity (and it doesn't stop with my current code), I just want to prevent the MediaPlayer start playing again when another audio is playing. So how do I let's say create a global MediaPlayer that can be accessed from a BroadcastReceiver? Or how do I check if a MediaPlayer already exist so the BroadcastReceiver doesn't create a MediaPlayer object everytime it receives an Intent?


Solution

  • I would suggest making a separate service that the BroadcastReceiver starts/stops. Inside this service create your MediaPlayer object. You can then check if the service is running already to see if your MediaPlayer already exists. Or an even better method would be to create a bind to the service so you can then interact with it from your activities. Here's some code that you can use to check if your service is currently running.

    public boolean isServiceRunning(Context context, Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
    

    You would call this with isServiceRunning(this, MyService.class) and it would return true or false.

    I would also highly recommend checking out https://developer.android.com/guide/components/bound-services.html to learn more about binding to your service, then you can interact with your MediaPlayer to your heart's content.