非同步準備

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
        }
});