Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 用 WindowManager 實現懸浮按鈕與懸浮菜單

編輯:關於 Android 程式設計

簡介

本文模仿實現的是 360 手機衛士的「內存球」效果:桌面上懸著一個小窗,點一下能展開菜單。實現它並不需要什麼黑科技,核心只有一個 API——WindowManager。

整體思路

所謂懸浮窗,本質上是一個沒有界面的 App,主體是一個常駐的 Service。Activity 的任務只有一個:啟動 Service,然後立刻關掉自己。

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startService(new Intent(this, FloatWindowService.class));
        finish();
    }
}
public class FloatWindowService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        FloatWindowManager.instance(getApplicationContext()).createFloatWindow();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

這裡有個關鍵點:傳統 Service 默認運行在 UI 線程中(這與內部封裝了 Thread 和 Handler 的 IntentService 不同),所以我們可以直接在 Service 裡操作界面相關內容,不必額外切換線程。

創建懸浮窗

public void createFloatWindow() {
    if (isWindowShowing()) return;

    WindowManager windowManager = getWindowManger(context);
    int screenWidth = windowManager.getDefaultDisplay().getWidth();
    int screenHeight = windowManager.getDefaultDisplay().getHeight();

    if (floatLayout == null) {
        floatLayout = new FloatLayout(context);
        if (smallLayoutParams == null) {
            smallLayoutParams = new WindowManager.LayoutParams();
            smallLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
            smallLayoutParams.format = PixelFormat.RGBA_8888;
            smallLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
            smallLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
            smallLayoutParams.width = FloatLayout.viewWidth;
            smallLayoutParams.height = FloatLayout.viewHeight;
            smallLayoutParams.x = screenWidth;
            smallLayoutParams.y = screenHeight / 2;
        }
    }
    windowManager.addView(floatLayout, smallLayoutParams);
}

幾個參數值得解釋一下:TYPE_PHONE 讓這個 View 成為系統級窗口,可以覆蓋在所有應用的最上層;FLAG_NOT_FOCUSABLE 表示不搶佔焦點,不影響其他應用的輸入;FLAG_NOT_TOUCH_MODAL 則讓窗口外的觸摸事件照常傳遞給後台應用。

自定義懸浮 View

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/small_layout"
    android:background="@drawable/bg_small"
    android:orientation="vertical"
    android:layout_width="60dip"
    android:layout_height="25dip">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="懸浮窗" />
</LinearLayout>
public class FloatLayout extends LinearLayout {

    public static int viewWidth;
    public static int viewHeight;
    private WindowManager windowManager;

    public FloatLayout(final Context context) {
        super(context);
        windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        LayoutInflater.from(context).inflate(R.layout.small_layout, this);
        View view = findViewById(R.id.small_layout);
        viewWidth = view.getLayoutParams().width;
        viewHeight = view.getLayoutParams().height;

        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                FloatWindowManager.instance(context).createFloatMenu();
                return true;
            }
        });
    }
}

這裡有個容易踩的坑:獲取寬高必須用 view.getLayoutParams(),而不能用 view.getHeight()。因為在構造方法中,這個 View 還沒有走完 measure 流程,此時 getHeight() 返回的是 0,直接拿去給 LayoutParams 會讓懸浮窗不可見。

創建懸浮菜單

菜單本質上又是一個通過 WindowManager 添加的 View,套路與懸浮窗一致:

public void createFloatMenu() {
    if (menuLayout != null) return;

    WindowManager windowManager = getWindowManger(context);
    menuLayout = new MenuLayout(context);
    menuLayoutParams = new WindowManager.LayoutParams();
    menuLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
    menuLayoutParams.format = PixelFormat.RGBA_8888;

    windowManager.addView(menuLayout, menuLayoutParams);
}

菜單佈局採用半透明背景,分成上下兩塊:上半部分是透明區域,點擊即關閉菜單;下半部分用來承載實際內容。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:background="#96000000"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/trans_part"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_weight="1"
        android:layout_height="0dp"></LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:background="@color/colorPrimary"
        android:layout_height="0dp">
        <TextView
            android:layout_width="match_parent"
            android:text="存放content"
            android:layout_height="match_parent" />
    </LinearLayout>
</LinearLayout>
public class MenuLayout extends LinearLayout {

    public MenuLayout(final Context context) {
        super(context);
        LayoutInflater.from(context).inflate(R.layout.transparent_layout, this);
        View view = findViewById(R.id.trans_part);
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                FloatWindowManager.instance(context).removeMenuLayout();
            }
        });
    }
}

小結

實現懸浮窗的關鍵就一句話:windowManager.addView() 時把 LayoutParams.type 設為系統級類型,你的 View 就能浮在所有應用的上層。剩下的工作,其實都屬於自定義 View 的範疇。

最後補充兩點現實情況:從 Android 6.0 開始,TYPE_PHONE 這類系統級懸浮窗需要用戶手動授予 SYSTEM_ALERT_WINDOW 權限(Settings.canDrawOverlays() 判斷 + 跳轉設置頁),8.0 以後則建議改用 TYPE_APPLICATION_OVERLAY;同時常駐 Service 也要面對後台的存活性問題,需要配合前台通知來提升優先級。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved