Android 11引入了新的多窗口模式增强功能,允许用户将应用程序分割成多个窗口同时运行。这个新的功能需要在代码中进行一些调整,在此提供一个简单的代码示例以启发实现。
为了支持多窗口,需要在应用程序的活动中添加以下代码片段:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
getWindow().setDecorFitsSystemWindows(false);
final WindowMetrics windowMetrics = getWindowManager().getCurrentWindowMetrics();
final Insets insets = windowMetrics.getWindowInsets().getInsetsIgnoringVisibility(WindowInsets.Type.systemBars());
final int insetsWidth = insets.left + insets.right;
final int insetsHeight = insets.top + insets.bottom;
final Rect bounds = windowMetrics.getBounds();
bounds.inset(insets);
final int width = bounds.width();
final int height = bounds.height();
final Rational aspectRatio = new Rational(width, height);
final Pair pair = new Pair<>(
WindowLayoutInfo.Builder.from(getWindow(), null).setBounds(bounds).setForegroundInsets(insets).setSystemGestureInsets(insets).setTrustedOverlay(true).build(),
ActivityOptions.makeBasic().setLaunchWindowingMode(SCREEN_SPLIT_SECONDARY).setTaskAlwaysOnTop(true).setTaskWindowingMode(SPLIT_SCREEN_CREATED).setActivityLaunchAnimation(NO_ANIMATION)
);
getWindow().setWindowLayoutInfo(pair.first);
startActivity(getApplicationInfo().packageName, MainActivity.class, null, pair.second.toBundle());
finish();
}
这个代码片段做了很多事情,包括: