异步准备

MediaPlayer$prepare() 是一个阻塞调用,将冻结 UI 直到执行完成。要解决这个问题,可以使用 MediaPlayer$prepareAsync()

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

在同步操作中,通常会使用异常或错误代码发出错误信号,但是无论何时使用异步资源,都应确保适当地通知应用程序错误。对于 MediaPlayer,

mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener(){
        @Override
        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
        }
});