[iOS]Learning iOS,the Beginner’s Guide

开篇扯淡是惯例(其实这个博客是一个AI维护的你信么?), 又是一个多月没写东西,折腾各种东西,写不出来什么有营养的,也就放着了。本文虽然谋划已久,但一直都没动手写,在iOS这块,虽然坚持2年了,但还是担心会误导别人,不敢写这种类型的东西。最近要集中点别的技能点,iOS会放缓,先把这篇放出来吧,供大家参考,为了方便搜索,给本文起个中文标题:学习iOS,从菜鸟到小强。

啰嗦版

先说下我开始折腾iOS这块之前的知识背景,“碰过“C/C++,“看过”Java,“碰过”Android,当然这些都是比较保守的说法,不过也基本可以认为就是大菜的水平,认为什么都不会也可以,但是有过几个较完整的项目经验(比如我写过俩android小破项目)。

开始的时候,我的路线是在基本什么都不会的情况下,以一个不大不小的项目驱动,快速产出,这里最重要的一点就是学会如何在什么也不懂的情况下搜索到你想要实现的那些东西的代码,或者是相似的代码,然后就是如何照猫画虎把别人写的几块东西改改,用胶水代码沾一起,形成一些“能用的”东西,快速的产出有助增强信心,有效避免半途而废,同时一旦开始写代码了,所学到的知识就自然而然记牢了,不会发生看一遍忘一遍这种情况。

当然如果我这么建议别人,一些大神就会喷了(比如这个:【豆瓣校招-面试官发声】近期面试感受),说这种搜索式学习方式会打下不好的基础,因为你接触到的都是二手,三手以上的信息(这里定义一下,一手信息为文档,质量最高,二手信息可以认为是StackOverflow这类,也很不错了,三手就是这个链接里所表达的那个“二手”),对这些信息就要比较谨慎,有些东西可能太过技巧,不是一种好的解决方法,另外就是难免有错误,而且这个错误可能会被你继承很久,因为是新手,你会倾向于相信所有“好使“的代码。

这些弊端确实存在,不过恭喜你学习的是iOS,只要将你寻找问题解决方法的搜索范围限定在官方文档,WWDC视频,StackOverFlow上就可以了,这些都是一手二手的信息,而且一手信息占了绝大多数,基本可以保证信息的优质性,同时也完全足够解决问题了。当然多看看其他人写的东西也是有好处的,学习不要死板,这里的限制只是在避免上一段提到的问题,搜索式学习虽有弊端,但还是要比啃一手资料快很多,对于优先实现功能是很有必要的,关键就是要和一手资料结合着用,如何掌握之间的度就靠自己来衡量吧。

这里不得不提一下文档,苹果的文档是我见过的最好的文档(MSDN的也很牛,但是我没做过windows那方面的开发,所以没什么了解),这里不仅仅有对类、方法的详细说明,还有非常多的XXX Programming Guide,这种导引性的文章,从一定程度上来说,有了文档我们甚至已经不再需要StackOverflow,其实在StackOverflow搜索问题的时候,很多回答就是一个指向官方文档的链接。同时,文档中包含了大量Sample Project,这些Sample都很有针对性,清晰地展示了各种实现方法,同时Sample的代码都是高手写的,多看看Sample Project对编程能力的提升也有很高价值。额外说一句,如果你认为英文的文档太难读懂,那就只能查着字典啃,如果还是不行,你去学英文吧,要么就别搞这一行,文档的英文要求已经很低了。

WWDC视频,也是快速解决问题的必备,在接触比较陌生的一块比如音频处理的时候,先看一看WWDC相关视频,就能大概了解一下相应的实现方法,对这一块有一个比较清晰全面的认识,这时候再借助文档的XXX Programming Guide,基本就可以非常深入地学习到你需要的知识。

前面一直都没提到,书–这一重要学习工具,在我看来买书基本上完全没有必要,有文档在看什么书啊,那种讲语言,讲SDK的书没有必要买,根本比不上文档,时效性也差。当然还是有些好书值得买来看看,比如Apress的iPhone Cool Projects,和More iPhone Cool Projects,虽然比较旧,但是里面那几个项目还是很有参考价值的。

