Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 遊戲 >> Android 遊戲開發

Android 遊戲開發教程(九):深入剖析 VideoView 類的實作原理

編輯:Android 遊戲開發

想真正搞懂 Android 的圖形繪製機制,光會用 API 是不夠的,讀懂系統原始碼往往能讓你豁然開朗。本節延續上一回 SurfaceView 的討論,帶大家走進系統內建的 VideoView 類,看看一個功能完整的影片播放器是如何被打造出来的。

或許你會發現,VideoView 在控制層面上有點「不聽話」——想自訂播放介面時處處受限。這正是因為它把播放邏輯與畫面控制綁得比較死。想做出更個人化的播放器,最理想的做法就是繼承 VideoView 加以重構,而這一切的前提,是你得先讀懂它。以下是 VideoView 的相關程式碼:

  1. public class VideoView extends SurfaceView implements MediaPlayerControl {
  2.     private String TAG = "VideoView";
  3.     // settable by the client
  4.     private Uri          mUri;
  5.     private int          mDuration;
  6.  
  7.     // all possible internal states
  8.     private static final int STATE_ERROR                   = -1;
  9.     private static final int STATE_IDLE                      = 0;
  10.     private static final int STATE_PREPARING                 = 1;
  11.     private static final int STATE_PREPARED                  = 2;
  12.     private static final int STATE_PLAYING                  = 3;
  13.     private static final int STATE_PAUSED                    = 4;
  14.     private static final int STATE_PLAYBACK_COMPLETED = 5;
  15.  
  16.     // mCurrentState is a VideoView object's current state.
  17.     // mTargetState is the state that a method caller intends to reach.
  18.     // For instance, regardless the VideoView object's current state,
  19.     // calling pause() intends to bring the object to a target state
  20.     // of STATE_PAUSED.
  21.     private int mCurrentState = STATE_IDLE;
  22.     private int mTargetState  = STATE_IDLE;
  23.  
  24.     // All the stuff we need for playing and showing a video
  25.     private SurfaceHolder mSurfaceHolder = null;
  26.     private MediaPlayer mMediaPlayer = null;
  27.     private int          mVideoWidth;
  28.     private int          mVideoHeight;
  29.     private int          mSurfaceWidth;
  30.     private int          mSurfaceHeight;
  31.     private MediaController mMediaController;
  32.     private OnCompletionListener mOnCompletionListener;
  33.     private MediaPlayer.OnPreparedListener mOnPreparedListener;
  34.     private int          mCurrentBufferPercentage;
  35.     private OnErrorListener mOnErrorListener;
  36.     private int          mSeekWhenPrepared;  // recording the seek position while preparing
  37.     private boolean      mCanPause;
  38.     private boolean      mCanSeekBack;
  39.     private boolean      mCanSeekForward;
  40.  
  41.     public VideoView(Context context) {
  42.         super(context);
  43.         initVideoView();
  44.     }
  45.     
  46.     public VideoView(Context context, AttributeSet attrs) {
  47.         this(context, attrs, 0);
  48.         initVideoView();
  49.     }
  50.     
  51.     public VideoView(Context context, AttributeSet attrs, int defStyle) {
  52.         super(context, attrs, defStyle);
  53.         initVideoView();
  54.     }
  55.  
  56.     @Override  
  57.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  58.         //Log.i("@@@@", "onMeasure");
  59.         int width = getDefaultSize(mVideoWidth, widthMeasureSpec);
  60.         int height = getDefaultSize(mVideoHeight, heightMeasureSpec);
  61.         if (mVideoWidth > 0 && mVideoHeight > 0) {
  62.             if ( mVideoWidth * height  > width * mVideoHeight ) {
  63.                 //Log.i("@@@", "image too tall, correcting");
  64.                 height = width * mVideoHeight / mVideoWidth;
  65.             } else if ( mVideoWidth * height  < width * mVideoHeight ) {
  66.                 //Log.i("@@@", "image too wide, correcting");
  67.                 width = height * mVideoWidth / mVideoHeight;
  68.             } else {
  69.                 //Log.i("@@@", "aspect ratio is correct: " +
  70.                         //width+"/"+height+"="+
  71.                         //mVideoWidth+"/"+mVideoHeight);
  72.             }
  73.         }
  74.         //Log.i("@@@@@@@@@@", "setting size: " + width + 'x' + height);
  75.         setMeasuredDimension(width, height);
  76.     }
  77.  
  78.     public int resolveAdjustedSize(int desiredSize, int measureSpec) {
  79.         int result = desiredSize;
  80.         int specMode = MeasureSpec.getMode(measureSpec);
  81.         int specSize =  MeasureSpec.getSize(measureSpec);
  82.  
  83.         switch (specMode) {
  84.             case MeasureSpec.UNSPECIFIED:
  85.                 /* Parent says we can be as big as we want. Just don't be larger
  86.                  * than max size imposed on ourselves.
  87.                 */  
  88.                 result = desiredSize;
  89.                 break;
  90.  
  91.             case MeasureSpec.AT_MOST:
  92.                 /* Parent says we can be as big as we want, up to specSize.
  93.                  * Don't be larger than specSize, and don't be larger than
  94.                  * the max size imposed on ourselves.
  95.                 */
  96.                 result = Math.min(desiredSize, specSize);
  97.                 break;
  98.                 
  99.             case MeasureSpec.EXACTLY:
  100.                 // No choice. Do what we are told.
  101.                 result = specSize;
  102.                 break;
  103.         }
  104.         return result;
  105. }
  106.  
  107.     private void initVideoView() {
  108.         mVideoWidth = 0;
  109.         mVideoHeight = 0;
  110.         getHolder().addCallback(mSHCallback);
  111.         getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
  112.         setFocusable(true);
  113.         setFocusableInTouchMode(true);
  114.         requestFocus();
  115.         mCurrentState = STATE_IDLE;
  116.         mTargetState  = STATE_IDLE;
  117.     }
  118.  
  119.     public void setVideoPath(String path) {
  120.         setVideoURI(Uri.parse(path));
  121.     }
  122.  
  123.     public void setVideoURI(Uri uri) {
  124.         mUri = uri;
  125.         mSeekWhenPrepared = 0;
  126.         openVideo();
  127.         requestLayout();
  128.         invalidate();
  129.     }
  130.  
  131.     public void stopPlayback() {
  132.         if (mMediaPlayer != null) {
  133.             mMediaPlayer.stop();
  134.             mMediaPlayer.release();
  135.             mMediaPlayer = null;
  136.             mCurrentState = STATE_IDLE;
  137.             mTargetState  = STATE_IDLE;
  138.         }
  139.     }
  140.  
  141.     private void openVideo() {
  142.         if (mUri == null || mSurfaceHolder == null) {
  143.             // not ready for playback just yet, will try again later
  144.             return;
  145.         }
  146.         // Tell the music playback service to pause
  147.         // TODO: these constants need to be published somewhere in the framework.
  148.         Intent i = new Intent("com.android.music.musicservicecommand");
  149.         i.putExtra("command", "pause");
  150.         mContext.sendBroadcast(i);
  151.  
  152.         // we shouldn't clear the target state, because somebody might have
  153.         // called start() previously
  154.         release(false);
  155.         try {
  156.             mMediaPlayer = new MediaPlayer();
  157.             mMediaPlayer.setOnPreparedListener(mPreparedListener);
  158.             mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
  159.             mDuration = -1;
  160.             mMediaPlayer.setOnCompletionListener(mCompletionListener);
  161.             mMediaPlayer.setOnErrorListener(mErrorListener);
  162.             mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
  163.             mCurrentBufferPercentage = 0;
  164.             mMediaPlayer.setDataSource(mContext, mUri);
  165.             mMediaPlayer.setDisplay(mSurfaceHolder);
  166.             mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  167.             mMediaPlayer.setScreenOnWhilePlaying(true);
  168.             mMediaPlayer.prepareAsync();
  169.             // we don't set the target state here either, but preserve the
  170.             // target state that was there before.
  171.             mCurrentState = STATE_PREPARING;
  172.             attachMediaController();
  173.         } catch (IOException ex) {
  174.                 Log.w(TAG, "Unable to open content: " + mUri, ex);
  175.                 mCurrentState = STATE_ERROR;
  176.                 mTargetState = STATE_ERROR;
  177.                 mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
  178.                 return;
  179.         } catch (IllegalArgumentException ex) {
  180.                 Log.w(TAG, "Unable to open content: " + mUri, ex);
  181.                 mCurrentState = STATE_ERROR;
  182.                 mTargetState = STATE_ERROR;
  183.                 mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
  184.                 return;
  185.         }
  186.     }
  187.  
  188.     public void setMediaController(MediaController controller) {
  189.         if (mMediaController != null) {
  190.             mMediaController.hide();
  191.         }
  192.         mMediaController = controller;
  193.         attachMediaController();
  194.     }
  195.  
  196.     private void attachMediaController() {
  197.         if (mMediaPlayer != null && mMediaController != null) {
  198.             mMediaController.setMediaPlayer(this);
  199.             View anchorView = this.getParent() instanceof View ?
  200.                     (View)this.getParent() : this;
  201.             mMediaController.setAnchorView(anchorView);
  202.             mMediaController.setEnabled(isInPlaybackState());
  203.         }
  204.     }
  205.  
  206.     MediaPlayer.OnVideoSizeChangedListener mSizeChangedListener =
  207.         new MediaPlayer.OnVideoSizeChangedListener() {
  208.             public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
  209.                 mVideoWidth = mp.getVideoWidth();
  210.                 mVideoHeight = mp.getVideoHeight();
  211.                 if (mVideoWidth != 0 && mVideoHeight != 0) {
  212.                     getHolder().setFixedSize(mVideoWidth, mVideoHeight);
  213.                 }
  214.             }
  215.     };
  216.  
  217.     MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() {
  218.         public void onPrepared(MediaPlayer mp) {
  219.             mCurrentState = STATE_PREPARED;
  220.  
  221.             // Get the capabilities of the player for this stream
  222.             Metadata data = mp.getMetadata(MediaPlayer.METADATA_ALL,
  223.                                       MediaPlayer.BYPASS_METADATA_FILTER);
  224.  
  225.             if (data != null) {
  226.                 mCanPause = !data.has(Metadata.PAUSE_AVAILABLE)
  227.                          || data.getBoolean(Metadata.PAUSE_AVAILABLE);
  228.                 mCanSeekBack = !data.has(Metadata.SEEK_BACKWARD_AVAILABLE)
  229.                          || data.getBoolean(Metadata.SEEK_BACKWARD_AVAILABLE);
  230.                 mCanSeekForward = !data.has(Metadata.SEEK_FORWARD_AVAILABLE)
  231.                          || data.getBoolean(Metadata.SEEK_FORWARD_AVAILABLE);
  232.             } else {
  233.                 mCanPause = mCanSeekForward = mCanSeekForward = true;
  234.             }
  235.  
  236.             if (mOnPreparedListener != null) {
  237.                 mOnPreparedListener.onPrepared(mMediaPlayer);
  238.             }
  239.             if (mMediaController != null) {
  240.                 mMediaController.setEnabled(true);
  241.             }
  242.             mVideoWidth = mp.getVideoWidth();
  243.             mVideoHeight = mp.getVideoHeight();
  244.  
  245.             int seekToPosition = mSeekWhenPrepared;  // mSeekWhenPrepared may be changed after seekTo() call
  246.             if (seekToPosition != 0) {
  247.                 seekTo(seekToPosition);
  248.             }
  249.             if (mVideoWidth != 0 && mVideoHeight != 0) {
  250.                 //Log.i("@@@@", "video size: " + mVideoWidth +"/"+ mVideoHeight);
  251.                 getHolder().setFixedSize(mVideoWidth, mVideoHeight);
  252.                 if (mSurfaceWidth == mVideoWidth && mSurfaceHeight == mVideoHeight) {
  253.                     // We didn't actually change the size (it was already at the size
  254.                     // we need), so we won't get a "surface changed" callback, so
  255.                     // start the video here instead of in the callback.
  256.                     if (mTargetState == STATE_PLAYING) {
  257.                         start();
  258.                         if (mMediaController != null) {
  259.                            mMediaController.show();
  260.                         }
  261.                     } else if (!isPlaying() &&
  262.                                      (seekToPosition != 0 || getCurrentPosition() > 0)) {
  263.                     if (mMediaController != null) {
  264.                             // Show the media controls when we're paused into a video and make 'em stick.
  265.                            mMediaController.show(0);
  266.                         }
  267.                     }
  268.                 }
  269.             } else {
  270.                 // We don't know the video size yet, but should start anyway.
  271.                 // The video size might be reported to us later.
  272.                 if (mTargetState == STATE_PLAYING) {
  273.                     start();
  274.                 }
  275.             }
  276.             }
  277.     };
  278.  
  279.     private MediaPlayer.OnCompletionListener mCompletionListener =
  280.         new MediaPlayer.OnCompletionListener() {
  281.             public void onCompletion(MediaPlayer mp) {
  282.                 mCurrentState = STATE_PLAYBACK_COMPLETED;
  283.                 mTargetState = STATE_PLAYBACK_COMPLETED;
  284.                 if (mMediaController != null) {
  285.                     mMediaController.hide();
  286.                 }
  287.                 if (mOnCompletionListener != null) {
  288.                     mOnCompletionListener.onCompletion(mMediaPlayer);
  289.                 }
  290.             }
  291.     };
  292.  
  293.     private MediaPlayer.OnErrorListener mErrorListener =
  294.         new MediaPlayer.OnErrorListener() {
  295.             public boolean onError(MediaPlayer mp, int framework_err, int impl_err) {
  296.                 Log.d(TAG, "Error: " + framework_err + "," + impl_err);
  297.                 mCurrentState = STATE_ERROR;
  298.                 mTargetState = STATE_ERROR;
  299.                 if (mMediaController != null) {
  300.                     mMediaController.hide();
  301.                 }
  302.  
  303.                 /* If an error handler has been supplied, use it and finish. */
  304.                 if (mOnErrorListener != null) {
  305.                     if (mOnErrorListener.onError(mMediaPlayer, framework_err, impl_err)) {
  306.                         return true;
  307.                     }
  308.                 }
  309.  
  310.                 /* Otherwise, pop up an error dialog so the user knows that
  311.                   * something bad has happened. Only try and pop up the dialog
  312.                   * if we're attached to a window. When we're going away and no
  313.                   * longer have a window, don't bother showing the user an error.
  314.                 */
  315.                 if (getWindowToken() != null) {
  316.                     Resources r = mContext.getResources();
  317.                     int messageId;
  318.  
  319.                     if (framework_err == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
  320.                         messageId = com.android.internal.R.string.VideoView_error_text_invalid_progressive_playback;
  321.                     } else {
  322.                         messageId = com.android.internal.R.string.VideoView_error_text_unknown;
  323.                     }
  324.  
  325.                     new AlertDialog.Builder(mContext)
  326.                         .setTitle(com.android.internal.R.string.VideoView_error_title)
  327.                         .setMessage(messageId)
  328.                         .setPositiveButton(com.android.internal.R.string.VideoView_error_button,
  329.                             new DialogInterface.OnClickListener() {
  330.                                  public void onClick(DialogInterface dialog, int whichButton) {
  331.                                       /* If we get here, there is no onError listener, so
  332.                                            * at least inform them that the video is over.
  333.                                          */
  334.                                       if (mOnCompletionListener != null) {
  335.                                             mOnCompletionListener.onCompletion(mMediaPlayer);
  336.                                       }
  337.                               }
  338.                               })
  339.                         .setCancelable(false)
  340.                         .show();
  341.                 }
  342.                 return true;
  343.         };
  344.  
  345.     private MediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener =
  346.         new MediaPlayer.OnBufferingUpdateListener() {
  347.             public void onBufferingUpdate(MediaPlayer mp, int percent) {
  348.                 mCurrentBufferPercentage = percent;
  349.         };
  350.  
  351.     /**
  352.  * Register a callback to be invoked when the media file
  353.  * is loaded and ready to go.
  354.  
  355.  * @param l The callback that will be run
  356.  */
  357.     public void setOnPreparedListener(MediaPlayer.OnPreparedListener l)
  358.     {
  359.         mOnPreparedListener = l;
  360.     }
  361.  
  362.     /**
  363.  * Register a callback to be invoked when the end of a media file
  364.  * has been reached during playback.
  365.  
  366.  * @param l The callback that will be run
  367.  */
  368.     public void setOnCompletionListener(OnCompletionListener l)
  369.     {
  370.         mOnCompletionListener = l;
  371.     }
  372.  
  373.     /**
  374.  * Register a callback to be invoked when an error occurs
  375.  * during playback or setup.  If no listener is specified,
  376.  * or if the listener returned false, VideoView will inform
  377.  * the user of any errors.
  378.  
  379.  * @param l The callback that will be run
  380.  */
  381.     public void setOnErrorListener(OnErrorListener l)
  382.     {
  383.         mOnErrorListener = l;
  384.     }
  385.  
  386.     SurfaceHolder.Callback mSHCallback = new SurfaceHolder.Callback()
  387.     {
  388.         public void surfaceChanged(SurfaceHolder holder, int format,
  389.                                      int w, int h)
  390.         {
  391.             mSurfaceWidth = w;
  392.             mSurfaceHeight = h;
  393.             boolean isValidState =  (mTargetState == STATE_PLAYING);
  394.             boolean hasValidSize = (mVideoWidth == w && mVideoHeight == h);
  395.             if (mMediaPlayer != null && isValidState && hasValidSize) {
  396.                 if (mSeekWhenPrepared != 0) {
  397.                     seekTo(mSeekWhenPrepared);
  398.                 }
  399.                 start();
  400.                     if (mMediaController != null) {
  401.                         mMediaController.show();
  402.                     }
  403.             } }
  404.  
  405.             public void surfaceCreated(SurfaceHolder holder)
  406.             {
  407.                 mSurfaceHolder = holder;
  408.                 openVideo();
  409.         }
  410.  
  411.             public void surfaceDestroyed(SurfaceHolder holder)
  412.             {
  413.                 // after we return from this we can't use the surface any more
  414.                 mSurfaceHolder = null;
  415.                 if (mMediaController != null) mMediaController.hide();
  416.                 release(true);
  417.             }
  418.     };
  419.  
  420.     /*
  421.  * release the media player in any state
  422.  */
  423.     private void release(boolean cleartargetstate) {
  424.         if (mMediaPlayer != null) {
  425.             mMediaPlayer.reset();
  426.             mMediaPlayer.release();
  427.             mMediaPlayer = null;
  428.             mCurrentState = STATE_IDLE;
  429.             if (cleartargetstate) {
  430.                 mTargetState  = STATE_IDLE;
  431.             }
  432.         }
  433.     }
  434.  
  435.     @Override
  436.     public boolean onTouchEvent(MotionEvent ev)
  437.     {
  438.         if (isInPlaybackState() && mMediaController != null) {
  439.             toggleMediaControlsVisiblity();
  440.         }
  441.         return false;
  442.     }
  443.  
  444.     @Override
  445.     public boolean onTrackballEvent(MotionEvent ev)
  446.     {
  447.         if (isInPlaybackState() && mMediaController != null) {
  448.             toggleMediaControlsVisiblity();
  449.         }
  450.         return false;
  451.     }
  452.  
  453.     @Override
  454.     public boolean onKeyDown(int keyCode, KeyEvent event)
  455.     {
  456.         boolean isKeyCodeSupported = keyCode != KeyEvent.KEYCODE_BACK &&
  457.                                         keyCode != KeyEvent.KEYCODE_VOLUME_UP &&
  458.                                         keyCode != KeyEvent.KEYCODE_VOLUME_DOWN &&
  459.                                         keyCode != KeyEvent.KEYCODE_MENU &&
  460.                                         keyCode != KeyEvent.KEYCODE_CALL &&
  461.                                         keyCode != KeyEvent.KEYCODE_ENDCALL;
  462.         if (isInPlaybackState() && isKeyCodeSupported && mMediaController != null) {
  463.             if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK ||
  464.                     keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
  465.                 if (mMediaPlayer.isPlaying()) {
  466.                     pause();
  467.                     mMediaController.show();
  468.                     } else {
  469.                     start();
  470.                     mMediaController.hide();
  471.                 }
  472.                 return true;
  473.             } else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP
  474.                     && mMediaPlayer.isPlaying()) {
  475.                 pause();
  476.                     mMediaController.show();
  477.             } else {
  478.                 toggleMediaControlsVisiblity();
  479.             }
  480.         }
  481.  
  482.         return super.onKeyDown(keyCode, event);
  483.     }
  484.  
  485.     private void toggleMediaControlsVisiblity() {
  486.         if (mMediaController.isShowing()) {
  487.             mMediaController.hide();
  488.         } else {
  489.             mMediaController.show();
  490.     } }
  491.  
  492.     public void start() {
  493.         if (isInPlaybackState()) {
  494.             mMediaPlayer.start();
  495.             mCurrentState = STATE_PLAYING;
  496.         }
  497.         mTargetState = STATE_PLAYING;
  498.     }
  499.  
  500.     public void pause() {
  501.         if (isInPlaybackState()) {
  502.             if (mMediaPlayer.isPlaying()) {
  503.                 mMediaPlayer.pause();
  504.                 mCurrentState = STATE_PAUSED;
  505.             }
  506.         }
  507.         mTargetState = STATE_PAUSED;
  508.     }
  509.  
  510.     // cache duration as mDuration for faster access
  511.     public int getDuration() {
  512.         if (isInPlaybackState()) {
  513.             if (mDuration > 0) {
  514.                 return mDuration;
  515.             }
  516.             mDuration = mMediaPlayer.getDuration();
  517.             return mDuration;
  518.         }
  519.         mDuration = -1;
  520.         return mDuration;
  521.     }
  522.  
  523.     public int getCurrentPosition() {
  524.         if (isInPlaybackState()) {
  525.         return mMediaPlayer.getCurrentPosition();
  526.         }
  527.         return 0;
  528.     }
  529.  
  530.     public void seekTo(int msec) {
  531.         if (isInPlaybackState()) {
  532.             mMediaPlayer.seekTo(msec);
  533.             mSeekWhenPrepared = 0;
  534.         } else {
  535.             mSeekWhenPrepared = msec;
  536.         }
  537.     }
  538.  
  539.     public boolean isPlaying() {
  540.         return isInPlaybackState() && mMediaPlayer.isPlaying();
  541.     }
  542.  
  543.     public int getBufferPercentage() {
  544.         if (mMediaPlayer != null) {
  545.             return mCurrentBufferPercentage;
  546.         }
  547.         return 0;
  548.     }
  549.  
  550.     private boolean isInPlaybackState() {
  551.         return (mMediaPlayer != null &&
  552.                 mCurrentState != STATE_ERROR &&
  553.                 mCurrentState != STATE_IDLE &&
  554.                 mCurrentState != STATE_PREPARING);
  555.     }
  556.  
  557.     public boolean canPause() {
  558.         return mCanPause;
  559.     }
  560.  
  561.     public boolean canSeekBackward() {
  562.         return mCanSeekBack;
  563.     }
  564.  
  565.     public boolean canSeekForward() {
  566.         return mCanSeekForward;
  567.     }
  568. }

