freeform模式默认关闭,一些手机厂商开启了此功能,模拟器没有开启。依次执行下面命令:
adb shell settings put global enable_freeform_support 1
adb shell settings put global force_resizable_activities 1
系统应用可以通过下面代码开启freeform自由模式。
Settings.Global.putInt(getContentResolver(), Settings.Global.DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT, 1);
Settings.Global.putInt(getContentResolver(), Settings.Global.DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES, 1);
DEVELOPMENT_ENABLE_FREEFORM_WINDOWS_SUPPORT和DEVELOPMENT_FORCE_RESIZABLE_ACTIVITIES为系统隐藏的API常量。
android系统可通过修改framework默认开启freeform模式,通过系统应用可直接调用相关API,三方应用需要通过反射调用setLaunchWindowingMode
方法。实现代码如下:
//freeform模式
private static final int WINDOWING_MODE_FREEFORM = 5;
//获取屏幕高宽
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
int screenWidth = metric.widthPixels;
int screenHeight = metric.heightPixels;
Intent intent = new Intent(MainActivity.this, FreeformActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT | Intent.FLAG_ACTIVITY_NEW_TASK);
ActivityOptions activityOptions = ActivityOptions.makeBasic();
//设置为freeform模式
try {
Method method = ActivityOptions.class.getMethod("setLaunchWindowingMode", int.class);
method.invoke(activityOptions, WINDOWING_MODE_FREEFORM);
} catch (Exception e) {
e.printStackTrace();
}
//freeform模式下自由窗口的大小
int freeformWidth = 400;
int freeformHeight = 400;
//居中显示
int left = screenWidth / 2 - freeformWidth / 2;
int top = screenHeight / 2 - freeformHeight / 2;
int right = screenWidth / 2 + freeformWidth / 2;
int bottom = screenHeight / 2 + freeformHeight / 2;
activityOptions.setLaunchBounds(new Rect(left,top,right,bottom));
Bundle bundle = activityOptions.toBundle();
startActivity(intent,bundle);
系统应用则可直接调用隐藏API设置Freeform模式:
activityOptions.setLaunchWindowingMode(WindowConfiguration.WINDOWING_MODE_FREEFORM)
相关系统API如下:
实现的自由窗口效果如下: