android的mediaplayer在release后一定需要=null

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:


In my PlayerActivity.java code, I set my MediaPlayer as static so that I can use it in my home activity:


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在release后一定需要=null)