以重绘状态栏,遮盖状态栏为例:
1、设置 WindowManager.LayoutParams 属性
public static WindowManager.LayoutParams getStatusViewParams(Context ctx, WindowManager mWindowManager) {
//反射状态栏高度
int actionBarHight = 0;
int resourceId = ctx.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
actionBarHight = ctx.getResources().getDimensionPixelSize(resourceId);
}
// 设置LayoutParams(全局变量)相关参数
WindowManager.LayoutParams mStatusBarParams = new WindowManager.LayoutParams();
//TYPE_SYSTEM_ERROR 需要控件获取焦点时才需要 TYPE_SYSTEM_OVERLAY
mStatusBarParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
mStatusBarParams.format = PixelFormat.RGBA_8888;
mStatusBarParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
mStatusBarParams.gravity = Gravity.CENTER | Gravity.TOP; // 调整悬浮窗口至左上角
// 以屏幕左上角为原点,设置x、y初始值
mStatusBarParams.x = 0;
mStatusBarParams.y = 0;
// 设置悬浮窗口长宽数据
mStatusBarParams.width = mWindowManager.getDefaultDisplay().getWidth();
mStatusBarParams.height = actionBarHight;
//设置加载动画
mStatusBarParams.windowAnimations=android.R.style.Animation_Translucent;
Log.e(TAG,"width:"+mStatusBarParams.width +"\nheight:" + mStatusBarParams.height );
return mStatusBarParams;
}
需要重点注意 :WindowManager.LayoutParams的type属性
TYPE_SYSTEM_ERROR 需要控件获取焦点时才需要(例如下拉、点击事件等); TYPE_SYSTEM_OVERLAY 不可以获取焦点; TYPE_TOAST 不需要权限显示悬浮窗;从4.4开始, 使用TYPE_TOAST的同时还可以接收触摸事件和按键事件了, 而4.4以前只能显示出来, 不能交互.
2、添加、修改、移除悬浮窗方法
addView、updateViewLayout、removeView
3、附注
1)悬浮窗添加流程:
WindowManager.addView -> ViewRootImpl.setView -> WindowSession.addToDisplay(AIDL进行IPC) -> WindowManagerService.addWindow() -> ViewRootImpl.setView
2)反射通知栏操作:
public static void OpenNotify(Context ctx) {
// TODO Auto-generated method stub
int currentApiVersion = android.os.Build.VERSION.SDK_INT;
try {
Object service = ctx.getSystemService("statusbar");
Class<?> statusbarManager = Class
.forName("android.app.StatusBarManager");
Method expand = null;
if (service != null) {
if (currentApiVersion <= 16) {
expand = statusbarManager.getMethod("expand");
} else {
expand = statusbarManager
.getMethod("expandNotificationsPanel");
}
expand.setAccessible(true);
expand.invoke(service);
}
} catch (Exception e) {
}
}