Android懸浮窗實現 使用WindowManager
WindowManager介紹
通過Context.getSystemService(Context.WINDOW_SERVICE)可以獲得 WindowManager
對象。
每一個WindowManager對象都和一個特定的 Display
綁定。
想要獲取一個不同的display的WindowManager,可以用 createDisplayContext(Display)
來獲取那個display的 Context
,之后再使用:
Context.getSystemService(Context.WINDOW_SERVICE)來獲取WindowManager。
使用WindowManager可以在其他應用最上層,甚至手機桌面最上層顯示窗口。
調用的是WindowManager繼承自基類的addView方法和removeView方法來顯示和隱藏窗口。具體見后面的實例。
另:API 17推出了Presentation
,它將自動獲取display的Context和WindowManager,可以方便地在另一個display上顯示窗口。
WindowManager實現懸浮窗例子
聲明權限
首先在manifest中添加如下權限:
<!-- 顯示頂層浮窗 --> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
注意:在MIUI上需要在設置中打開本應用的”顯示懸浮窗”開關,並且重啟應用,否則懸浮窗只能顯示在本應用界面內,不能顯示在手機桌面上。
服務獲取和基本參數設置
// 獲取應用的Context mContext = context.getApplicationContext(); // 獲取WindowManager mWindowManager = (WindowManager) mContext .getSystemService(Context.WINDOW_SERVICE);
參數設置:
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(); // 類型 params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; // WindowManager.LayoutParams.TYPE_SYSTEM_ALERT // 設置flag int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM; // | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; // 如果設置了WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,彈出的View收不到Back鍵的事件 params.flags = flags; // 不設置這個彈出框的透明遮罩顯示為黑色 params.format = PixelFormat.TRANSLUCENT; // FLAG_NOT_TOUCH_MODAL不阻塞事件傳遞到后面的窗口 // 設置 FLAG_NOT_FOCUSABLE 懸浮窗口較小時,后面的應用圖標由不可長按變為可長按 // 不設置這個flag的話,home頁的划屏會有問題 params.width = LayoutParams.MATCH_PARENT; params.height = LayoutParams.MATCH_PARENT; params.gravity = Gravity.CENTER;
點擊和按鍵事件
除了View中的各個控件的點擊事件之外,彈窗View的消失控制需要一些處理。
點擊彈窗外部可隱藏彈窗的效果,首先,懸浮窗是全屏的,只不過最外層的是透明或者半透明的:
布局如下:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:background="@color/darken_background" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:id="@+id/popup_window" android:layout_width="@dimen/dialog_window_width" android:layout_height="@dimen/dialog_window_height" android:background="@color/white" android:orientation="vertical" > <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="@dimen/dialog_title_height" android:gravity="center" android:text="@string/default_title" android:textColor="@color/dialog_title_text_color" android:textSize="@dimen/dialog_title_text_size" /> <View android:id="@+id/title_divider" android:layout_width="match_parent" android:layout_height="2dp" android:layout_below="@id/title" android:background="@drawable/dialog_title_divider" /> <TextView android:id="@+id/content" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/title_divider" android:gravity="center" android:padding="@dimen/dialog_content_padding_side" android:text="@string/default_content" android:textColor="@color/dialog_content_text_color" android:textSize="@dimen/dialog_content_text_size" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:orientation="horizontal" android:paddingBottom="@dimen/dialog_content_padding_bottom" android:paddingLeft="@dimen/dialog_content_padding_side" android:paddingRight="@dimen/dialog_content_padding_side" > <Button android:id="@+id/negativeBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:background="@drawable/promote_window_negative_btn_selector" android:focusable="true" android:padding="@dimen/dialog_button_padding" android:text="@string/default_btn_cancel" android:textColor="@color/dialog_negative_btn_text_color" android:textSize="@dimen/dialog_button_text_size" /> <Button android:id="@+id/positiveBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="18dp" android:layout_weight="1" android:background="@drawable/promote_window_positive_btn_selector" android:focusable="true" android:padding="@dimen/dialog_button_padding" android:text="@string/default_btn_ok" android:textColor="@color/dialog_positive_btn_text_color" android:textSize="@dimen/dialog_button_text_size" /> </LinearLayout> </RelativeLayout> </LinearLayout>
點擊外部可消除設置:
// 點擊窗口外部區域可消除 // 這點的實現主要將懸浮窗設置為全屏大小,外層有個透明背景,中間一部分視為內容區域 // 所以點擊內容區域外部視為點擊懸浮窗外部 final View popupWindowView = view.findViewById(R.id.popup_window);// 非透明的內容區域 view.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { LogUtil.i(LOG_TAG, "onTouch"); int x = (int) event.getX(); int y = (int) event.getY(); Rect rect = new Rect(); popupWindowView.getGlobalVisibleRect(rect); if (!rect.contains(x, y)) { WindowUtils.hidePopupWindow(); } LogUtil.i(LOG_TAG, "onTouch : " + x + ", " + y + ", rect: " + rect); return false; } });
點擊Back鍵可隱藏彈窗:
注意Flag不能設置WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE。
// 點擊back鍵可消除 view.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: WindowUtils.hidePopupWindow(); return true; default: return false; } } });
完整效果
完整代碼:

