一、懸浮窗原理
應用使用Context上下文獲取WINDOW_SERVICE獲取WindowManager
通過調用addView()
removeView()
兩個方法來顯示和移除View
WindowManager mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
需要注意這里的Context上下文,在絕大多數非原生系統上,context上下文會影響懸浮窗的顯示范圍。
在MIUI和華為等國產系統上,使用Activity的Context只能顯示在Activity里,一旦后臺就看不見了。
所以你的懸浮窗需要后臺顯示,就一定要使用getApplicationContext()
。
二、添加一個懸浮窗
WindowManager.LayoutParams mWindowParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_TOAST,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
PixelFormat.RGBA_8888);
if (Build.VERSION.SDK_INT < 19 ) {
mWindowParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
}
mWindowManager.addView(view,mWindowParams );
public LayoutParams(int w, int h, int _type, int _flags, int _format)
當你需要一個后臺懸浮窗時,
_type
這個參數得注意和了解一下,推薦使用TYPE_TOAST
TYPE_TOAST
:
優點
: 無需開啟懸浮窗權限,缺點
:API < 19 時無法處理觸控操作TYPE_SYSTEM_ALERT
:
缺點
需要開啟懸浮窗權限
當然還有其他的_type,根據自己的需求去使用對應的類型
三、移除一個懸浮窗
removeView...................