【轉載】使用WindowManage實現Android懸浮窗

reage_wang發表於2018-12-20

原文章連結

http://www.cnblogs.com/mengdd/p/3824782.html

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" /

服務獲取

// 獲取應用的Context
mContext = context.getApplicationContext();
// 獲取WindowManage
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://www.xsmile.net/?p=538

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

相關文章