给Android VideoView一个文件目录,就可以直接播放智能设备中的视频文件,现在以播放事先用手机拍好并重命名的视频文件test.mp4为例。
(1) 需要在布局文件中写一个ViedoView:
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 tools:context="com.example.videoview.MainActivity" > 6 7 <VideoView 8 android:layout_width="match_parent" 9 android:layout_height="match_parent" 10 android:id="@+id/videoView" /> 11 12 </RelativeLayout>
(2)不要忘记在AndroidManifest.xml文件中添加读写外部存储的权限:
1 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
(3)在java代码中给VideoView设置文件目录,然后start播放:
1 package com.example.videoview; 2 3 import java.io.File; 4 5 import android.app.Activity; 6 import android.os.Bundle; 7 import android.os.Environment; 8 import android.widget.VideoView; 9 10 public class MainActivity extends Activity { 11 12 @Override 13 protected void onCreate(Bundle savedInstanceState) { 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.activity_main); 16 17 VideoView videoView = (VideoView) findViewById(R.id.videoView); 18 19 // 获得的path等于:/storage/emulated/0/DCIM 20 File path = Environment 21 .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); 22 23 // 拼接完整路径 24 File f = new File(path, "/Camera/test.mp4"); 25 26 // 此时的f.getAbsolutePath()=/storage/emulated/0/DCIM//Camera/test.mp4 27 videoView.setVideoPath(f.getAbsolutePath()); 28 29 // 开始播放视频 30 videoView.start(); 31 32 // VideiView获焦点 33 // videoView.requestFocus(); 34 } 35 }