Keywords: Android | MediaPlayer | State Management | Asynchronous Preparation | Error Handling
Abstract: This article explores the common state error 'start called in state 0' in Android MediaPlayer, providing solutions through asynchronous preparation and listeners to ensure proper state management.
Problem Description
When developing an Android app for streaming internet radio, a common error is "start called in state 0" with error code -38. This corresponds to MediaPlayer's state 0 (idle), meaning that the start() method was called before MediaPlayer was properly prepared, which is not allowed.
MediaPlayer State Machine Overview
MediaPlayer has a state machine that includes idle, initialized, data source set, preparing, and prepared states. After creating a MediaPlayer object, its default state is 0 (idle). Only after calling prepare() or prepareAsync() and completing preparation can MediaPlayer enter a playable state.
Solution: Using OnPreparedListener
To avoid state errors, use the asynchronous preparation method prepareAsync() and set setOnPreparedListener(). This allows safe calling of start() within the onPrepared callback. Below is a revised code example:
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(url);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mediaPlayer.prepareAsync();In this example, prepareAsync() prepares MediaPlayer asynchronously, and start() is called in onPrepared. This ensures that all necessary initialization is completed before playback begins.
Supplement: Other Listeners and Best Practices
Referencing Answer 2, it is recommended to use other listeners such as OnErrorListener to handle error events. For instance, you can set an error listener to catch and handle error code -38. Example code:
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// Handle the error, e.g., log it or notify the user
return true; // Return true to indicate error handled
}
});Additionally, checking state before method calls is a good habit. For example, use isPlaying() to ensure MediaPlayer is playing before calling pause(). This can prevent unnecessary state exceptions.
Conclusion
To ensure proper operation of Android MediaPlayer, focus on its state management. By using prepareAsync() and listeners, errors like "start called in state 0" can be effectively avoided. It is also advised to implement robust error handling mechanisms to enhance application stability and user experience.