Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2006 The Android Open Source Project
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package android.widget;
 
 
Displays a video file. The VideoView class can load images from various sources (such as resources or content providers), takes care of computing its measurement from the video so that it can be used in any layout manager, and provides various display options such as scaling and tinting.
 
 public class VideoView extends SurfaceView implements MediaPlayerControl {
     private String TAG = "VideoView";
     // settable by the client
     private Uri         mUri;
     private int         mDuration;
 
     // all possible internal states
     private static final int STATE_ERROR              = -1;
     private static final int STATE_IDLE               = 0;
     private static final int STATE_PREPARING          = 1;
     private static final int STATE_PREPARED           = 2;
     private static final int STATE_PLAYING            = 3;
     private static final int STATE_PAUSED             = 4;
     private static final int STATE_PLAYBACK_COMPLETED = 5;
 
     // mCurrentState is a VideoView object's current state.
     // mTargetState is the state that a method caller intends to reach.
     // For instance, regardless the VideoView object's current state,
     // calling pause() intends to bring the object to a target state
     // of STATE_PAUSED.
     private int mCurrentState = ;
     private int mTargetState  = ;
 
     // All the stuff we need for playing and showing a video
     private SurfaceHolder mSurfaceHolder = null;
     private MediaPlayer mMediaPlayer = null;
     private int         mVideoWidth;
     private int         mVideoHeight;
     private int         mSurfaceWidth;
     private int         mSurfaceHeight;
     private MediaController mMediaController;
     private int         mCurrentBufferPercentage;
     private OnErrorListener mOnErrorListener;
     private int         mSeekWhenPrepared;  // recording the seek position while preparing
     private boolean     mCanPause;
     private boolean     mCanSeekBack;
     private boolean     mCanSeekForward;
 
     public VideoView(Context context) {
         super(context);
         initVideoView();
     }
     
     public VideoView(Context contextAttributeSet attrs) {
         this(contextattrs, 0);
         initVideoView();
     }
     
     public VideoView(Context contextAttributeSet attrsint defStyle) {
        super(contextattrsdefStyle);
        initVideoView();
    }
    @Override
    protected void onMeasure(int widthMeasureSpecint heightMeasureSpec) {
        //Log.i("@@@@", "onMeasure");
        int width = getDefaultSize(widthMeasureSpec);
        int height = getDefaultSize(heightMeasureSpec);
        if ( > 0 &&  > 0) {
            if (  * height  > width *  ) {
                //Log.i("@@@", "image too tall, correcting");
                height = width *  / ;
            } else if (  * height  < width *  ) {
                //Log.i("@@@", "image too wide, correcting");
                width = height *  / ;
            } else {
                //Log.i("@@@", "aspect ratio is correct: " +
                        //width+"/"+height+"="+
                        //mVideoWidth+"/"+mVideoHeight);
            }
        }
        //Log.i("@@@@@@@@@@", "setting size: " + width + 'x' + height);
        setMeasuredDimension(widthheight);
    }
    
    public int resolveAdjustedSize(int desiredSizeint measureSpec) {
        int result = desiredSize;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize =  MeasureSpec.getSize(measureSpec);
        switch (specMode) {
            case .:
                /* Parent says we can be as big as we want. Just don't be larger
                 * than max size imposed on ourselves.
                 */
                result = desiredSize;
                break;
            case .:
                /* Parent says we can be as big as we want, up to specSize. 
                 * Don't be larger than specSize, and don't be larger than 
                 * the max size imposed on ourselves.
                 */
                result = Math.min(desiredSizespecSize);
                break;
                
            case .:
                // No choice. Do what we are told.
                result = specSize;
                break;
        }
        return result;
    
    private void initVideoView() {
         = 0;
         = 0;
        setFocusable(true);
        setFocusableInTouchMode(true);
        requestFocus();
         = ;
          = ;
    }
    public void setVideoPath(String path) {
        setVideoURI(Uri.parse(path));
    }
    public void setVideoURI(Uri uri) {
         = uri;
         = 0;
        openVideo();
        requestLayout();
        invalidate();
    }
    
    public void stopPlayback() {
        if ( != null) {
            .stop();
            .release();
             = null;
             = ;
              = ;
        }
    }
    private void openVideo() {
        if ( == null ||  == null) {
            // not ready for playback just yet, will try again later
            return;
        }
        // Tell the music playback service to pause 
        // TODO: these constants need to be published somewhere in the framework.
        Intent i = new Intent("com.android.music.musicservicecommand");
        i.putExtra("command""pause");
        .sendBroadcast(i);
        // we shouldn't clear the target state, because somebody might have
        // called start() previously
        release(false);
        try {
             = new MediaPlayer();
             = -1;
             = 0;
            .setDataSource();
            .setDisplay();
            .setScreenOnWhilePlaying(true);
            .prepareAsync();
            // we don't set the target state here either, but preserve the
            // target state that was there before.
             = ;
            attachMediaController();
        } catch (IOException ex) {
            Log.w("Unable to open content: " + ex);
             = ;
             = ;
            return;
        } catch (IllegalArgumentException ex) {
            Log.w("Unable to open content: " + ex);
             = ;
             = ;
            return;
        }
    }
    
    public void setMediaController(MediaController controller) {
        if ( != null) {
            .hide();
        }
         = controller;
        attachMediaController();
    }
    private void attachMediaController() {
        if ( != null &&  != null) {
            .setMediaPlayer(this);
            View anchorView = this.getParent() instanceof View ?
                    (View)this.getParent() : this;
            .setAnchorView(anchorView);
        }
    }
    
        new MediaPlayer.OnVideoSizeChangedListener() {
            public void onVideoSizeChanged(MediaPlayer mpint widthint height) {
                 = mp.getVideoWidth();
                 = mp.getVideoHeight();
                if ( != 0 &&  != 0) {
                    getHolder().setFixedSize();
                }
            }
    };
    
        public void onPrepared(MediaPlayer mp) {
             = ;
            // Get the capabilities of the player for this stream
            Metadata data = mp.getMetadata(.,
                                      .);
            if (data != null) {
                 = !data.has(.)
                        || data.getBoolean(.);
                 = !data.has(.)
                        || data.getBoolean(.);
                 = !data.has(.)
                        || data.getBoolean(.);
            } else {
                 =  =  = true;
            }
            if ( != null) {
                .onPrepared();
            }
            if ( != null) {
                .setEnabled(true);
            }
             = mp.getVideoWidth();
             = mp.getVideoHeight();
            int seekToPosition = ;  // mSeekWhenPrepared may be changed after seekTo() call
            if (seekToPosition != 0) {
                seekTo(seekToPosition);
            }
            if ( != 0 &&  != 0) {
                //Log.i("@@@@", "video size: " + mVideoWidth +"/"+ mVideoHeight);
                getHolder().setFixedSize();
                if ( ==  &&  == ) {
                    // We didn't actually change the size (it was already at the size
                    // we need), so we won't get a "surface changed" callback, so
                    // start the video here instead of in the callback.
                    if ( == ) {
                        start();
                        if ( != null) {
                            .show();
                        }
                    } else if (!isPlaying() &&
                               (seekToPosition != 0 || getCurrentPosition() > 0)) {
                       if ( != null) {
                           // Show the media controls when we're paused into a video and make 'em stick.
                           .show(0);
                       }
                   }
                }
            } else {
                // We don't know the video size yet, but should start anyway.
                // The video size might be reported to us later.
                if ( == ) {
                    start();
                }
            }
        }
    };
        new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mp) {
             = ;
             = ;
            if ( != null) {
                .hide();
            }
            if ( != null) {
                .onCompletion();
            }
        }
    };
        new MediaPlayer.OnErrorListener() {
        public boolean onError(MediaPlayer mpint framework_errint impl_err) {
            Log.d("Error: " + framework_err + "," + impl_err);
             = ;
             = ;
            if ( != null) {
                .hide();
            }
            /* If an error handler has been supplied, use it and finish. */
            if ( != null) {
                if (.onError(framework_errimpl_err)) {
                    return true;
                }
            }
            /* Otherwise, pop up an error dialog so the user knows that
             * something bad has happened. Only try and pop up the dialog
             * if we're attached to a window. When we're going away and no
             * longer have a window, don't bother showing the user an error.
             */
            if (getWindowToken() != null) {
                Resources r = .getResources();
                int messageId;
                if (framework_err == .) {
                    messageId = .....;
                } else {
                    messageId = .....;
                }
                new AlertDialog.Builder()
                        .setTitle(.....)
                        .setMessage(messageId)
                        .setPositiveButton(.....,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialogint whichButton) {
                                        /* If we get here, there is no onError listener, so
                                         * at least inform them that the video is over.
                                         */
                                        if ( != null) {
                                            .onCompletion();
                                        }
                                    }
                                })
                        .setCancelable(false)
                        .show();
            }
            return true;
        }
    };
        new MediaPlayer.OnBufferingUpdateListener() {
        public void onBufferingUpdate(MediaPlayer mpint percent) {
             = percent;
        }
    };

    
