我正在开发一款使用内置Android Mediaplayer播放流的应用。除了我按下" home"之外,一切都很好。按钮,然后再次打开活动,应用程序只是启动媒体播放器的新实例,我可以听到两次流,但没有可能停止第一个。
情景。
我的应用仅由一项活动组成。
我检查onResume是否媒体播放器为空或播放但不知何故它似乎总是为null因此创建了一个新实例。
我的伪代码......
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();
}
}
}
有什么想法吗?感谢