首页 > 代码库 > android中使用videoview播放视频

android中使用videoview播放视频

先是布局文件:

 1 <LinearLayout 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     android:orientation="vertical"
 6     tools:context=".MainActivity" >
 7 
 8     <VideoView
 9         android:id="@+id/video"
10         android:layout_width="match_parent"
11         android:layout_height="match_parent" />
12 
13 </LinearLayout>

然后在mainactivity中使用videoview:

 1 import java.io.File;
 2 
 3 import android.app.Activity;
 4 import android.os.Bundle;
 5 import android.os.Environment;
 6 import android.widget.MediaController;
 7 import android.widget.Toast;
 8 import android.widget.VideoView;
 9 
10 public class MainActivity extends Activity {
11     VideoView videoView;
12     MediaController mController;
13 
14     @Override
15     protected void onCreate(Bundle savedInstanceState) {
16         super.onCreate(savedInstanceState);
17         setContentView(R.layout.activity_main);
18         videoView = (VideoView) findViewById(R.id.video);
19         mController = new MediaController(this);
20         File video = new File(Environment.getExternalStorageDirectory() + "/xiexienideai.mp4");//获得手机上sd卡视频存储路径
21         if(video.exists()){
22             videoView.setVideoPath(video.getAbsolutePath());
23             videoView.setMediaController(mController);//设置mController关联videoview
24             mController.setMediaPlayer(videoView);
25             videoView.requestFocus();//videoview获得焦点
26         }else{
27             Toast.makeText(this, "nonono", Toast.LENGTH_LONG).show();
28         }
29     }
30 
31 }

由于使用到sd卡上内容获取,需要在配置文件中增加权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

android中使用videoview播放视频