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();
}
}
You can create a
Service
that will keep the music playing on the backgroundSample code:
For more details, please refer here.