Search code examples
androidandroid-music-player

How to play music in the background through out the App continuously?


I have 4 activities in my android app.When the first activity is created, it starts music in the background. Now when the user goes from 1st activity to the 2nd activity I want the song to continue without any interruption. The song should stop only when the user is out of the app.

Right now the music stops when I am going out of one activity and starts from the beginning in the next activity.


Solution

  • Keep the player in the background as a static reference. Then let it know if you are moving within the app or out of it. Here is how I would do it. I am using a class named DJ for this purpose.

    public class DJ { 
    private static MediaPlayer player;
    private static boolean keepMusicOn;
    
    public static void iAmIn(Context context){
    if (player == null){
    player = MediaPlayer.create(context, R.raw.music1);
    player.setLooping(true);
    
    try{
    player.prepare();
    }
    catch (IllegalStateException e){}
    catch (IOException e){}
    }
    
    if(!player.isPlaying()){
    player.start();
    }
    
    keepMusicOn= false;
    }
    
    public static void keepMusicOn(){
    keepMusicOn= true;
    }
    
    public static void iAmLeaving(){
    
    if(!keepMusicOn){
    player.pause();
    }
    }
    }
    

    Now from your Activity call the DJ like this.(Let him know if you would like to keep the music on)

    public void onPause() {
    super.onPause();
    DJ.iAmLeaving();
    }
    
    public void onResume(){
    super.onResume();
    DJ.iAmIn(this); 
    }
    
    public void buttonOnClick(View view){
    DJ.keepMusicOn();
    Intent intent = new Intent(this, TheOtherActivity.class);
    startActivity(intent);
    }