VideoView 視頻播放 示例



介紹
       
       
       
               
實現的功能:
  • 可播放本地視頻或網絡視頻,可控制播放或暫停
  • 最小化時保存播放位置及播放狀態,resume時恢復所有狀態;
  • 橫豎屏切換時保持切換前的位置及狀態
  • 在屏幕上豎直滑動可調節屏幕亮度和音量
  • 可改變視頻顯示樣式(有bug)
  • 可獲取視頻縮略圖及視頻大小

Activity
        
        
        
                
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends Activity implements OnCompletionListener, OnErrorListener, OnPreparedListener, OnTouchListener, OnClickListener,
        OnGestureListener {
    private Button btn_switch;
    private Button btn_start;
    private Button btn_fullscreen;
    private VideoView mVideoView;
    //在 VidioView 外層套一個容器,以在切換屏幕方向的時候對 rl_vv 進行拉伸,而內部的 mVideoView 會依據視頻尺寸重新計算寬高。
    //若是直接具體指定了view的寬高,則視頻會被拉伸。
    private RelativeLayout rl_vv;
    private ProgressBar progressBar//加載進度條
    private int positionWhenPause = 0;//標記當視頻暫停時的播放位置
    private boolean isPlayingWhenPause = false;//標記最小化或橫豎屏時是否正在播放
    private GestureDetector mGestureDetector;//手勢識別器,用戶控制屏幕亮度和音量
    private Uri mVideoUri;
    public static final String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/b.rmvb";//本地路徑
    public static final String url = "http://7xt0mj.com1.z0.glb.clouddn.com/lianaidaren.v.640.480.mp4";//網絡路徑
    public static final String url2 = "http://7xt0mj.com1.z0.glb.clouddn.com/xia.v.1280.720.f4v";
    public static final String url3 = "http://112.253.22.157/17/z/z/y/u/zzyuasjwufnqerzvyxgkuigrkcatxr/hc.yinyuetai.com   /D046015255134077DDB3ACA0D7E68D45.flv";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        rl_vv = (RelativeLayout) findViewById(R.id.rl_vv);
        mVideoView = (VideoView) findViewById(R.id.mVideoView);
        btn_switch = (Button) findViewById(R.id.btn_switch);
        btn_start = (Button) findViewById(R.id.btn_start);
        btn_fullscreen = (Button) findViewById(R.id.btn_fullscreen);
        //設置顯示控制條
        mVideoView.setMediaController(new MediaController(this));
        mVideoUri = Uri.parse(filePath);
        mVideoView.setVideoURI(mVideoUri);//mVideoView.setVideoPath(url);//這兩個方法都可以用來播放網絡視頻或本地視頻
        btn_switch.setOnClickListener(this);
        btn_start.setOnClickListener(this);
        btn_fullscreen.setOnClickListener(this);
        mVideoView.setOnCompletionListener(this);
        mVideoView.setOnErrorListener(this);
        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnTouchListener(this);
        mVideoView.setOnClickListener(this);
        mGestureDetector = new GestureDetector(thisthis);
    }
    @Override
    protected void onResume() {
        super.onResume();
        //如果有保存位置,則跳轉到暫停時所保存的那個位置
        if (positionWhenPause > 0) {
            mVideoView.seekTo(positionWhenPause);
            //如果暫停前正在播放,則繼續播放,並將播放位置置為0
            if (isPlayingWhenPause) {
                mVideoView.start();
                mVideoView.requestFocus();
                positionWhenPause = 0;
            }
        }
    }
    @Override
    protected void onPause() {
        //如果當前頁面暫定,則保存當前播放位置,並記錄之前mVideoView是否正在播放
        isPlayingWhenPause = mVideoView.isPlaying();
        positionWhenPause = mVideoView.getCurrentPosition();
        //停止回放視頻文件,先獲取再stopPlayback()
        mVideoView.stopPlayback();
        super.onPause();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mVideoViewmVideoView = null;
    }
    @Override
    //橫豎屏切換時更改mVideoView的大小
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mVideoView == null) {
            return;
        }
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {//橫屏
            VideoUtils.setActivityFullScreenMode(this);//設置為全屏模式
            getWindow().getDecorView().invalidate();
            //rl_vv.getLayoutParams().width = VideoUtils.getScreenWidth(this);
            rl_vv.getLayoutParams().height = VideoUtils.getScreenHeight(this);
        } else {//豎屏
            VideoUtils.setActivityWindowScreenMode(this);
            rl_vv.getLayoutParams().width = VideoUtils.getScreenWidth(this);
            //rl_vv.getLayoutParams().height = VideoUtils.dp2px(this, 400);
        }
    }
    //***************************************************************************************************************************
    @Override
    public void onPrepared(MediaPlayer mp) {
        try {
            long timeLong = Long.valueOf(VideoUtils.getVideoLength(mVideoUri.toString()));
            Toast.makeText(this"准備好了,時長為 " + VideoUtils.long2Time(timeLong), Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
        }
        //如果文件加載成功,隱藏加載進度條
        progressBar.setVisibility(View.GONE);
    }
    @Override
    public void onCompletion(MediaPlayer mp) {
    }
    @Override
    //視頻播放發生錯誤時回調。如果未指定回調, 或回調函數返回false,mVideoView 會通知用戶發生了錯誤。
    public boolean onError(MediaPlayer mp, int what, int extra) {
        switch (what) {
        case MediaPlayer.MEDIA_ERROR_UNKNOWN:
            Log.e("text""發生未知錯誤");
            break;
        case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
            Log.e("text""媒體服務器死機");
            break;
        default:
            Log.e("text""onError+" + what);
            break;
        }
        switch (extra) {
        case MediaPlayer.MEDIA_ERROR_IO:
            Log.e("text""文件或網絡相關的IO操作錯誤");
            break;
        case MediaPlayer.MEDIA_ERROR_MALFORMED:
            Log.e("text""比特流編碼標准或文件不符合相關規范");
            break;
        case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
            Log.e("text""操作超時");
            break;
        case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
            Log.e("text""比特流編碼標准或文件符合相關規范,但媒體框架不支持該功能");
            break;
        default:
            Log.e("text""onError+" + extra);
            break;
        }
        return true;//經常會碰到視頻編碼格式不支持的情況,若不想彈出提示框就返回true
    }
    //************************************************************************************************************************************
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return mGestureDetector.onTouchEvent(event);//把Touch事件傳遞給手勢識別器,這一步非常重要!
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_start:
            if (mVideoView.isPlaying()) {
                mVideoView.pause();
            } else {
                mVideoView.start();//啟動視頻播放
                mVideoView.requestFocus();//獲取焦點
            }
            break;
        case R.id.btn_switch:
            //橫豎屏切換
            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
            //            btn_switch.setVisibility(View.INVISIBLE);
            break;
        case R.id.btn_fullscreen:
            VideoUtils.setVideoViewLayoutParams(thismVideoView, VideoUtils.FULL_SCREEN);
            break;
        }
    }
    //************************************************************************************************************************************
    @Override
    //e1代表觸摸時的事件,是不變的,e2代表滑動過程中的事件,是時刻變化的
    //distance是當前event2與上次回調時的event2之間的距離,代表上次回調之后到這次回調之前移動的距離
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        float FLING_MIN_BRIGHTNESS = 1.0f * VideoUtils.dp2px(MainActivity.this, 1f);//調節亮度時的敏感度,
        float FLING_MIN_VOICE = 1.0f * VideoUtils.dp2px(MainActivity.this, 5f);//調節聲音時的敏感度
        float distance = Math.abs(distanceY);//豎直方向移動范圍
        //在屏幕左側滑動調節亮度,在屏幕右側滑動調節聲音
        if (e1.getX() < VideoUtils.getScreenWidth(this) / 2) {//左側
            if (distance > FLING_MIN_BRIGHTNESS) {//移動范圍滿足
                if (e1.getY() - e2.getY() > 0) {//上滑
                    VideoUtils.setScreenBrightness(this, 15);//亮度增加,第二參數的大小代表着敏感度
                } else {//下滑
                    VideoUtils.setScreenBrightness(this, -15);
                }
            }
        } else {//右側
            if (distance > FLING_MIN_VOICE) {//移動范圍滿足
                if (e1.getY() - e2.getY() > 0) {//上滑
                    //VideoUtils.setVoiceVolume(this, 1);//音量增加
                    VideoUtils.setVoiceVolumeAndShowNotification(thistrue);//系統自動控制音量增加減小級別
                } else {//下滑
                    //    VideoUtils.setVoiceVolume(this, -1);
                    VideoUtils.setVoiceVolumeAndShowNotification(thisfalse);
                }
            }
        }
        return true;
    }
    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return true;
    }
    @Override
    public void onLongPress(MotionEvent e) {
    }
    @Override
    public void onShowPress(MotionEvent e) {
    }
    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }
}