面对iOS这一快速更新的系统,新手面临的一个常见问题就是该从哪个SDK版本入手。SDK版本对于新手老手都是个问题,要想要新功能,就要高版本的SDK,要想兼容旧设备,就要放弃新功能,或者自己实现新功能,选择低版本的SDK。这里根据我的经验,如果你是一个纯新手,不着急开发产品,就从最新的SDK版本入手,因为等你出师了,当时入门的SDK版本已经是旧版了,兼容旧设备的问题就不存在了。如果要快速出产品,那就只能从低版本SDK入手了,当然有些新API就用不了了,作为新手一个能用新API很方便实现的功能却要为了兼容用很复杂的方法实现还是有些不爽的。选择SDK要注意的一点就是,在iOS 4.0以后,引入了Auto Reference Counting(ARC)这一技术,个人感觉使用ARC虽然方便了内存管理,但是对于新手来说缺少了手动管理内存的历练,这里欠下的债,将来一定要还的。所以还是推荐先看文档学习一下内存管理方法,并在此后一段时间内关掉ARC实践手动管理内存,记得用Instruments测一下内存泄露,等到基本掌握了手动内存管理,就可以开ARC了。当然,我在折腾内存管理的时候还没有ARC,所以这部分建议可能存在一点主观因素,虽然不一定是最好的路线,但总不是错误的路线。

工欲善其事,必先利其器,XCode的熟练使用,对于提高效率至关重要,关于怎么使用XCode请搜索我以前的文章,关键词“XCode”,懒,不发链接了。

以上都是以项目驱动为前提,至于这个项目,规模不要太大也不要太小,有一定升级空间,最好是没有时间限制的长期项目,这样就有充足的时间来深入研究某一部分知识点,第一个版本功能实现了,但是代码不够漂亮,效率不够高,推到重来是一个非常好的选择,反复迭代几次,大有益处。

我的入门项目就是HIT Mobile(在关于页面里面有链接,现在也基本停止维护了,实际上也没什么人用)。这个项目我和一个队友分别负责不同的功能,持续时间将近一年(当然有上课考试等因素干扰),为了代码整洁或者效率等问题,每个功能都反复写了2、3遍,这几遍推到重来对能力的提升是非常大的。

虽然做单一的项目可能接触的不够全面,但如果你是一个渴求知识的人,必然会在做主线任务的同时,走一些分支路线,接触到其他方面的知识,另外一点就是,iOS虽然是个手机上的OS,但不要忘了这是基于Mac OS做出来的系统,Mac OS这么多年历史岂是我等弱菜一两年就能接触全面的,专注一两个点深入学习下去也是一种很好的选择。

我们还没有说github,github的重要性其实根本不必多提,开源的framework,控件什么的基本都在上面。其他网站比如,CocoaControls,有很多开源的UI控件,建议订阅个RSS。此外cocoaneticsCocoa is my girlfriend等博客类型的网站也经常会发布一些非常优秀的文章。

总之想“精通”iOS,绝对不是短时间可以做到的,贵在坚持不断学习。

精简版:

  • 项目驱动
  • 寻找帮助
    • 文档
    • WWDC视频
    • StackOverflow
    • Google
  • 书,不是很必要
  • 学习XCode使用
  • 手动管理内存,熟练以后再开启ARC
  • 找代码,开源库:github, CocoaControls
  • 好文章:
    • cocoanetics
    • Cocoa is my girlfriend
    • 等等

补充:

一些非常好的资源:

  • RAYWENDERLICH   |  简单高质量的Tutorial,涵盖iOS Mac Cocos2D Unity等内容

 

–以上–

Android Dev:VideoView源代码浅析及拓展应用

做Android开发不免要涉及到编写媒体播放器,对于初学者来说用MediaPlayer实现一个具有基本功能的播放器(有进度条,可以通过进度条上的按钮进行控制)还是有一定难度的,幸好Android还提供了一个VideoView类,借用该类可以快速实现简单的媒体播放功能,其源代码如下(单击右边那个箭头展开):

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

继续阅读Android Dev:VideoView源代码浅析及拓展应用