編輯:關於 Android 程式設計
上一篇我們談了 Android Toast 的擴展,在原生 Toast 基礎上對顯示時長與動畫做了二次封裝,並分析了 ExToast 的設計原理與關鍵點。本文接著探討一個延伸應用:如何打造免權限的懸浮窗。
其實 Toast 本質上就是一種系統懸浮窗,那它與一般懸浮窗有何不同?先看常見的系統懸浮窗寫法:
mContext = context.getApplicationContext();
mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
mView = setUpView(context);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
params.flags = flags;
params.format = PixelFormat.TRANSLUCENT;
params.width = LayoutParams.MATCH_PARENT;
params.height = LayoutParams.MATCH_PARENT;
params.gravity = Gravity.CENTER;
mWindowManager.addView(mView, params);再看 Toast 原始碼中的關鍵片段:
final WindowManager.LayoutParams params = mParams;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.format = PixelFormat.TRANSLUCENT;
params.windowAnimations = com.android.internal.R.style.Animation_Toast;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
params.setTitle("Toast");
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
Context context = mView.getContext().getApplicationContext();
mWM = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if (mView.getParent() != null) { mWM.removeView(mView); }
mWM.addView(mView, mParams);兩段程式流程一致:建立 LayoutParams 做視窗設定 → 透過 context 取得 WindowManager → 用它加入懸浮窗 View。主要差異在 LayoutParams 的 type。type 種類繁多,包括各種系統對話框、鎖屏視窗、電話視窗等,但大多需要權限;而 Toast 不需權限即可顯示,因此我們可以嘗試把懸浮窗類型設成 TYPE_TOAST,打造免權限懸浮窗。
public class ADToast implements View.OnTouchListener {
Context mContext;
WindowManager.LayoutParams params;
WindowManager mWM;
View mView;
private float mTouchStartX, mTouchStartY, x, y;
public ADToast(Context context) {
this.mContext = context;
params = new WindowManager.LayoutParams();
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.format = PixelFormat.TRANSLUCENT;
params.windowAnimations = R.style.anim_view;
// 懸浮窗類型,整個 demo 的關鍵點
params.type = WindowManager.LayoutParams.TYPE_TOAST;
params.gravity = Gravity.LEFT | Gravity.TOP;
params.setTitle("Toast");
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mWM = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = inflate.inflate(R.layout.float_tips_layout, null);
mView.setOnTouchListener(this);
}
public void show() {
if (mView.getParent() != null) { mWM.removeView(mView); }
mWM.addView(mView, params);
}
public void hide() {
if (mView != null) { mWM.removeView(mView); }
}
private void updateViewPosition() {
params.x = (int) (x - mTouchStartX);
params.y = (int) (y - mTouchStartY);
mWM.updateViewLayout(mView, params);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
x = event.getRawX();
y = event.getRawY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTouchStartX = event.getX();
mTouchStartY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
updateViewPosition();
break;
case MotionEvent.ACTION_UP:
updateViewPosition();
break;
}
return true;
}
}版面 float_tips_layout.xml:
<LinearLayout android:background="@android:color/black" android:gravity="center" android:layout_height="match_parent" android:layout_width="match_parent" android:orientation="vertical">
<TextView android:id="@+id/message" android:layout_gravity="center_horizontal" android:layout_height="wrap_content" android:layout_width="wrap_content" android:linespacingextra="16dp" android:maxlines="2" android:textcolor="@android:color/white" android:textsize="40sp">
</LinearLayout>
這套做法在原生 6.0(Nexus 5)、一加 3、魅族 pro5 上都測試通過,唯独小米 MIUI8 對 Toast 類型懸浮窗做了權限控制。實測在 MIUI8 中,開啟懸浮窗權限後此類懸浮窗才能顯示,而原生 Toast 卻不需權限即可顯示,可見小米在 framework 層對 Toast 類型做了特殊處理。
既然 Toast 能顯示,就代表一定有辦法繞過。最直接的方式是比對 framework 層原生 Toast 與自訂懸浮窗在權限處理上的差異,但難度較高。因此先採用更易實現的方案:既然原生 Toast 不需權限,那就在原生 Toast 基礎上繼續擴展封裝。
public class MiExToast implements View.OnTouchListener {
public static final int LENGTH_ALWAYS = 0;
public static final int LENGTH_SHORT = 2;
public static final int LENGTH_LONG = 4;
private Toast toast;
private Context mContext;
private int mDuration = LENGTH_SHORT;
private int animations = -1;
private boolean isShow = false;
private Object mTN;
private Method show, hide;
private WindowManager mWM;
private WindowManager.LayoutParams params;
private View mView;
private float mTouchStartX, mTouchStartY, x, y;
private Handler handler = new Handler();
public MiExToast(Context context) {
this.mContext = context;
if (toast == null) { toast = new Toast(mContext); }
LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = inflate.inflate(R.layout.float_tips_layout, null);
mView.setOnTouchListener(this);
}
private Runnable hideRunnable = new Runnable() {
@Override public void run() { hide(); }
};
public void show() {
if (isShow) return;
toast.setView(mView);
initTN();
try {
show.invoke(mTN);
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
isShow = true;
if (mDuration > LENGTH_ALWAYS) {
handler.postDelayed(hideRunnable, mDuration * 1000);
}
}
public void hide() {
if (!isShow) return;
try {
hide.invoke(mTN);
} catch (InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
isShow = false;
}
private void initTN() {
try {
Field tnField = toast.getClass().getDeclaredField("mTN");
tnField.setAccessible(true);
mTN = tnField.get(toast);
show = mTN.getClass().getMethod("show");
hide = mTN.getClass().getMethod("hide");
Field tnParamsField = mTN.getClass().getDeclaredField("mParams");
tnParamsField.setAccessible(true);
params = (WindowManager.LayoutParams) tnParamsField.get(mTN);
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
if (animations != -1) { params.windowAnimations = animations; }
// 呼叫 tn.show() 前一定要先設定 mNextView
Field tnNextViewField = mTN.getClass().getDeclaredField("mNextView");
tnNextViewField.setAccessible(true);
tnNextViewField.set(mTN, toast.getView());
mWM = (WindowManager) mContext.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
} catch (Exception e) {
e.printStackTrace();
}
}
private void updateViewPosition() {
params.x = (int) (x - mTouchStartX);
params.y = (int) (y - mTouchStartY);
mWM.updateViewLayout(toast.getView(), params);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
x = event.getRawX();
y = event.getRawY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTouchStartX = event.getX();
mTouchStartY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
updateViewPosition();
break;
}
return true;
}
}使用範例:
MiExToast miToast = new MiExToast(getApplicationContext());
miToast.setDuration(MiExToast.LENGTH_ALWAYS);
miToast.setAnimations(R.style.anim_view);
miToast.show();這個 Demo 基於前一篇的 Toast 擴展再次封裝而成,僅供理解原理,並非可直接使用的工具類。
三個關鍵點:
1. Toast 可以自訂 View。
2. 懸浮窗的觸摸需修改 LayoutParams.flags,設定 FLAG_NOT_TOUCH_MODAL。
3. 刷新懸浮窗只需取得 WindowManager 實例,呼叫 updateViewLayout 並傳入 View 與 LayoutParams。
由於可透過反射取得 Toast 的 LayoutParams 實例並設定可觸摸旗標,重點在 initTN() 方法中保留該實例的引用:
Field tnParamsField = mTN.getClass().getDeclaredField("mParams");
tnParamsField.setAccessible(true);
params = (WindowManager.LayoutParams) tnParamsField.get(mTN);
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;接著對 Toast 設定自訂 View,並為它加上 Touch 事件,讓使用者能拖動懸浮窗。最後透過 WindowManager 的 updateViewLayout 完成更新:
private void updateViewPosition() {
mWM.updateViewLayout(toast.getView(), params);
}大致原理便是借助原生 Toast 顯示自訂懸浮窗,藉此繞過小米 MIUI8 對 Toast 類型懸浮窗的權限封鎖。
最後附上小米系統上的實測示意圖:

Android 網路編程:UDP 通信模型實作範例
什麼是 Android UDP? UDP 是 User Datagram Protocol 的簡稱,中文名為使用者資料包協定,是 OSI 參考模型中一種無連線的傳輸層協定
Android自定義安全輸入法:防止密碼被第三方竊取
本文為大家分享一個自定義輸入法的實現示例,供感興趣的讀者參考。 對於Android用戶來說,大多數人都習慣使用第三方輸入法。然而在輸入密碼(尤其是支付相關的密碼)時,第三
Android RecyclerView 使用入門:從依賴到自訂 Adapter
RecyclerView 是 support-v7 中的新元件。 RecyclerView 可以用來取代 ListView 與 GridView。顧名思義,它會自動回
Android Studio 導入專案到 VisualSVN Server 並忽略相關檔案的詳細步驟
當你提交程式碼時,若冒出一堆不想提交的檔案,也許你會在左側欄手動選中 java→src 再提交。這樣做沒問題,但如果你想用捷徑圖示快速提交,就會很頭痛了。如下圖就是這個