工具
        
        
        
                
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.provider.MediaStore.Video;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.VideoView;
public class VideoUtils {
    /** 
     * 根據手機的分辨率從 dp或 sp 的單位 轉成為 px
     */
    public static int dp2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    /** 
    * 根據手機的分辨率從 px 的單位轉成為 dp 或 sp
    */
    public static int px2dp(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    /**
    * 獲取屏幕高度
    */
    public static int getScreenHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }
    /**
     * 獲取屏幕寬度
     */
    public static int getScreenWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }
    /**
     * 設置Activity為全屏模式
     */
    public static void setActivityFullScreenMode(Activity context) {
        context.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
    /**
     * 設置Activity為窗口模式???
     */
    public static void setActivityWindowScreenMode(Activity context) {
        WindowManager.LayoutParams attrs = context.getWindow().getAttributes();
        attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
        context.getWindow().setAttributes(attrs);
        context.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
    }
    //********************************************************************************************************************
    public static final int FULL_SCREEN = 1;//全屏拉伸模式
    public static final int SCREEN_WINDOW = 2;//指定大小模式
    public static final int SCREEN_WINDOW_ADAPT = 3;//自適應寬高模式
    /**
     * 設置VideoView的全屏和窗口模式。<br>
     * 全屏拉伸模式 : {@link #FULL_SCREEN} <br>
     * 指定大小模式: {@link #SCREEN_WINDOWE}<br>
     * 自適應寬高模式 : {@link #SCREEN_WINDOW_ADAPT}
     * 這里有很多bug******************************************************************************************************************************************************
     */
    public static void setVideoViewLayoutParams(Activity context, VideoView mVideoView, int paramsType) {
        int width, height;
        switch (paramsType) {
        case FULL_SCREEN:
            setActivityFullScreenMode(context);
            RelativeLayout.LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            ((View) mVideoView.getParent()).setLayoutParams(layoutParams);//布局里我們給VideoView設置了一個父布局
            mVideoView.setLayoutParams(layoutParams);
            break;
        case SCREEN_WINDOW:
            width = getScreenWidth(context) * 2 / 3;
            height = VideoUtils.getScreenHeight(context) * 2 / 3;
            RelativeLayout.LayoutParams LayoutParams = new LayoutParams(width, height);
            LayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            mVideoView.setLayoutParams(LayoutParams);
            break;
        default://先獲取VideoView中資源的大小,然后分別和VideoView控件的大小作對比,當資源寬高大於控件時,縮小,否則放大。
            //和加載圖片一個樣,但是VideoView沒有scaleType塑性
            int videoWidth = mVideoView.getWidth();
            int videoHeight = mVideoView.getHeight();
            break;
        }
    }
    //********************************************************************************************************************
    /**
     * 獲取屏幕亮度模式,返回-1代表沒有獲取到
     * 自動調節:Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1
     * 手動調節:SCREEN_BRIGHTNESS_MODE_MANUAL=0
     */
    public static int getScreenBrightnessMode(Context context) {
        int screenMode = -1;
        try {
            screenMode = Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE);
        } catch (SettingNotFoundException e) {
            e.printStackTrace();
        }
        return screenMode;
    }
    /**
     * 設置屏幕亮度模式
     * 自動調節:Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1
     * 手動調節:SCREEN_BRIGHTNESS_MODE_MANUAL=0
     */
    public static void setScreenBrightnessMode(Context context, int value) {
        Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, value);
    }
    /**
     * 獲取屏幕亮度,獲取失敗返回-1
     */
    public static int getScreenBrightness(Context context) {
        int bright = -1;
        try {
            bright = Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (SettingNotFoundException e) {
            e.printStackTrace();
        }
        return bright;
    }
    /**
     * 增加或減小當前屏幕亮度,並在整個系統上生效
    */
    public static void setScreenBrightness(Activity context, float value) {
        //設置當前【activity】的屏幕亮度
        Window mWindow = context.getWindow();
        WindowManager.LayoutParams mParams = mWindow.getAttributes();//注意:它的值是從0到1,亮度從暗到全亮
        mParams.screenBrightness += value / 255.0F;
        if (mParams.screenBrightness > 1) {//設置大於1的值后,雖然獲取到的此參數的值被改了,但系統並不使用此值而是使用某一指定值設置亮度
            mParams.screenBrightness = 1;
        } else if (mParams.screenBrightness < 0.01) {
            mParams.screenBrightness = 0.01f;
        }
        mWindow.setAttributes(mParams);
        // 保存設置為【系統】屏幕亮度值。注意它的值是0-255
        int newValue = (int) (mParams.screenBrightness * 255.0F + value);// 或者= (int) (getScreenBrightness(context) + value);
        if (newValue > 255) newValue = 255;
        else if (newValue < 0) newValue = 0;
        Log.i("bqt""亮度=" + mParams.screenBrightness + ",亮度=" + newValue);
        Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, newValue);
    }
    //********************************************************************************************************************
    /**
     * 設置鈴聲模式
     * @param mode 聲音模式:AudioManager.RINGER_MODE_NORMAL;靜音模式:_SILENT;震動模式:_VIBRATE
     */
    public static void setRingerMode(Context context, int mode) {
        AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        mAudioManager.setRingerMode(mode);
    }
    /**
     * 增加或減小媒體音量
     */
    public static void setVoiceVolume(Context context, int value) {
        AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        // 注意:分為靜音(0),震動(0),1--7 共九個等級。從靜音調為1時,需要調大兩個等級;從1調為0時,手機將調整為“震動模式”
        int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        //尼瑪,我獲得的最大值是15
        int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int newVolume = currentVolume + value;
        if (newVolume > maxVolume) {
            newVolume = maxVolume;
        } else if (newVolume < 0) {
            newVolume = 0;
        }
        Log.i("bqt""音量=" + newVolume);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, 0);
    }
    /**
     * 增加或減小媒體音量,並且顯示系統音量控制提示條
     */
    public static void setVoiceVolumeAndShowNotification(Context context, boolean isAddVolume) {
        AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (isAddVolume) {
            //參數:聲音類型,調整音量的方向(只能是增加、減小、不變),可選的標志位(不知道有卵用)
            //音樂:AudioManager.STREAM_MUSIC;通話:_VOICE_CALL;系統:_SYSTEM;鈴聲:_RING;提示音:_NOTIFICATION;鬧鈴:_ALARM
            mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FX_FOCUS_NAVIGATION_UP);
        } else {
            mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FX_FOCUS_NAVIGATION_UP);
        }
        Log.i("bqt""音量=" + mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
    }
    //********************************************************************************************************************
    /**
     * 獲取視頻長度,獲取網絡視頻長度時異常!
     */
    public static String getVideoLength(String filePath) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(filePath);
        String length = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        return length;
    }
    /**
     * 毫秒值裝換為時分秒形式
     */
    @SuppressWarnings("deprecation")
    public static String long2Time(long timeLong) {
        Date date = new Date(timeLong);
        date.setHours(date.getHours() - 8); //沃日,我們這里比標准時長快了八個小時
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss ");
        return format.format(date);
    }
    /**
     * 獲取視頻縮略圖
     * @param filePath 視頻文件的路徑
     */
    public static Bitmap createVideoThumbnail(String filePath) {
        return ThumbnailUtils.createVideoThumbnail(filePath, Video.Thumbnails.MINI_KIND);
    }
    /**
    * 獲取視頻的縮略圖
    * 先通過ThumbnailUtils來創建一個視頻的縮略圖,然后再利用ThumbnailUtils來生成指定大小的縮略圖。
    * 如果想要的縮略圖的寬和高都小於MICRO_KIND,則類型要使用MICRO_KIND作為kind的值,這樣會節省內存。
    * @param videoPath 視頻的路徑
    * @param width 指定輸出視頻縮略圖的寬度
    * @param height 指定輸出視頻縮略圖的高度度
    * @param kind 參照Thumbnails類中的常量MINI_KIND(512 x 384) 和 MICRO_KIND(96 x 96)
    */
    public static Bitmap getVideoThumbnail(String videoPath, int width, int height, int kind) {
        // 獲取視頻的縮略圖
        Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }
    /**
     * 利用反射的方式獲取視頻縮略圖,不建議使用
     * @param filePath 視頻文件的路徑
     */
    public static Bitmap createVideoThumbnail2(String filePath) {
        Class<?> clazz = null;
        Object instance = null;
        try {
            clazz = Class.forName("android.media.MediaMetadataRetriever");
            instance = clazz.newInstance();
            Method method = clazz.getMethod("setDataSource", String.class);
            method.invoke(instance, filePath);
            if (Build.VERSION.SDK_INT <= 9) {
                return (Bitmap) clazz.getMethod("captureFrame").invoke(instance);
            } else {
                byte[] data = (byte[]) clazz.getMethod("getEmbeddedPicture").invoke(instance);
                if (data != null) {
                    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                    if (bitmap != nullreturn bitmap;
                }
                return (Bitmap) clazz.getMethod("getFrameAtTime").invoke(instance);
            }
        } catch (Exception ex) {
        } finally {
            try {
                if (instance != null) {
                    clazz.getMethod("release").invoke(instance);
                }
            } catch (Exception ignored) {
            }
        }
        return null;
    }
    /**
     * 將Drawable轉化為Bitmap
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的長寬,顏色格式  
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
        // 創建對應 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        return bitmap;
    }
    //********************************************************************************************************************
    public static final int NETWORK_TYPE_INVALID = 0;
    public static final int NETWORK_TYPE_MOBILE = 1;
    public static final int NETWORK_TYPE_WIFI = 2;
    /**
     * 獲取當前網絡連接狀況
     * 網絡不可用 : {@link #NETWORK_TYPE_INVALID} <br>
     * 蜂窩網絡(手機流量) : {@link #NETWORK_TYPE_MOBILE}<br>
     * WIFI連接 : {@link #NETWORK_TYPE_WIFI}
     */
    public static int getNetworkType(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            String type = networkInfo.getTypeName();
            if (type.equalsIgnoreCase("WIFI")) {
                return NETWORK_TYPE_WIFI;
            } else if (type.equalsIgnoreCase("MOBILE")) {
                return NETWORK_TYPE_MOBILE;
            }
        }
        return NETWORK_TYPE_INVALID;
    }
}

布局
       
       
       
               
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#300f"
    android:padding="5dp" >
    <RelativeLayout
        android:id="@+id/rl_vv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_weight="2016"
        android:background="#30f0"
        android:minHeight="200dp"
        android:padding="5dp" >
        <VideoView
            android:id="@+id/mVideoView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:padding="5dp" />
    </RelativeLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" >
        <Button
            android:id="@+id/btn_start"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="播放/暫停" />
        <Button
            android:id="@+id/btn_switch"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="橫豎屏切換" />
        <Button
            android:id="@+id/btn_fullscreen"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="全屏" />
    </LinearLayout>
    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
</RelativeLayout>

清單文件
      
      
      
              
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bqt.videoview"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <!-- 網絡權限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <!-- 滑動改變屏幕亮度/音量 -->
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:configChanges="keyboard|orientation|screenSize"
            android:label="@string/app_name"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN/>
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM