1.實現思路
通過WM.addView()方式
2.實現步驟
2.1 獲取WM對象
WindowManager mWindowManager = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
2.2 創(chuàng)建View
View mFloatingContentView = LayoutInflater.from(this).inflate(R.layout.float_content,null);
//查找控件
TextView txtView = mFaceDetectView.findViewById(R.id.floating_textview);
2.3 設置布局參數
//創(chuàng)建LayoutParams對象邢笙,WindowManager.LayoutParams為ViewGroup.LayoutParams的子類
WindowManager.LayoutParams mFloatingLayoutParams = new WindowManager.LayoutParams();
// 設置Window Type
// TYPE_SYSTEM_OVERLAY 系統頂層窗口誊涯。顯示在其他一切內容之上。此窗口不能獲得輸入焦點民珍,否則影響鎖屏。
//mFloatingLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
// 設置懸浮框不可觸摸
// mFloatingLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
// | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
//TYPE_APPLICATION_OVERLAY--所有應用之上盗飒,狀態(tài)欄嚷量、輸入法等系統window之下
mFloatingLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
mFloatingLayoutParams.format = PixelFormat.RGBA_8888;
// 設置懸浮框的寬高
mFloatingLayoutParams.width = 200;
mFloatingLayoutParams.height = 120;
mFloatingLayoutParams.gravity = Gravity.CENTER;
mFloatingLayoutParams.x = 0;
mFloatingLayoutParams.y = 0;
2.4 WM.addView
mWindowManager.addView(mFloatingContentView,mFloatingLayoutParams);
2.5 mainfest申請權限
<!-- 顯示頂層浮窗 -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
2.6 高版本動態(tài)權限申請(略)
3.擴展
WindowManager.LayoutParams的type部分取值
- WindowManager.LayoutParams.TYPE_SYSTEM_ALERT 類似低電量彈框,在應用之上
- WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY android o或之上版本推薦使用
參考資料
安卓:許可被拒絕窗式2038使用TYPE_APPLICATION_OVERLAY