0

I've a problem in android and i test every methods but i cant solve it!! I want to play some musics in some activities it means I have a music for home Activity and another one for second Activity and another music for another activity and etc ...! when my app runs i want to play background music activity and when the user goes to another activity i want at first home music should be stop! and then second activity music should be play! it's important when I go back to home activity, home music should play again!

is there any person can help me ?! thanks a lot to any one that reply to me!

  • As far as I'm concerned, the solution is very straight forward. Start your music in onCreate(), stop it in onPause() and or onStop(). Repeat process for all activities. This is a crude but fast approach. – Taslim Oseni Feb 18 '19 at 22:10

1 Answers1

1

You can create MediaPlayer object in every Activity. Then it's just a switch between your music files location.

MediaPlayer mp;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mp= MediaPlayer.create(getApplicationContext(), \your song location\);

    mp.start();

}

@Override
protected void onPause() {
    super.onPause();
    mp.stop();
    mp.release();
}
itsMike
  • 64
  • 10
  • thanks a lot for your reply! but there is a problem! i did it like your code and copy that in another activity with a different song name! but when i come back from second activity to first activity by back button , the music doesn't play!! – Ali Hatefi Feb 18 '19 at 23:54
  • 1
    To control what happens when the user presses the back button in your fragment, overrride the onBackPressed of the Fragment. Check this: https://stackoverflow.com/a/46425415/5670752. – Taslim Oseni Feb 19 '19 at 00:04