Android WindowManager是一项系统服务,负责管理Windows的Z顺序列表,Windows是可见的,以及如何在屏幕上布置它们。除其他外,它在打开或关闭应用程序或旋转屏幕时会自动执行窗口过渡和动画。
每个活动都有一个用于在屏幕上显示其内容的窗口。当您在活动上调用SetContentView时,它将该视图附加到活动的默认窗口。默认窗口填充了屏幕,因此您的活动的窗口隐藏了所有其他活动 - WindowManager将显示最顶部的窗口。因此,通常您不必担心Windows - 您只需创建一个活动,Android将为您服务。
但是,如果您想做一些不寻常的事情,例如创建不填充屏幕的浮动窗口,则需要与WindowManager进行交互。如果要创建一个在其他应用程序面前可见的浮动窗口,则无法使用活动,因为当另一个应用程序进入前景时,您的活动将停止,并且其窗口将被隐藏或破坏。相反,您需要显示背景服务的窗口。例如:
WindowManager.LayoutParams p = new WindowManager.LayoutParams(
// Shrink the window to wrap the content rather than filling the screen
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
// Display it on top of other application windows, but only for the current user
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
// Don't let it grab the input focus
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
// Make the underlying application window visible through any transparent parts
PixelFormat.TRANSLUCENT);
// Define the position of the window within the screen
p.gravity = Gravity.TOP | Gravity.RIGHT;
p.x = 0;
p.y = 100;
WindowManager windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
windowManager.addView(myView, p);
为此,您需要将以下权限添加到您的androidmanifest.xml
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>