Register a callback to be invoked when the media file is loaded and ready to go.

Parameters:
l The callback that will be run
    {
         = l;
    }

    
Register a callback to be invoked when the end of a media file has been reached during playback.

Parameters:
l The callback that will be run
    {
         = l;
    }

    
Register a callback to be invoked when an error occurs during playback or setup. If no listener is specified, or if the listener returned false, VideoView will inform the user of any errors.

Parameters:
l The callback that will be run
    public void setOnErrorListener(OnErrorListener l)
    {
         = l;
    }
    {
        public void surfaceChanged(SurfaceHolder holderint format,
                                    int wint h)
        {
             = w;
             = h;
            boolean isValidState =  ( == );
            boolean hasValidSize = ( == w &&  == h);
            if ( != null && isValidState && hasValidSize) {
                if ( != 0) {
                    seekTo();
                }
                start();
                if ( != null) {
                    .show();
                }
            }
        }
        public void surfaceCreated(SurfaceHolder holder)
        {
             = holder;
            openVideo();
        }
        public void surfaceDestroyed(SurfaceHolder holder)
        {
            // after we return from this we can't use the surface any more
             = null;
            if ( != null.hide();
            release(true);
        }
    };
    /*
     * release the media player in any state
     */
    private void release(boolean cleartargetstate) {
        if ( != null) {
            .reset();
            .release();
             = null;
             = ;
            if (cleartargetstate) {
                  = ;
            }
        }
    }
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (isInPlaybackState() &&  != null) {
            toggleMediaControlsVisiblity();
        }
        return false;
    }
    
    @Override
    public boolean onTrackballEvent(MotionEvent ev) {
        if (isInPlaybackState() &&  != null) {
            toggleMediaControlsVisiblity();
        }
        return false;
    }
    
    @Override
    public boolean onKeyDown(int keyCodeKeyEvent event)
    {
        boolean isKeyCodeSupported = keyCode != . &&
                                     keyCode != . &&
                                     keyCode != . &&
                                     keyCode != . &&
                                     keyCode != . &&
                                     keyCode != .;
        if (isInPlaybackState() && isKeyCodeSupported &&  != null) {
            if (keyCode == . ||
                    keyCode == .) {
                if (.isPlaying()) {
                    pause();
                    .show();
                } else {
                    start();
                    .hide();
                }
                return true;
            } else if (keyCode == . 
                    && .isPlaying()) {
                pause();
                .show();
            } else {
                toggleMediaControlsVisiblity();
            }
        }
        return super.onKeyDown(keyCodeevent);
    }
    private void toggleMediaControlsVisiblity() {
        if (.isShowing()) { 
            .hide();
        } else {
            .show();
        }
    }
    
    public void start() {
        if (isInPlaybackState()) {
            .start();
             = ;
        }
         = ;
    }
    
    public void pause() {
        if (isInPlaybackState()) {
            if (.isPlaying()) {
                .pause();
                 = ;
            }
        }
         = ;
    }
    
    // cache duration as mDuration for faster access
    public int getDuration() {
        if (isInPlaybackState()) {
            if ( > 0) {
                return ;
            }
             = .getDuration();
            return ;
        }
         = -1;
        return ;
    }
    
    public int getCurrentPosition() {
        if (isInPlaybackState()) {
            return .getCurrentPosition();
        }
        return 0;
    }
    
    public void seekTo(int msec) {
        if (isInPlaybackState()) {
            .seekTo(msec);
             = 0;
        } else {
             = msec;
        }
    }    
            
    public boolean isPlaying() {
        return isInPlaybackState() && .isPlaying();
    }
    
    public int getBufferPercentage() {
        if ( != null) {
            return ;
        }
        return 0;
    }
    private boolean isInPlaybackState() {
        return ( != null &&
                 !=  &&
                 !=  &&
                 != );
    }
    public boolean canPause() {
        return ;
    }
    public boolean canSeekBackward() {
        return ;
    }
    public boolean canSeekForward() {
        return ;
    }
New to GrepCode? Check out our FAQ X