Android MediaPlayer Asynchronous prepare

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


The MediaPlayer$prepare() is a blocking call and will freeze the UI till execution completes. To solve this problem, MediaPlayer$prepareAsync() can be used.

mMediaPlayer = ... // Initialize it here
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
    public void onPrepared(MediaPlayer player) {
        // Called when the MediaPlayer is ready to play
}); // Set callback for when prepareAsync() finishes
mMediaPlayer.prepareAsync(); // Prepare asynchronously to not block the Main Thread

On synchronous operations, errors would normally be signaled with an exception or an error code, but whenever you use asynchronous resources, you should make sure your application is notified of errors appropriately. For MediaPlayer,

mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener(){
        public boolean onError(MediaPlayer mp, int what, int extra) {
            // ... react appropriately ...
            // The MediaPlayer has moved to the Error state, must be reset!
            // Then return true if the error has been handled

Got any Android Question?