2

In my project I am trying to make a media player which plays a shoutcast stream. Everything seemed to be working well until I pressed the back button on my device, which I think stops the activity and causes the device to recreate the activity when launched again. The problem is , when the activity is recreated , I lose the control of the mediaplayer and a new mediaplayer is created.

I need to be able to have the mediaplayer's control back at that point. How is it possible?

This part of code belongs to onCreate

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.button);
    if (mediaPlayer == null){
        mediaPlayer = new MediaPlayer();
    try {
        mediaPlayer.setDataSource(getString(R.string.yayin));
    } catch (Exception e) {
        e.printStackTrace();
    }
    mediaPlayer.prepareAsync();
    }

    if(!isPlaying){

        btn.setBackgroundResource(R.drawable.oynat);

    }
    else{

        btn.setBackgroundResource(R.drawable.durdur);

    }
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(!isPlaying){

                playOnReady();
                isPlaying = true;
                btn.setBackgroundResource(R.drawable.durdur);

            }
            else{

                mediaPlayer.reset();
                isPlaying = false;
                btn.setBackgroundResource(R.drawable.oynat);

            }
        }
    });

This part of code belongs to the function playOnReady()

 private void playOnReady(){

    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();

        }
    });

}
  • Use a single instance of MediaPlayer like this. http://stackoverflow.com/questions/14135459/create-only-one-object-for-a-class-and-reuse-same-object. So you will have the same instance everywhere in the app . – Sunil Sunny Jun 30 '16 at 14:35
  • I solved the problem by using a service ! Thanks anyway! – Erdem Erten Jun 30 '16 at 14:39

2 Answers2

0

Take a look at the Android Activity lifecycle flowchart: https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

You need to account for the path where onPause is called when you leave the Activity and then onResume is called when you enter it again. The solution for you could be as simple as moving some/all of your code from onCreate into onResume.

Eric Levine
  • 13,536
  • 5
  • 49
  • 49
  • I've understood the cycle but when I moved the related part to onResume nothing has changed. Still, I don't have the control of the player. – Erdem Erten Jun 30 '16 at 14:00
0

Using this tutorial I have managed to build a service which handles the mediaplayer that I can have the control of anytime I need.