I am developing an app that plays a stream by using the built-in Android Mediaplayer. Everything works fine apart the fact that when I press the "home" button and then open the activity again, the app just starts a new instance of the mediaplayer and I can hear the stream twice without the possibility to stop the first one.
Scenario.
My app is only made of one activity.
- I open my app first time and the stream starts.
- Push the home button and the activity is "minimized" but the music still plays
- I open my app again and it just starts a new instance of the mediaplayer playing the same music twice.
I check onResume if the mediaplayer is null or playing but somehow it appears to be always null thus a new instance is created.
My pseudo code...
public class MainActivity {
private MediaPlayer _mp;
private PlayTask _playTask;
private PauseTask _pauseTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume(){
super.onResume();
if(_mp != null && _mp.isPlaying()){
// I should find a playing mediaplayer here but it's always null!!!
Toast.makeText(MainActivity.this, "Playing mediaplayer found!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "No mediaplayer found :(", Toast.LENGTH_SHORT).show();
}
}
/* ...:::============= *** ASYNCTASK Definition START *** =============:::... */
private class PlayTask extends AsyncTask<Void, Void, Integer> {
@Override
protected void onPreExecute() {
if(_mp == null)
_mp = new MediaPlayer();
else if(_mp.isPlaying()){
_mp.stop();
_mp.release();
_mp = null;
_mp = new MediaPlayer();
}
}
@Override
protected Integer doInBackground(Void...voids) {
try{
_mp.setDataSource(URL_DATASOURCE);
_mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
_mp.prepare();
_mp.start();
}
catch(Exception ex){
}
return 0;
}
@Override
protected void onPostExecute(Integer i) {
}
}
private class PauseTask extends AsyncTask<Void, Void, Integer> {
@Override
protected void onPreExecute() {
// Do Nothing here...for now
}
@Override
protected Integer doInBackground(Void...voids) {
_mp.stop();
_mp.release();
_mp = null;
return 0;
}
@Override
protected void onPostExecute(Integer i) {
}
}
public void playPause(View view){
if(_play){
_playTask = new PlayTask();
_playTask.execute();
}
else{
_pauseTask = new PauseTask();
_pauseTask.execute();
}
}
}
Any idea? Thanks