surfaceview播放视频 竖屏activity中启动另一个横屏activity实现代码
时间: 2023-11-24 20:08:21 浏览: 82
surfaceview 支持横竖屏切换 视屏适配屏幕
在竖屏的Activity中启动横屏的Activity,可以在Intent中设置横屏的Activity的屏幕方向为横屏,然后在横屏的Activity中使用SurfaceView播放视频。
以下是示例代码:
竖屏的Activity:
```java
public class VerticalActivity extends AppCompatActivity {
private static final String TAG = "VerticalActivity";
// 启动横屏的Activity
private void startHorizontalActivity() {
Intent intent = new Intent(this, HorizontalActivity.class);
intent.putExtra("SCREEN_ORIENTATION", ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
startActivity(intent);
}
// 在竖屏状态下按下按钮,启动横屏的Activity
public void onClickButton(View view) {
startHorizontalActivity();
}
}
```
横屏的Activity:
```java
public class HorizontalActivity extends AppCompatActivity {
private static final String TAG = "HorizontalActivity";
private SurfaceView mSurfaceView;
private MediaPlayer mMediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 获取Intent中的屏幕方向参数
int orientation = getIntent().getIntExtra("SCREEN_ORIENTATION", ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setRequestedOrientation(orientation); // 设置屏幕方向
setContentView(R.layout.activity_horizontal);
mSurfaceView = findViewById(R.id.surface_view);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setSurface(mSurfaceView.getHolder().getSurface()); // 设置MediaPlayer的Surface
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start(); // 准备完成后开始播放
}
});
try {
mMediaPlayer.setDataSource("video.mp4"); // 设置视频文件路径
mMediaPlayer.prepareAsync(); // 异步准备MediaPlayer
} catch (IOException e) {
Log.e(TAG, "Failed to set data source", e);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.release(); // 释放MediaPlayer资源
}
}
```
其中,`activity_horizontal.xml`文件中添加了一个`SurfaceView`:
```xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="@+id/surface_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
```
阅读全文