編輯:關於 Android 程式設計
突然對懸浮視窗產生興趣,查了資料之後做了一個小 Demo。效果是:點擊按鈕後關閉當前 Activity,顯示懸浮視窗;視窗可以拖動,雙擊後消失。

它的原理其實很簡單,核心是借用 WindowManager 這個系統管理類別來把 View 直接掛到視窗層級上。
首先在 AndroidManifest.xml 中加入 SYSTEM_ALERT_WINDOW 權限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
這裡有個非常重要的實務提醒:光是宣告權限並不夠。從 Android 6.0(API 23)開始,這個權限屬於特殊權限,必須引導使用者到系統設定頁手動開啟:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
}
若不檢查就直接 addView(),在 6.0 以上會直接拋出 BadTokenException 或 SecurityException。
把布局封裝成一個 LinearLayout 子類:
public class DesktopLayout extends LinearLayout {
public DesktopLayout(Context context) {
super(context);
setOrientation(LinearLayout.VERTICAL);
// 設定寬高
setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
View view = LayoutInflater.from(context)
.inflate(R.layout.desklayout, null);
addView(view);
}
}
// 取得系統視窗管理服務 mWindowManager = (WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE); // 視窗的布局參數 mLayout = new WindowManager.LayoutParams(); // 視窗類型:TYPE_SYSTEM_ALERT(系統提示層級) mLayout.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; // 視窗焦點與觸摸:FLAG_NOT_FOCUSABLE 表示不取得按鍵輸入焦點 mLayout.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; // 顯示模式 mLayout.format = PixelFormat.RGBA_8888; // 對齊方式 mLayout.gravity = Gravity.TOP | Gravity.LEFT; // 寬高 mLayout.width = WindowManager.LayoutParams.WRAP_CONTENT; mLayout.height = WindowManager.LayoutParams.WRAP_CONTENT;
關於 mLayout.type,要補充說明版本差異:在 Android 8.0(API 26)之前使用 TYPE_SYSTEM_ALERT 是可以的;8.0 之後必須改用 TYPE_APPLICATION_OVERLAY,否則會出 BadTokenException。寫成相容寫法如下:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mLayout.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
mLayout.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
}


package com.yc.yc_suspendingform;
import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends Activity {
private WindowManager mWindowManager;
private WindowManager.LayoutParams mLayout;
private DesktopLayout mDesktopLayout;
private long startTime;
private float x, y;
private int top; // 狀態欄高度
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createWindowManager();
createDesktopLayout();
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !Settings.canDrawOverlays(MainActivity.this)) {
startActivity(new Intent(
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName())));
return;
}
showDesk();
}
});
}
/** 建立懸浮視窗並掛上拖曳手勢 */
private void createDesktopLayout() {
mDesktopLayout = new DesktopLayout(this);
mDesktopLayout.setOnTouchListener(new OnTouchListener() {
float mTouchStartX;
float mTouchStartY;
@Override
public boolean onTouch(View v, MotionEvent event) {
// 取得相對螢幕的座標,以螢幕左上角為原點
x = event.getRawX();
y = event.getRawY() - top; // 扣掉狀態欄高度
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 取得相對 View 的座標,以此 View 左上角為原點
mTouchStartX = event.getX();
mTouchStartY = event.getY();
long end = System.currentTimeMillis() - startTime;
// 雙擊間隔在 300ms 以下視為雙擊
if (end < 300) {
closeDesk();
}
startTime = System.currentTimeMillis();
break;
case MotionEvent.ACTION_MOVE:
// 更新浮動視窗位置參數
mLayout.x = (int) (x - mTouchStartX);
mLayout.y = (int) (y - mTouchStartY);
mWindowManager.updateViewLayout(v, mLayout);
break;
case MotionEvent.ACTION_UP:
mLayout.x = (int) (x - mTouchStartX);
mLayout.y = (int) (y - mTouchStartY);
mWindowManager.updateViewLayout(v, mLayout);
mTouchStartX = mTouchStartY = 0;
break;
}
return true;
}
});
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Rect rect = new Rect();
// 取得整個視窗可見區域。若要自訂標題樣式,這行必須放在之後,否則會出錯
getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
top = rect.top; // 狀態欄高度
}
/** 顯示懸浮視窗 */
private void showDesk() {
mWindowManager.addView(mDesktopLayout, mLayout);
finish();
}
/** 關閉懸浮視窗 */
private void closeDesk() {
mWindowManager.removeView(mDesktopLayout);
finish();
}
/** 設定 WindowManager */
private void createWindowManager() {
mWindowManager = (WindowManager)
getApplicationContext().getSystemService(WINDOW_SERVICE);
mLayout = new WindowManager.LayoutParams();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mLayout.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
mLayout.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
}
mLayout.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mLayout.format = PixelFormat.RGBA_8888;
mLayout.gravity = Gravity.TOP | Gravity.LEFT;
mLayout.width = WindowManager.LayoutParams.WRAP_CONTENT;
mLayout.height = WindowManager.LayoutParams.WRAP_CONTENT;
}
}
為什麼要減掉 top?WindowManager 的座標原點是整個螢幕的左上角,而 event.getRawY() 也是以螢幕為原點,但 event.getY() 是以 View 為原點。兩者混用會導致位移量錯誤,所以在 onWindowFocusChanged 中量出狀態欄高度並扣除,才能讓拖曳手感與手指同步。
一定要用 getApplicationContext() 取 WindowManager。如果傳 Activity 的 Context,系統會把視窗綁定在該 Activity 的生命週期上,Activity 一銷毀,視窗可能殘留或直接崩潰。
記得在離開時移除視窗。如果 Activity 被銷毀而沒有呼叫 removeView(),會出現 WindowLeaked 錯誤。穩妥的做法是在 onDestroy() 中判斷並移除。
雙擊判斷的問題。上面用「兩次 ACTION_DOWN 間隔小於 300ms」來判斷雙擊,這在實機上容易誤判。更穩妥的方式是改用 GestureDetector 並搭配 setIsLongpressEnabled(),或直接使用 View.setOnDoubleTapListener()。
別忘了電池與權限成本。懸浮視窗屬於高干擾行為,Google Play 對使用 SYSTEM_ALERT_WINDOW 的 App 審核較嚴。若只是要在自己的 App 內做浮動效果,應該用 FrameLayout 疊層或 Jetpack Compose 的 Dialog/自訂 Overlay,不需要跨應用權限。
Android 與 H5 混合開發:仿微信朋友圈的 WebView 實作
混合開發讓 Android 能借助 H5 快速呈現動態內容。本文以仿微信朋友圈為例,說明如何透過 WebView 載入本地 HTML,並讓 Java 與 JavaScri
React Native 與 Android 原生的螢幕適配對照實作
從初次接觸 RN 到現在終於能寫出點東西,值得給自己一個肯定。學習這條路還長,廢話少說,直接進主題。 RN 的螢幕適配,說真的比 Android 原生簡單不少——不得不佩
Android 入門:Notification 通知的用法分析
Notification 中文即為「通知」,通常用來顯示廣播式的提示訊息。要使用 Notification,就必須搭配 NotificationManager。本文透過實
可直接套用的 Android 刮獎控制項(含百分比統計)
這裡提供一個開箱即用的刮獎 View,除了基本的刮開效果,還能回報「已刮開面積占比」,方便在刮到一定程度時自動揭示獎項。 功能特色 1. 刮開後可顯示自訂的文字或圖片(