讀懂這段程式碼,你會學到什麼?

VideoView 的設計藏著幾個值得細細品味的思路。首先,它用一組 STATE_* 常數把播放器的生命週期切分得清清楚楚——從 IDLE、PREPARING、PREPARED,一路到 PLAYING、PAUSED 與 PLAYBACK_COMPLETED。更巧妙的是,它同時維護了 mCurrentState(目前狀態)與 mTargetState(呼叫者想抵達的目標狀態),這種「現況與意圖分離」的設計,讓播放流程在各種非同步情境下都能保持井然有序。

其次,VideoView 繼承自 SurfaceView,並實作 MediaPlayerControl 介面。這意味著它把底層的畫面繪製交給 Surface,把播放控制交給 MediaPlayer,自己則扮演協調者的角色,透過一連串 Listener(準備完成、播放結束、錯誤、緩衝更新)串起整個播放體驗。

如果你仔細觀察 onMeasure 方法,還會發現它花了大把力氣在維持影片的長寬比例——當容器與影片比例不一致時,程式會主動縮放寬或高,確保畫面不會被拉伸變形。這些看似瑣碎的細節,正是打造一個「好播放器」的關鍵。

把這些設計消化透徹之後,再回頭看你自己的專案,就會明白為什麼客製化播放器往往建議直接繼承 VideoView 重寫——因为你已经站在巨人的肩膀上了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved