Android中懸浮視窗的實現原理和範例程式碼

來源:互聯網
上載者:User
 

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

調用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,參加這裡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.