最近需要實現(xiàn)在白板App中點“打開”然后選擇文件再用懸浮窗展示的功能。打開文件是另外一個App贾节,剛開始我把代碼加在打開文件的這個App中魄咕,由于打開懸浮窗之后需要關(guān)閉打開文件的這個App吟税,所以我選擇先啟動Serivce犬辰,然后傳入Service的Context給懸浮窗進行打開,顯示白板的代碼如下:
package com.test.floatwindowtest;
import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.WindowManager;
import android.widget.RelativeLayout;
public class CustomFloatWindow extends RelativeLayout {
protected WindowManager mWindowManager;
private int mNormalWidth, mNormalHeight, mNormalOffsetX, mNormalOffsetY;
private WindowManager.LayoutParams mLayoutParams;
public CustomFloatWindow(Context context){
super(context);
mNormalWidth = DisplayUtil.dp2px(533);
mNormalHeight = DisplayUtil.dp2px(602);
mNormalOffsetX = DisplayUtil.dp2px(53);
mNormalOffsetY = DisplayUtil.dp2px(42);
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
mLayoutParams = new WindowManager.LayoutParams();
mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY ;
mLayoutParams.format = PixelFormat.RGBA_8888;
mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
LayoutInflater.from(context).inflate(R.layout.layout_float_window, this);
setGravityOffset(Gravity.LEFT | Gravity.TOP, mNormalOffsetX, mNormalOffsetY);
setSize(mNormalWidth, mNormalHeight);
}
private void setSize(int width, int height) {
mLayoutParams.width = width;
mLayoutParams.height = height;
}
private void setGravityOffset(int gravity, int xOffset, int yOffset) {
mLayoutParams.gravity = gravity;
mLayoutParams.x = xOffset;
mLayoutParams.y = yOffset;
}
public void show(){
mWindowManager.addView(this, mLayoutParams);
}
}
功能確實實現(xiàn)了填物,但是有一個問題纹腌,因為這里type使用TYPE_APPLICATION_OVERLAY,導(dǎo)致懸浮窗顯示在所有窗口的上方滞磺,擋住了白板里的窗口升薯。想要解決這個問題,必須調(diào)整type屬性击困,但是低層級的懸浮窗需要傳入Activity的Context覆劈,這樣必須把顯示懸浮窗的代碼移入白板App中。這樣方案改成使用startActivityForResult啟動打開文件的App沛励,拿到文件路徑之后setResult返回到白板App中打開懸浮窗责语。當(dāng)時想當(dāng)然地覺得type的值越小,層級越低目派,于是把type改成FIRST_APPLICATION_WINDOW坤候,但是測試之后發(fā)現(xiàn)層級還不是最低的。最后把type改成FIRST_SUB_WINDOW達到了目的企蹭,懸浮窗顯示在所有白板窗口的下方白筹。