安卓12通过windowmanage实现全局夜间模式
在Android 12中,可以通过以下步骤通过WindowManager实现全局夜间模式:
- 获取WindowManager对象:
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
- 创建一个LayoutParams对象:
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
- 设置LayoutParams的flags:
layoutParams.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; layoutParams.flags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; layoutParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; layoutParams.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
- 设置LayoutParams的type:
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
- 设置LayoutParams的宽高和位置:
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT; layoutParams.x = 0; layoutParams.y = 0;
- 创建一个View对象:
View view = new View(this);
- 设置View的背景色:
if (isNightMode) { view.setBackgroundColor(Color.BLACK); } else { view.setBackgroundColor(Color.WHITE); }
- 将View添加到WindowManager上:
windowManager.addView(view, layoutParams);
通过上述步骤,就可以实现全局夜间模式。注意,需要在AndroidManifest.xml中添加以下权限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /
原文地址: https://www.cveoy.top/t/topic/chxE 著作权归作者所有。请勿转载和采集!