一、运行效果:
二、新建empty activity项目:
三、打开activity_main.xml布局文件,添加VideoView:
<VideoView android:id="@+id/videoView" android:layout_width="368dp" android:layout_height="573dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
四、打开AndroidManifest.xml文件添加权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION"/>
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
五、编写MainActivity.java:
private VideoView videoView;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); videoView = findViewById(R.id.videoView); File file = new File(Environment.getExternalStorageDirectory().getPath()+"/VID_20231201_114100.mp4"); if (file.exists()) { //设置视频地址 videoView.setVideoPath(file.getAbsolutePath()); Log.d("StyleOneActivity", "视频存在"); } else { Log.d("StyleOneActivity", "视频不存在"); }
private void initMediaPlayer() { String path = Environment.getExternalStorageDirectory().getPath()+"/VID_20231201_114100.mp4"; videoView.setVideoPath(path); //创建MediaController对象 MediaController mediaController = new MediaController(this){ @Override public void hide() { super.show(); } }; //VideoView与MediaController建立关联 videoView.setMediaController(mediaController); //让VideoView获取焦点 videoView.requestFocus(); videoView.start(); }
六、项目工程: