-3

I am an absolute beginner working on my first android app. I am working on an audio stream app and i implemented the mediaPlayer inside a service. There is a play-pause button that toggles if bound or not. The issue i have is that when isPlaying, and i change the screen orientation, though the service continues, the activity is recreated which makes the play button appear rather than the pause button. I know for me to retain the pause button, i need to override two methods - onSaveInstanceState and onRestoreInstanceState but i dont know the right logic to use in order to retain mainActivity's state. Pls help me because the examples i saw didnt solve my problem.

This is my main activity

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //.......
        if(savedInstanceState != null) {
            boolean isPlaying = savedInstanceState.getBoolean("isPlaying");
            if(!isPlaying){
                imageButton2.setImageResource(R.drawable.stop);
            } else {
                imageButton2.setImageResource(R.drawable.play);
            }
        }

    @Override
    protected void onStart() {
        // bind to the radio service
        Intent intent = new Intent(this, RadioService.class);
        startService(intent);
        bindService(intent, mConnection, BIND_AUTO_CREATE);
        super.onStart();
    }

    @Override
    protected void onResume() {


        super.onResume();
    }


    @Override
    protected void onStop() {
        // unbind the radio
        // service

        if (boundToRadioService) {
            unbindService(mConnection);
            boundToRadioService = false;
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
    radioService.hideNotification();

        if (boundToRadioService) {
            unbindService(mConnection);
            boundToRadioService = false;
        }
    super.onDestroy();
    }

    public void setupMediaPlayer(View view) {

        if (boundToRadioService) {
            boundToRadioService = false;
            imageButton2.setImageResource(R.drawable.stop);
            radioService.play();
        } else {
            boundToRadioService = true;
            imageButton2.setImageResource(R.drawable.play);
            radioService.pause();

    @Override
    protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("isPlaying", boundToRadioService);
        super.onSaveInstanceState(outState);


    }

}

This is my Service

 // Binder given to clients
    private final IBinder mBinder = new RadioBinder();
   }

    public void pause() {
        audioManager.abandonAudioFocus(audioFocusChangeListener);
        unregisterReceiver(audioBecomingNoisy);
        mediaPlayer.pause();
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        Toast.makeText(this, "Oops! Error Occured, Check your network connection", Toast.LENGTH_SHORT).show();
        mediaPlayer.reset();
        return false;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;
    }


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

    }



    public class RadioBinder extends Binder {
        RadioService getService() {
            // Return this instance of RadioBinder so clients can call public methods
            return RadioService.this;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        Log.d(TAG, "onBind: ");

        return mBinder;
    }

    public void play() {
        registerReceiver(audioBecomingNoisy, noisyIntentFilter);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        new PlayerTask().execute(stream);
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnErrorListener(this);
        mediaPlayer.reset();
        showNotification();
        Toast.makeText(this, "loading... please wait", Toast.LENGTH_LONG).show();
        Log.i(TAG, "onCreate, Thread name " + Thread.currentThread().getName());

    }


    class PlayerTask extends AsyncTask<String, Void, Boolean> {
        @Override
        protected Boolean doInBackground(String... strings) {
            try {
                mediaPlayer.setDataSource(stream);
                mediaPlayer.prepareAsync();
                prepared = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return prepared;
        }

    }
Ben Ajax
  • 668
  • 2
  • 13
  • 27

1 Answers1

0

try this,

public class MainActivity extends AppCompatActivity {

private boolean boundToRadioService = false;
private ImageButton imageButton2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageButton2 = (ImageButton) findViewById(R.id.my_button);
    if(savedInstanceState != null){
        boundToRadioService = savedInstanceState.getBoolean("isPlaying", false);
        if(boundToRadioService){
            imageButton2.setImageResource(R.drawable.stop);
        } else {
            imageButton2.setImageResource(R.drawable.play);
        }
    } else {
       // bind to the radio service
       Intent intent = new Intent(this, RadioService.class);
       startService(intent);
       bindService(intent, mConnection, BIND_AUTO_CREATE);
   }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putBoolean("isPlaying", boundToRadioService);
    super.onSaveInstanceState(outState);
}
public void setupMediaPlayer(View view){
    if (boundToRadioService) {
        boundToRadioService = false;
        imageButton2.setImageResource(R.drawable.play);
        radioService.pause();
    } else {
        boundToRadioService = true;
        imageButton2.setImageResource(R.drawable.stop);
        radioService.play();
     }
   }
}

and add android:src="@drawable/play" to the imagebutton in your xml file.

shinilms
  • 1,494
  • 3
  • 22
  • 35
  • I have an issue. The service gets restarted when trying to pause the media player after changing orientation. What's the way around this? – Ben Ajax Jun 12 '17 at 12:00
  • That's because `onStart` is called every time the orientation is changed. Delete the `onStart` method from your code and start your service from `onCreate`. I have edited my answer. Try it. – shinilms Jun 12 '17 at 12:20