Music player - activity lifecycle

885 views Asked by At

I have really hard time with background music in my app. I just want to play music in all activities - when I press home button I want to stop music. I want "stop or play" music button in all activities, but couldnĀ“t make it work.

So I decided to make embarassing choice - play it only in 1 activitiy by

onCreate

    backgroundmusic = MediaPlayer.create(StoryActivity.this, R.raw.creepy_music);
    backgroundmusic.start();

onPause

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

Can you please help me with easy activity lifecycle? So when a user presses home button - music will stop. When he will come back to app - music will be restored and this activity too (it is not MainActivity)

Thank you, guys

2

There are 2 answers

0
devDeejay On

<code>enter image description here</code>

Here are the different LifeCycle states. Now to your answer,

@Override
    protected void onStop() {
        super.onStop();
        backgroundmusic.pause();
        length = backgroundmusic.getCurrentPosition();  
    }

@Override
    protected void onResume() {
        super.onResume();
        backgroundmusic.seekTo(length);
        backgroundmusic.start();
    }

In public class MainActivity extends AppCompatActivity, It's the AppCompatActivity that is the main source of an Activity's functionality, hence in the above methods like super.onResume(); and super.onStop(); super refers to the AppCompatActivity class

0
Du.Fantasy On

assume that you can get the music service in the Application ,you may be looking for this :

 public class MyApp extends Application{

MusicService musicService;

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

    registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

        }

        @Override
        public void onActivityStarted(Activity activity) {

        }

        @Override
        public void onActivityResumed(Activity activity) {
            if(musicService==null) return;
            if(!musicService.isPlaying()){
                musicService.play();
            }
        }

        @Override
        public void onActivityPaused(Activity activity) {
             if(musicService==null) return;
             if(musicService.isPlaying()){
                musicService.pause();
            }
        }

        @Override
        public void onActivityStopped(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {

        }
    });
}

}

Hope this helps