本文實例講述了Android中懸浮窗口的實現原理。分享給大家供大家參考。具體如下:
用了我一個周末的時間,個中憤懣就不說了,就這個問題,我翻遍全球網絡沒有一篇像樣的資料,現在將實現原理簡單敘述如下:
調用WindowManager,并設置WindowManager.LayoutParams的相關屬性,通過WindowManager的addView方法創建View,這樣產生出來的View根據WindowManager.LayoutParams屬性不同,效果也就不同了。比如創建系統頂級窗口,實現懸浮窗口效果!
WindowManager的方法很簡單,基本用到的就三個addView,removeView,updateViewLayout。
而WindowManager.LayoutParams的屬性就多了,非常豐富,具體請查看SDK文檔。這里給出Android中的WindowManager.java源碼,可以具體看一下。
下面是簡單示例代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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中添加權限:
PS:這里舉例說明一下type的值的意思:
1
2
3
4
|
/** * 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,能顯示在系統下拉狀態欄之上!
希望本文所述對大家的Android程序設計有所幫助。