权限
参考 Android10外部存储器无权限
layout
<SurfaceView
android:id="@+id/media_player_surface"
android:layout_width="match_parent"
android:layout_height="match_parent" />
设置数据源并开始播放
void startPlay() {
try {
m_MediaPlayer.setDataSource("/storage/emulated/0/Movies/Test.ts");
m_MediaPlayer.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT);//缩放模式
m_MediaPlayer.setLooping(true);//设置循环播放
m_MediaPlayer.prepareAsync();//异步准备
m_MediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
} catch (IOException e) {
e.printStackTrace();
Log.e(LOG_TAG, "m_MediaPlayer.setDataSource() failed.");
}
}
设置SurfaceHolder
private SurfaceView m_SurfaceView = null;
private SurfaceHolder m_SurfaceHolder = null;
private MediaPlayer m_MediaPlayer = null;
@Override
protected void onStart() {
m_MediaPlayer = new MediaPlayer();
m_SurfaceView = findViewById(R.id.media_player_surface);
m_SurfaceView.setKeepScreenOn(true);
m_SurfaceHolder = m_SurfaceView.getHolder();
m_SurfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
m_MediaPlayer.setDisplay(holder);
startPlay();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
});
super.onStart();
}
销毁
@Override
protected void onDestroy() {
super.onDestroy();
if (m_MediaPlayer.isPlaying()) {
m_MediaPlayer.stop();
}
m_MediaPlayer.release();
m_MediaPlayer = null;
}
设置全屏
AndroidManifest.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="android:windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
设置横屏
- 1 AndroidManifest.xml
<activity android:name=".MainActivity"
android:screenOrientation="landscape"//设置启动即横屏
android:configChanges="orientation|keyboardHidden|screenSize">//设置横竖屏切换不影响生命周期
- 2 Java中设置
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);