Android - How to keep music playing while inside the app?

1.2k views Asked by At

I want to set up the background music of my app so that it will keep playing while I am on the app, and pause when I press the home button. The problem is that if I pause the music when the phone goes to the home screen, it also pauses the music when I go to a different activity within my app. Is there a way to keep the music playing while I switch activities (e.g. I have a menu, from which I can open different screens in my app, and the music stops playing as soon as the phone leaves the menu screen). My code is as follows:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1,
            classes));
    mp = MediaPlayer.create(Menu.this, R.raw.music);
    mp.start();

}

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

@Override
protected void onStop() {
    super.onStop();
    mp.pause();
}

@Override
protected void onResume() {
    super.onResume();
    mp.start();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    mp.release();
    finish();
}

}

2

There are 2 answers

1
bjiang On BEST ANSWER

You can create a Service that will keep the music playing on the background

Sample code:

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;

public class PlayAudio extends Service{
    private static final String LOGCAT = null;
    MediaPlayer objPlayer;

    public void onCreate(){
        super.onCreate();
        Log.d(LOGCAT, "Service Started!");
        objPlayer = MediaPlayer.create(this,R.raw.sleepaway);
    }

    public int onStartCommand(Intent intent, int flags, int startId){
        objPlayer.start();
        Log.d(LOGCAT, "Media Player started!");
        if(objPlayer.isLooping() != true){
            Log.d(LOGCAT, "Problem in Playing Audio");
        }
        return 1;
    }

    public void onStop(){
        objPlayer.stop();
        objPlayer.release();
    }

    public void onPause(){
        objPlayer.stop();
        objPlayer.release();
    }
    public void onDestroy(){
        objPlayer.stop();
        objPlayer.release();
    }
    @Override
    public IBinder onBind(Intent objIndent) {
        return null;
    }
}

For more details, please refer here.

1
arthur_gg On

I see 2 different solutions:

  • Create a class that extends Application and put your music player there.

  • Create a Service that will read the music on the background