package com.example.hellowindow; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private Handler mHandler = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mHandler = new Handler(); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mHandler.postDelayed(new Runnable() { @Override public void run() { WindowUtils.showPopupWindow(MainActivity.this); } }, 1000 * 3); } }); } }

package com.example.hellowindow; import android.content.Context; import android.graphics.PixelFormat; import android.graphics.Rect; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnKeyListener; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.WindowManager.LayoutParams; import android.widget.Button; /** * 彈窗輔助類 * * @ClassName WindowUtils * * */ public class WindowUtils { private static final String LOG_TAG = "WindowUtils"; private static View mView = null; private static WindowManager mWindowManager = null; private static Context mContext = null; public static Boolean isShown = false; /** * 顯示彈出框 * * @param context * @param view */ public static void showPopupWindow(final Context context) { if (isShown) { LogUtil.i(LOG_TAG, "return cause already shown"); return; } isShown = true; LogUtil.i(LOG_TAG, "showPopupWindow"); // 獲取應用的Context mContext = context.getApplicationContext(); // 獲取WindowManager mWindowManager = (WindowManager) mContext .getSystemService(Context.WINDOW_SERVICE); mView = setUpView(context); final WindowManager.LayoutParams params = new WindowManager.LayoutParams(); // 類型 params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; // WindowManager.LayoutParams.TYPE_SYSTEM_ALERT // 設置flag int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM; // | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; // 如果設置了WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,彈出的View收不到Back鍵的事件 params.flags = flags; // 不設置這個彈出框的透明遮罩顯示為黑色 params.format = PixelFormat.TRANSLUCENT; // FLAG_NOT_TOUCH_MODAL不阻塞事件傳遞到后面的窗口 // 設置 FLAG_NOT_FOCUSABLE 懸浮窗口較小時,后面的應用圖標由不可長按變為可長按 // 不設置這個flag的話,home頁的划屏會有問題 params.width = LayoutParams.MATCH_PARENT; params.height = LayoutParams.MATCH_PARENT; params.gravity = Gravity.CENTER; mWindowManager.addView(mView, params); LogUtil.i(LOG_TAG, "add view"); } /** * 隱藏彈出框 */ public static void hidePopupWindow() { LogUtil.i(LOG_TAG, "hide " + isShown + ", " + mView); if (isShown && null != mView) { LogUtil.i(LOG_TAG, "hidePopupWindow"); mWindowManager.removeView(mView); isShown = false; } } private static View setUpView(final Context context) { LogUtil.i(LOG_TAG, "setUp view"); View view = LayoutInflater.from(context).inflate(R.layout.popupwindow, null); Button positiveBtn = (Button) view.findViewById(R.id.positiveBtn); positiveBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { LogUtil.i(LOG_TAG, "ok on click"); // 打開安裝包 // 隱藏彈窗 WindowUtils.hidePopupWindow(); } }); Button negativeBtn = (Button) view.findViewById(R.id.negativeBtn); negativeBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { LogUtil.i(LOG_TAG, "cancel on click"); WindowUtils.hidePopupWindow(); } }); // 點擊窗口外部區域可消除 // 這點的實現主要將懸浮窗設置為全屏大小,外層有個透明背景,中間一部分視為內容區域 // 所以點擊內容區域外部視為點擊懸浮窗外部 final View popupWindowView = view.findViewById(R.id.popup_window);// 非透明的內容區域 view.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { LogUtil.i(LOG_TAG, "onTouch"); int x = (int) event.getX(); int y = (int) event.getY(); Rect rect = new Rect(); popupWindowView.getGlobalVisibleRect(rect); if (!rect.contains(x, y)) { WindowUtils.hidePopupWindow(); } LogUtil.i(LOG_TAG, "onTouch : " + x + ", " + y + ", rect: " + rect); return false; } }); // 點擊back鍵可消除 view.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: WindowUtils.hidePopupWindow(); return true; default: return false; } } }); return view; } }
參考資料
WindowManager:
http://developer.android.com/reference/android/view/WindowManager.html
參考實例:
http://blog.csdn.net/deng0zhaotai/article/details/16827719
http://blog.csdn.net/guolin_blog/article/details/8689140
簡單說明:
Android之Window、WindowManager與窗口管理:
http://blog.csdn.net/xieqibao/article/details/6567814
Android系統服務-WindowManager:
http://blog.csdn.net/chenyafei617/article/details/6577940
進一步的學習:
老羅的Android之旅:
Android Activity的窗口對象Window的創建過程分析:
http://blog.csdn.net/luoshengyang/article/details/8223770
窗口管理服務WindowManagerService的簡要介紹和學習計划:
http://blog.csdn.net/luoshengyang/article/details/8462738
Android核心分析之窗口管理:
http://blog.csdn.net/maxleng/article/details/5557758