1,概念
1)Window
桌面上类似悬浮窗的东西。
Window抽象类,具体实现是PhoneWindow。
Android中所有的视图都是附加在Window上的,Window实际是View的直接管理者。
2)WindowManager
WindowManager是外界访问Window的入口。
WindowManager和WindowManagerService的交互是一个IPC过程。
3)ActivityManagerService(AMS)
AMS也是一个Binder。
2,工作机制
①添加Window
使用WindowManager添加一个Window:
/*将一个Button添加到屏幕坐标为(100,300)的位置上。
mFloatingButton = new Button(this);
mFloatingButton.setText("button");
mLayoutParams = new WindowManager.LayoutParams(LayoutParams.WRAR_CONTENT, LayoutParams.WRAR_CONTENT,0,0,PixelFormat.TRANSPARENT);
mLayoutParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL;
mLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
mLayoutParams.x = 100;
mLayoutParams.y = 300;
mWindowManager.addView(mFloatingButton, mLayoutParams);
LayoutParams中的flags和type这两个参数比较重要。
**flags 表示Window属性。
–FLAG_NOT_TOUCH_MODAL
此模式下,系统会将当前Window区域以外的单击事件传递给底层的Window,当前Window区域以内的单击事件则自己处理。
不开启此标记,其他Window将无法收到单击事件。
–FLAG_NOT_FOCUSABLE
表示Window不需要获取焦点,也不需要接收各种输入事件,此标记同时会启动FLAG_NOT_TOUCH_MODAL,最终事件会直接传递给下层的有焦点的Window。
–FLAG_SHOW_WHEN_LOCKED
开启此模式可以让Window显示在锁屏界面上。
**Type 表示Window的类型
应用Window、子Window、系统Window的层级范围。
如果想要Window位于所有Window的最顶层,那么采用较大的层级即可。
2)Window分类
Window是分层的,每个Window都有对应的z-ordered,层级大的会覆盖在层级小的Window的上面,这和HTML中的z-index概念一致。
①应用Window
对应一个Activity。
层级范围:1~99
②子Window
不能单独存在,需要附属在特定的父Window之中,比如:Dialog.
层级范围:1000~1999
③系统Window
需要声明权限才能创建的Window,如Toast和系统状态栏等。
层级范围:2000~2999
使用时要在AndroidManifest中申明权限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
3)Window的内部机制
Window以View的形式存在。
WindowManager提供了3个方法:addView、updateViewLayout、removeView。
3,方法
1)获取屏幕密度 getScreen
2)获取设备屏幕大小 getDisplay
3)获得屏幕的属性,从而取得屏幕的高度和宽度 getMetrics
WindowManager manager = this.getWindowManager();
DisplayMetrics outMetrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(outMetrics);
int width = outMetrics.widthPixels;
int height = outMetrics.heightPixels;