So I am using a URL to stream audio using mediaPlayer- I can start the stream no problem- and stop it as well...as long as I don't switch activities.
The problem happens when I start the stream...then switch activities....then come back and try to stop it. I get a crash because I think the variable is already null even though mediaPlayer is still running.
I am declaring my mediaPlayer as a public in the main thread- so not sure why it's being seen as null after switching activities.
Here is my code for starting the stream, and closing it:
if(v.getId()==R.id.btnStart){
Context context = getApplicationContext();
AppPrefs appPrefs = new AppPrefs(context);
if(listening==false){
appPrefs.set_stream("1");
txtListen.setVisibility(View.VISIBLE);
listening=true;
btnStart.setText("Stop Stream");
String url = "http://streamingurl";
mediaPlayer = new MediaPlayer();
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // might take long! (for buffering, etc)
mediaPlayer.start();
}
else{
appPrefs.set_stream("0");
listening=false;
if(
mediaPlayer!=null){mediaPlayer.release();
mediaPlayer = null;
}
btnStart.setText("Start Stream");
txtListen.setVisibility(View.INVISIBLE);
}
}