Search code examples
androidmedia-playerlifecyclekill

Media player will not stop playing audio file after broadcast intent to stop it


I am using the Android MediaPlayer class to play an mp3 file from a running Service class. I wanted to stop the music player from playing if the user stops viewing any of the five Activities.

I tried it by using the code here to send a broadcast intent to the Service that holds the MediaPlayer. That way when the broadcast receiver inside of the Service receives this intent it will call the player.pause() method to stop the music from playing.

However it is not working. I started the player while viewing one of the activities, then next I left the application and viewed some other app like the Android calendar app. The music does not stop and keeps playing.

Any ideas on how to fix this problem?

   public class Monitor extends Application {

  @Override
   public void onCreate(){
   super.onCreate();

   if(activityVisible==false){
        Intent intent = new Intent();
        intent.setAction("com.sample.test");
        sendBroadcast(intent);
   }

   }


 public static boolean isActivityVisible() {
        return activityVisible;
      }  

      public static void activityResumed() {
        activityVisible = true;
      }

      public static void activityPaused() {
        activityVisible = false;

      }

      private static boolean activityVisible;

   }

And here is what I put in each of the other 5 activities;

  @Override
  protected void onResume() {
    super.onResume();
    Monitior.activityResumed();
  }

  @Override
  protected void onPause() {
     super.onPause();
    Monitor.activityPaused();
  }

Solution

  • onCreate in the Application class is not called when each of your activity's is created. Is this what you intended?

    So your Monitor will change the activityVisible to false, but from the code you have posted nothing ever acts upon this boolean.

    One solution is to create a MonitorActivity and have all your Activitys extends this. Then in the onCreate of the MonitorActivity you will send your broadcast to start the service and in the onPause stop the service. Yes this will pause between activitys so you could have a 3 second fuse of whether the service should actually stop.