Android11 调用系统分屏
时间: 2023-06-15 15:03:02 浏览: 210
在 Android 11 中,可以使用以下代码调用系统分屏:
```java
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
final Rational rational = new Rational(3, 4); // 宽高比
final int width = (int) (getWindowManager().getDefaultDisplay().getWidth() * rational.floatValue());
final int height = getWindowManager().getDefaultDisplay().getHeight();
final PictureInPictureParams.Builder pipBuilder = new PictureInPictureParams.Builder();
pipBuilder.setAspectRatio(rational).setSourceRectHint(new Rect(0, 0, width, height));
enterPictureInPictureMode(pipBuilder.build());
} else {
// 在 Android 11 以下版本,使用旧的分屏模式
final int flags = WindowManager.LayoutParams.FLAG_SPLIT_TOUCH | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
getWindow().setFlags(flags, flags);
final WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
final Display display = wm.getDefaultDisplay();
final Point size = new Point();
display.getSize(size);
final int width = size.x / 2;
final int height = size.y;
final int x = size.x / 2;
final int y = 0;
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(width, height, WindowManager.LayoutParams.TYPE_APPLICATION, flags, PixelFormat.RGBA_8888);
params.gravity = Gravity.START | Gravity.TOP;
params.x = x;
params.y = y;
wm.addView(getLayoutInflater().inflate(R.layout.activity_split_screen, null), params);
}
```
需要注意的是,在 Android 11 以下版本的分屏模式中,需要在布局文件中添加 `android:fitsSystemWindows="true"` 属性,以保证分屏后布局正确。
阅读全文