閱讀793 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Android中懸浮窗口的實現原理和示例代碼

 

用了我一個周末的時間,個中憤懣就不說了,就這個問題,我翻遍全球網絡沒有一篇像樣的資料,現在將實現原理簡單敘述如下:

調用WindowManager,並設置WindowManager.LayoutParams的相關屬性,通過WindowManager的addView方法創建View,這樣產生出來的View根據WindowManager.LayoutParams屬性不同,效果也就不同了。比如創建係統頂級窗口,實現懸浮窗口效果!

WindowManager的方法很簡單,基本用到的就三個addView,removeView,updateViewLayout。

而WindowManager.LayoutParams的屬性就多了,非常豐富,具體請查看SDK文檔。這裏給出Android中的WindowManager.java源碼,可以具體看一下

下麵是簡單示例代碼:

public class myFloatView extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button bb=new Button(getApplicationContext());
        WindowManager wm=(WindowManager)getApplicationContext().getSystemService("window");
        WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
 
        /**
         *以下都是WindowManager.LayoutParams的相關屬性
         * 具體用途請參考SDK文檔
         */
        wmParams.type=2002;   //這裏是關鍵,你也可以試試2003
        wmParams.format=1;
         /**
         *這裏的flags也很關鍵
         *代碼實際是wmParams.flags |= FLAG_NOT_FOCUSABLE;
         *40的由來是wmParams的默認屬性(32)+ FLAG_NOT_FOCUSABLE(8)
         */
        wmParams.flags=40;
        wmParams.width=40;
        wmParams.height=40;
        wm.addView(bb, wmParams);  //創建View
    }
}

別忘了在AndroidManifest.xml中添加權限:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

PS:這裏舉例說明一下type的值的意思:

        /**
         * Window type: phone.  These are non-application windows providing
         * user interaction with the phone (in particular incoming calls).
         * These windows are normally placed above all applications, but behind
         * the status bar.
         */
        public static final int TYPE_PHONE              = FIRST_SYSTEM_WINDOW+2;
 
        /**
         * Window type: system window, such as low power alert. These windows
         * are always on top of application windows.
         */
        public static final int TYPE_SYSTEM_ALERT       = FIRST_SYSTEM_WINDOW+3;

這個FIRST_SYSTEM_WINDOW的值就是2000。2003和2002的區別就在於2003類型的View比2002類型的還要top,能顯示在係統下拉狀態欄之上!

————————————————————————————-

已經給出可自由移動懸浮窗口的Demo,參加這裏

最後更新:2017-04-02 06:51:43

  上一篇:go 申請Google Map Android API Key
  下一篇:go android 開發工具之Monkey