z转自:xxx(暂时忘记了)
Apparently the documentation for the Android MediaPlayer is not right about no invalid state for reset(). Below's what happen when I experienced it:
public class PlayerActivity extends Activity {
....
public static MediaPlayer mp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Mediaplayer
if(mp == null) {
mp = new MediaPlayer();
}
....
}
/**
* Function to play a song
* @param songIndex - index of song
* */
public void playSong(int songIndex){
// Play song
try {
if(mUpdateTimeTask != null)
mHandler.removeCallbacks(mUpdateTimeTask);
mp.reset();
// the song path is get from internet
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
...
}
In my home activity, I release the player before closing the app:
public class TuoiTreAppActivity extends TabActivity {
...
@Override
public void onDestroy(){
if(PlayerActivity.mp != null) {
PlayerActivity.mp.release();
}
super.onDestroy();
}
...
}
So, when I launch the app for the first time and start playing a song. The reset() function runs well without error. But when I hit the back button to close the app and launch it for the second time, the IllegalStateException occurs when passing the reset() function.
I also discovered the cause when debugging. As the first time running the app, the player is null so it is initialized in the onCreate() function of PlayerActivity.java. But the player is not release itself to null after the app was closed. So it is not initialized again when re-opening for the second time. That's the reason why IllegalStateException occurs when passing reset() function. So, to solve this problem, I have to set the player to null before closing the app:
@Override
public void onDestroy(){
if(PlayerActivity.mp != null) {
PlayerActivity.mp.release();
// Set the MediaPlayer to null to avoid IlLegalStateException
// when call mp.reset() after launching the app again
PlayerActivity.mp = null;
}
super.onDestroy();
}
本文探讨了在Android应用中复用MediaPlayer时遇到的IllegalStateException问题,并提供了解决方案。通过在应用退出时将MediaPlayer设置为null,避免了在重新启动应用时发生的异常。
220

被折叠的 条评论
为什么被折叠?



