Search code examples
androidbroadcastreceiverandroid-mediaplayerandroid-lifecycle

Stop Android Media Player loop that is started from a BroadcastReceiver


I have a BroadcastReceiver that initiate a MediaPlayer and play a sound in loop. My Problem is, when the app is in the background and the receiver is triggered, the player plays the sound. Now I want to stop the player, when I open my app again. I tried to send a message to the receiver in onResume of an Activity but the instance of the player is null. How can I stop the player when I start / reopen my application?


Solution

  • Try to control MediaPlayer from Service and use Context.startService() and Context.stopService() and handle MediaPlayer in his lifecycle

    Use this Intent:

    final Intent mpServiceIntent = new Intent(context, MPService.class);
    

    When your BroadcastReceiver gets triggered use:

    startService(mpServiceIntent);
    

    When the Activity.onCreate() called use:

    stopService(mpServiceIntent);