使用VideoView可以很方便地播放本地视频,当然功能比较简单。
典型的问题有:
1、视频比例和屏幕比例不一致的话,默认不能全屏。
代码示例
public class VideoShowActivity extends AppCompatActivity {
private VideoView mVideoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_show);
mVideoView = findViewById(R.id.video_view);
setupVideo();
}
private void setupVideo() {
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mVideoView.start();
}
});
mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
stopPlaybackVideo();
}
});
mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
stopPlaybackVideo();
return true;
}
});
try {
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/raw/" + R.raw.test_video);
mVideoView.setVideoURI(uri);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onResume() {
super.onResume();
if (!mVideoView.isPlaying()) {
mVideoView.resume();
}
}
@Override
protected void onPause() {
super.onPause();
if (mVideoView.canPause()) {
mVideoView.pause();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
stopPlaybackVideo();
}
private void stopPlaybackVideo() {
try {
mVideoView.stopPlayback();
} catch (Exception e) {
e.printStackTrace();
}
}
}
xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/video_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical">
<VideoView
android:id="@+id/video_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>