Android桌面懸浮窗效果實現,仿360手機衛士懸浮窗效果

本文首發於CSDN博客,轉載請註明出處:http://blog.csdn.net/guolin_blog/article/details/8689140android

你們好,今天給你們帶來一個仿360手機衛士懸浮窗效果的教程,在開始以前請容許我說幾句不相干的廢話。app

不知不覺我發現本身接觸Android已有近三個年頭了,期間各類的成長少不了各位高手的幫助,老是有不少高手喜歡把本身的經驗寫在網上,供你們來學習,我也是從中受惠了不少,在此我深表感謝。但是我發現我卻歷來沒有將本身平時的一些心得拿出來與你們分享,共同窗習,太沒有奉獻精神了。因而我痛定思痛,決定從今天開始寫博客,但願能夠指點在我後面的開發者,更快地進入Android開發者的行列當中。ide

好了,廢話就說這麼多,下面開始進入今天的主題吧。工具

360手機衛士我相信你們都知道,好多人手機上都會裝這一款軟件,那麼咱們對它的一個桌面懸浮窗效果想必都不會陌生。請看下圖:佈局

                       

首先是一個小的懸浮窗顯示的是當前使用了百分之多少的內存,點擊一下小懸浮窗,就會彈出一個大的懸浮窗,能夠一鍵加速。好,咱們如今就來模擬實現一下相似的效果。post

先談一下基本的實現原理,這種桌面懸浮窗的效果很相似與Widget,可是它比Widget要靈活的多。主要是經過WindowManager這個類來實現的,調用這個類的addView方法用於添加一個懸浮窗,updateViewLayout方法用於更新懸浮窗的參數,removeView用於移除懸浮窗。其中懸浮窗的參數有必要詳細說明一下。學習

WindowManager.LayoutParams這個類用於提供懸浮窗所需的參數,其中有幾個常常會用到的變量:this

type值用於肯定懸浮窗的類型,通常設爲2002,表示在全部應用程序之上,但在狀態欄之下。spa

flags值用於肯定懸浮窗的行爲,好比說不可聚焦,非模態對話框等等,屬性很是多,你們能夠查看文檔。.net

gravity值用於肯定懸浮窗的對齊方式,通常設爲左上角對齊,這樣當拖動懸浮窗的時候方便計算座標。

x值用於肯定懸浮窗的位置,若是要橫向移動懸浮窗,就須要改變這個值。

y值用於肯定懸浮窗的位置,若是要縱向移動懸浮窗,就須要改變這個值。

width值用於指定懸浮窗的寬度。

height值用於指定懸浮窗的高度。

建立懸浮窗這種窗體須要向用戶申請權限才能夠的,所以還須要在AndroidManifest.xml中加入<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

原理介紹完了,下面咱們開始用代碼實現。首先在Eclipse中新建一個Android項目,項目名就叫作360FloatWindowDemo。而後寫一下佈局文件,佈局文件很是簡單,只有一個按鈕,打開或新建activity_main.xml,加入以下代碼:

 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="fill_parent"
 4     android:layout_height="fill_parent"
 5     tools:context=".MainActivity" >
 6     <Button
 7         android:id="@+id/start_float_window"
 8         android:layout_width="fill_parent"
 9         android:layout_height="wrap_content"
10         android:text="Start Float Window" >
11     </Button>
12 </RelativeLayout>

而後再新建一個名爲float_window_small.xml的佈局文件,用於作爲小懸浮窗的佈局,在其中加入以下代碼:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <LinearLayout
 3     xmlns:android="http://schemas.android.com/apk/res/android"
 4     android:id="@+id/small_window_layout"
 5     android:layout_width="60dip"
 6     android:layout_height="25dip"
 7     android:background="@drawable/bg_small"
 8     >
 9     <TextView 
10         android:id="@+id/percent"
11         android:layout_width="fill_parent"
12         android:layout_height="fill_parent"
13         android:gravity="center"
14         android:textColor="#ffffff"
15         />
16 </LinearLayout>

再新建一個名爲float_window_big.xml的佈局文件,用於作爲大懸浮窗的佈局,在其中加入以下代碼:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <LinearLayout
 3     xmlns:android="http://schemas.android.com/apk/res/android"
 4     android:id="@+id/big_window_layout"
 5     android:layout_width="200dip"
 6     android:layout_height="100dip"
 7     android:background="@drawable/bg_big"
 8     android:orientation="vertical"
 9     >
10     <Button 
11         android:id="@+id/close"
12         android:layout_width="100dip"
13         android:layout_height="40dip"
14         android:layout_gravity="center_horizontal"
15         android:layout_marginTop="12dip"
16         android:text="關閉懸浮窗"
17         />
18     <Button 
19         android:id="@+id/back"
20         android:layout_width="100dip"
21         android:layout_height="40dip"
22         android:layout_gravity="center_horizontal"
23         android:text="返回"
24         />
25 </LinearLayout>

兩個懸浮窗佈局文件中用到的圖片資源,你們能夠隨便找點圖片來代替,同時我會給出源碼,你們也能夠從源碼中取出。

而後打開或建立MainActivity,這是項目的主界面,在裏面加入以下代碼:

 1 public class MainActivity extends Activity {
 2     @Override
 3     protected void onCreate(Bundle savedInstanceState) {
 4         super.onCreate(savedInstanceState);
 5         setContentView(R.layout.activity_main);
 6         Button startFloatWindow = (Button) findViewById(R.id.start_float_window);
 7         startFloatWindow.setOnClickListener(new OnClickListener() {
 8             @Override
 9             public void onClick(View arg0) {
10                 Intent intent = new Intent(MainActivity.this, FloatWindowService.class);
11                 startService(intent);
12                 finish();
13             }
14         });
15     }
16 }

這裏能夠看到,MainActivity的代碼非窗簡單,就是對開啓懸浮窗的按鈕註冊了一個點擊事件,用於打開一個服務,而後關閉當前Activity。建立懸浮窗的邏輯都交給服務去作了。好,如今咱們來建立這個服務。新建一個名爲FloatWindowService的類,這個類繼承自Service,在裏面加入以下代碼:

 1 public class FloatWindowService extends Service {
 2 
 3     /**
 4      * 用於在線程中建立或移除懸浮窗。
 5      */
 6     private Handler handler = new Handler();
 7 
 8     /**
 9      * 定時器,定時進行檢測當前應該建立仍是移除懸浮窗。
10      */
11     private Timer timer;
12 
13     @Override
14     public IBinder onBind(Intent intent) {
15         return null;
16     }
17 
18     @Override
19     public int onStartCommand(Intent intent, int flags, int startId) {
20         // 開啓定時器,每隔0.5秒刷新一次
21         if (timer == null) {
22             timer = new Timer();
23             timer.scheduleAtFixedRate(new RefreshTask(), 0, 500);
24         }
25         return super.onStartCommand(intent, flags, startId);
26     }
27 
28     @Override
29     public void onDestroy() {
30         super.onDestroy();
31         // Service被終止的同時也中止定時器繼續運行
32         timer.cancel();
33         timer = null;
34     }
35 
36     class RefreshTask extends TimerTask {
37 
38         @Override
39         public void run() {
40             // 當前界面是桌面,且沒有懸浮窗顯示,則建立懸浮窗。
41             if (isHome() && !MyWindowManager.isWindowShowing()) {
42                 handler.post(new Runnable() {
43                     @Override
44                     public void run() {
45                         MyWindowManager.createSmallWindow(getApplicationContext());
46                     }
47                 });
48             }
49             // 當前界面不是桌面,且有懸浮窗顯示,則移除懸浮窗。
50             else if (!isHome() && MyWindowManager.isWindowShowing()) {
51                 handler.post(new Runnable() {
52                     @Override
53                     public void run() {
54                         MyWindowManager.removeSmallWindow(getApplicationContext());
55                         MyWindowManager.removeBigWindow(getApplicationContext());
56                     }
57                 });
58             }
59             // 當前界面是桌面,且有懸浮窗顯示,則更新內存數據。
60             else if (isHome() && MyWindowManager.isWindowShowing()) {
61                 handler.post(new Runnable() {
62                     @Override
63                     public void run() {
64                         MyWindowManager.updateUsedPercent(getApplicationContext());
65                     }
66                 });
67             }
68         }
69 
70     }
71 
72     /**
73      * 判斷當前界面是不是桌面
74      */
75     private boolean isHome() {
76         ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
77         List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
78         return getHomes().contains(rti.get(0).topActivity.getPackageName());
79     }
80 
81     /**
82      * 得到屬於桌面的應用的應用包名稱
83      * 
84      * @return 返回包含全部包名的字符串列表
85      */
86     private List<String> getHomes() {
87         List<String> names = new ArrayList<String>();
88         PackageManager packageManager = this.getPackageManager();
89         Intent intent = new Intent(Intent.ACTION_MAIN);
90         intent.addCategory(Intent.CATEGORY_HOME);
91         List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent,
92                 PackageManager.MATCH_DEFAULT_ONLY);
93         for (ResolveInfo ri : resolveInfo) {
94             names.add(ri.activityInfo.packageName);
95         }
96         return names;
97     }
98 }

FloatWindowService的onStartCommand方法中開啓了一個定時器,每隔500毫秒就會執行RefreshTask。在RefreshTask當中,要進行判斷,若是手機當前是在桌面的話,就應該顯示懸浮窗,若是手機打開了某一個應用程序,就應該移除懸浮窗,若是手機在桌面的話,還應該更新內存使用百分比的數據。而當FloatWindowService被銷燬的時候,應該將定時器中止,不然它還會一直運行。

從上面的代碼咱們也能夠看出,建立和移除懸浮窗,以及更新懸浮窗內的數據,都是由MyWindowManager這個類來管理的,比起直接把這些代碼寫在Activity或Service當中,使用一個專門的工具類來管理要好的多。不過要想建立懸浮窗,仍是先要把懸浮窗的View寫出來。

新建一個名叫FloatWindowSmallView的類,繼承自LinearLayout。新建一個名叫FloatWindowBigView的類,也繼承自LinearLayout。

在FloatWindowSmallView中加入以下代碼:

  1 public class FloatWindowSmallView extends LinearLayout {
  2 
  3     /**
  4      * 記錄小懸浮窗的寬度
  5      */
  6     public static int viewWidth;
  7 
  8     /**
  9      * 記錄小懸浮窗的高度
 10      */
 11     public static int viewHeight;
 12 
 13     /**
 14      * 記錄系統狀態欄的高度
 15      */
 16      private static int statusBarHeight;
 17 
 18     /**
 19      * 用於更新小懸浮窗的位置
 20      */
 21     private WindowManager windowManager;
 22 
 23     /**
 24      * 小懸浮窗的參數
 25      */
 26     private WindowManager.LayoutParams mParams;
 27 
 28     /**
 29      * 記錄當前手指位置在屏幕上的橫座標值
 30      */
 31     private float xInScreen;
 32 
 33     /**
 34      * 記錄當前手指位置在屏幕上的縱座標值
 35      */
 36     private float yInScreen;
 37 
 38     /**
 39      * 記錄手指按下時在屏幕上的橫座標的值
 40      */
 41     private float xDownInScreen;
 42 
 43     /**
 44      * 記錄手指按下時在屏幕上的縱座標的值
 45      */
 46     private float yDownInScreen;
 47 
 48     /**
 49      * 記錄手指按下時在小懸浮窗的View上的橫座標的值
 50      */
 51     private float xInView;
 52 
 53     /**
 54      * 記錄手指按下時在小懸浮窗的View上的縱座標的值
 55      */
 56     private float yInView;
 57 
 58     public FloatWindowSmallView(Context context) {
 59         super(context);
 60         windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
 61         LayoutInflater.from(context).inflate(R.layout.float_window_small, this);
 62         View view = findViewById(R.id.small_window_layout);
 63         viewWidth = view.getLayoutParams().width;
 64         viewHeight = view.getLayoutParams().height;
 65         TextView percentView = (TextView) findViewById(R.id.percent);
 66         percentView.setText(MyWindowManager.getUsedPercentValue(context));
 67     }
 68 
 69     @Override
 70     public boolean onTouchEvent(MotionEvent event) {
 71         switch (event.getAction()) {
 72         case MotionEvent.ACTION_DOWN:
 73             // 手指按下時記錄必要數據,縱座標的值都須要減去狀態欄高度
 74             xInView = event.getX();
 75             yInView = event.getY();
 76             xDownInScreen = event.getRawX();
 77             yDownInScreen = event.getRawY() - getStatusBarHeight();
 78             xInScreen = event.getRawX();
 79             yInScreen = event.getRawY() - getStatusBarHeight();
 80             break;
 81         case MotionEvent.ACTION_MOVE:
 82             xInScreen = event.getRawX();
 83             yInScreen = event.getRawY() - getStatusBarHeight();
 84             // 手指移動的時候更新小懸浮窗的位置
 85             updateViewPosition();
 86             break;
 87         case MotionEvent.ACTION_UP:
 88             // 若是手指離開屏幕時,xDownInScreen和xInScreen相等,且yDownInScreen和yInScreen相等,則視爲觸發了單擊事件。
 89             if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) {
 90                 openBigWindow();
 91             }
 92             break;
 93         default:
 94             break;
 95         }
 96         return true;
 97     }
 98 
 99     /**
100      * 將小懸浮窗的參數傳入,用於更新小懸浮窗的位置。
101      * 
102      * @param params
103      *            小懸浮窗的參數
104      */
105     public void setParams(WindowManager.LayoutParams params) {
106         mParams = params;
107     }
108 
109     /**
110      * 更新小懸浮窗在屏幕中的位置。
111      */
112     private void updateViewPosition() {
113         mParams.x = (int) (xInScreen - xInView);
114         mParams.y = (int) (yInScreen - yInView);
115         windowManager.updateViewLayout(this, mParams);
116     }
117 
118     /**
119      * 打開大懸浮窗,同時關閉小懸浮窗。
120      */
121     private void openBigWindow() {
122         MyWindowManager.createBigWindow(getContext());
123         MyWindowManager.removeSmallWindow(getContext());
124     }
125 
126     /**
127      * 用於獲取狀態欄的高度。
128      * 
129      * @return 返回狀態欄高度的像素值。
130      */
131     private int getStatusBarHeight() {
132         if (statusBarHeight == 0) {
133             try {
134                 Class<?> c = Class.forName("com.android.internal.R$dimen");
135                 Object o = c.newInstance();
136                 Field field = c.getField("status_bar_height");
137                 int x = (Integer) field.get(o);
138                 statusBarHeight = getResources().getDimensionPixelSize(x);
139             } catch (Exception e) {
140                 e.printStackTrace();
141             }
142         }
143         return statusBarHeight;
144     }
145 其中,對這個View的onTouchEvent事件進行了重寫,用於實現拖動和點擊的效果。若是發現用戶觸發了ACTION_DOWN事件,會記錄按下時的座標等數據。若是發現用戶觸發了ACTION_MOVE事件,則根據當前移動的座標更新懸浮窗在屏幕中的位置。若是發現用戶觸發了ACTION_UP事件,會和ACTION_DOWN中記下的座標對比,若是發現是相同的,則視爲用戶對懸浮窗進行了點擊。點擊小懸浮窗則打開大懸浮窗,而後咱們來實現大懸浮窗的View。
146 
147 在FloatWindowBigView中加入以下代碼:
148 
149 public class FloatWindowBigView extends LinearLayout {
150 
151     /**
152      * 記錄大懸浮窗的寬度
153      */
154     public static int viewWidth;
155 
156     /**
157      * 記錄大懸浮窗的高度
158      */
159     public static int viewHeight;
160 
161     public FloatWindowBigView(final Context context) {
162         super(context);
163         LayoutInflater.from(context).inflate(R.layout.float_window_big, this);
164         View view = findViewById(R.id.big_window_layout);
165         viewWidth = view.getLayoutParams().width;
166         viewHeight = view.getLayoutParams().height;
167         Button close = (Button) findViewById(R.id.close);
168         Button back = (Button) findViewById(R.id.back);
169         close.setOnClickListener(new OnClickListener() {
170             @Override
171             public void onClick(View v) {
172                 // 點擊關閉懸浮窗的時候,移除全部懸浮窗,並中止Service
173                 MyWindowManager.removeBigWindow(context);
174                 MyWindowManager.removeSmallWindow(context);
175                 Intent intent = new Intent(getContext(), FloatWindowService.class);
176                 context.stopService(intent);
177             }
178         });
179         back.setOnClickListener(new OnClickListener() {
180             @Override
181             public void onClick(View v) {
182                 // 點擊返回的時候,移除大懸浮窗,建立小懸浮窗
183                 MyWindowManager.removeBigWindow(context);
184                 MyWindowManager.createSmallWindow(context);
185             }
186         });
187     }
188 }

比起FloatWindowSmallView,FloatWindowBigView要簡單的多,其中只有兩個按鈕,點擊close按鈕,將懸浮窗所有移除,並將Service終止。單擊back按鈕則移除大懸浮窗,從新建立小懸浮窗。

如今兩個懸浮窗的View都已經寫好了,咱們來建立MyWindowManager,代碼以下:

  1 public class MyWindowManager {
  2 
  3     /**
  4      * 小懸浮窗View的實例
  5      */
  6     private static FloatWindowSmallView smallWindow;
  7 
  8     /**
  9      * 大懸浮窗View的實例
 10      */
 11     private static FloatWindowBigView bigWindow;
 12 
 13     /**
 14      * 小懸浮窗View的參數
 15      */
 16     private static LayoutParams smallWindowParams;
 17 
 18     /**
 19      * 大懸浮窗View的參數
 20      */
 21     private static LayoutParams bigWindowParams;
 22 
 23     /**
 24      * 用於控制在屏幕上添加或移除懸浮窗
 25      */
 26     private static WindowManager mWindowManager;
 27 
 28     /**
 29      * 用於獲取手機可用內存
 30      */
 31     private static ActivityManager mActivityManager;
 32 
 33     /**
 34      * 建立一個小懸浮窗。初始位置爲屏幕的右部中間位置。
 35      * 
 36      * @param context
 37      *            必須爲應用程序的Context.
 38      */
 39     public static void createSmallWindow(Context context) {
 40         WindowManager windowManager = getWindowManager(context);
 41         int screenWidth = windowManager.getDefaultDisplay().getWidth();
 42         int screenHeight = windowManager.getDefaultDisplay().getHeight();
 43         if (smallWindow == null) {
 44             smallWindow = new FloatWindowSmallView(context);
 45             if (smallWindowParams == null) {
 46                 smallWindowParams = new LayoutParams();
 47                 smallWindowParams.type = LayoutParams.TYPE_PHONE;
 48                 smallWindowParams.format = PixelFormat.RGBA_8888;
 49                 smallWindowParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
 50                         | LayoutParams.FLAG_NOT_FOCUSABLE;
 51                 smallWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
 52                 smallWindowParams.width = FloatWindowSmallView.viewWidth;
 53                 smallWindowParams.height = FloatWindowSmallView.viewHeight;
 54                 smallWindowParams.x = screenWidth;
 55                 smallWindowParams.y = screenHeight / 2;
 56             }
 57             smallWindow.setParams(smallWindowParams);
 58             windowManager.addView(smallWindow, smallWindowParams);
 59         }
 60     }
 61 
 62     /**
 63      * 將小懸浮窗從屏幕上移除。
 64      * 
 65      * @param context
 66      *            必須爲應用程序的Context.
 67      */
 68     public static void removeSmallWindow(Context context) {
 69         if (smallWindow != null) {
 70             WindowManager windowManager = getWindowManager(context);
 71             windowManager.removeView(smallWindow);
 72             smallWindow = null;
 73         }
 74     }
 75 
 76     /**
 77      * 建立一個大懸浮窗。位置爲屏幕正中間。
 78      * 
 79      * @param context
 80      *            必須爲應用程序的Context.
 81      */
 82     public static void createBigWindow(Context context) {
 83         WindowManager windowManager = getWindowManager(context);
 84         int screenWidth = windowManager.getDefaultDisplay().getWidth();
 85         int screenHeight = windowManager.getDefaultDisplay().getHeight();
 86         if (bigWindow == null) {
 87             bigWindow = new FloatWindowBigView(context);
 88             if (bigWindowParams == null) {
 89                 bigWindowParams = new LayoutParams();
 90                 bigWindowParams.x = screenWidth / 2 - FloatWindowBigView.viewWidth / 2;
 91                 bigWindowParams.y = screenHeight / 2 - FloatWindowBigView.viewHeight / 2;
 92                 bigWindowParams.type = LayoutParams.TYPE_PHONE;
 93                 bigWindowParams.format = PixelFormat.RGBA_8888;
 94                 bigWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
 95                 bigWindowParams.width = FloatWindowBigView.viewWidth;
 96                 bigWindowParams.height = FloatWindowBigView.viewHeight;
 97             }
 98             windowManager.addView(bigWindow, bigWindowParams);
 99         }
100     }
101 
102     /**
103      * 將大懸浮窗從屏幕上移除。
104      * 
105      * @param context
106      *            必須爲應用程序的Context.
107      */
108     public static void removeBigWindow(Context context) {
109         if (bigWindow != null) {
110             WindowManager windowManager = getWindowManager(context);
111             windowManager.removeView(bigWindow);
112             bigWindow = null;
113         }
114     }
115 
116     /**
117      * 更新小懸浮窗的TextView上的數據,顯示內存使用的百分比。
118      * 
119      * @param context
120      *            可傳入應用程序上下文。
121      */
122     public static void updateUsedPercent(Context context) {
123         if (smallWindow != null) {
124             TextView percentView = (TextView) smallWindow.findViewById(R.id.percent);
125             percentView.setText(getUsedPercentValue(context));
126         }
127     }
128 
129     /**
130      * 是否有懸浮窗(包括小懸浮窗和大懸浮窗)顯示在屏幕上。
131      * 
132      * @return 有懸浮窗顯示在桌面上返回true,沒有的話返回false。
133      */
134     public static boolean isWindowShowing() {
135         return smallWindow != null || bigWindow != null;
136     }
137 
138     /**
139      * 若是WindowManager還未建立,則建立一個新的WindowManager返回。不然返回當前已建立的WindowManager。
140      * 
141      * @param context
142      *            必須爲應用程序的Context.
143      * @return WindowManager的實例,用於控制在屏幕上添加或移除懸浮窗。
144      */
145     private static WindowManager getWindowManager(Context context) {
146         if (mWindowManager == null) {
147             mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
148         }
149         return mWindowManager;
150     }
151 
152     /**
153      * 若是ActivityManager還未建立,則建立一個新的ActivityManager返回。不然返回當前已建立的ActivityManager。
154      * 
155      * @param context
156      *            可傳入應用程序上下文。
157      * @return ActivityManager的實例,用於獲取手機可用內存。
158      */
159     private static ActivityManager getActivityManager(Context context) {
160         if (mActivityManager == null) {
161             mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
162         }
163         return mActivityManager;
164     }
165 
166     /**
167      * 計算已使用內存的百分比,並返回。
168      * 
169      * @param context
170      *            可傳入應用程序上下文。
171      * @return 已使用內存的百分比,以字符串形式返回。
172      */
173     public static String getUsedPercentValue(Context context) {
174         String dir = "/proc/meminfo";
175         try {
176             FileReader fr = new FileReader(dir);
177             BufferedReader br = new BufferedReader(fr, 2048);
178             String memoryLine = br.readLine();
179             String subMemoryLine = memoryLine.substring(memoryLine.indexOf("MemTotal:"));
180             br.close();
181             long totalMemorySize = Integer.parseInt(subMemoryLine.replaceAll("\\D+", ""));
182             long availableSize = getAvailableMemory(context) / 1024;
183             int percent = (int) ((totalMemorySize - availableSize) / (float) totalMemorySize * 100);
184             return percent + "%";
185         } catch (IOException e) {
186             e.printStackTrace();
187         }
188         return "懸浮窗";
189     }
190 
191     /**
192      * 獲取當前可用內存,返回數據以字節爲單位。
193      * 
194      * @param context
195      *            可傳入應用程序上下文。
196      * @return 當前可用內存。
197      */
198     private static long getAvailableMemory(Context context) {
199         ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
200         getActivityManager(context).getMemoryInfo(mi);
201         return mi.availMem;
202     }
203 
204 }

這個類負責了控制大懸浮窗,小懸浮窗的建立和移除,系統內存使用百分比的計算等操做。

到這裏基本全部的代碼都已經寫完了,而後咱們來看一下AndroidManifest.xml文件吧,裏面代碼以下:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 3     package="com.demo.floatwindowdemo"
 4     android:versionCode="1"
 5     android:versionName="1.0" >
 6 
 7     <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
 8 
 9     <uses-sdk
10         android:minSdkVersion="8"
11         android:targetSdkVersion="8" />
12 
13     <application
14         android:allowBackup="true"
15         android:icon="@drawable/ic_launcher"
16         android:label="@string/app_name"
17         android:theme="@style/AppTheme" >
18         <activity
19             android:name="com.demo.floatwindowdemo.MainActivity"
20             android:label="@string/app_name" >
21             <intent-filter>
22                 <action android:name="android.intent.action.MAIN" />
23 
24                 <category android:name="android.intent.category.LAUNCHER" />
25             </intent-filter>
26         </activity>
27         
28         <service android:name=".FloatWindowService"></service>
29     </application>
30 
31 </manifest>

比較簡單,記得把Activity和Service在裏面註冊好,還有一個權限聲明須要添加的android.permission.SYSTEM_ALERT_WINDOW,表示須要用戶受權容許建立系統提示窗口,也就是咱們的桌面懸浮窗。

好了,如今讓咱們運行一下項目吧,效果以下圖,主界面只有一個簡單的按鈕,點擊按鈕後,Activity被關閉,小懸浮窗顯示在桌面上。其中顯示着當前內存使用的百分比。

                     

小懸浮窗是能夠自由拖動的,若是打開了其它的應用程序,小懸浮窗會自動隱藏,回到桌面後小懸浮窗又會顯示出來。

                   

若是點擊了小懸浮窗會彈出大懸浮窗來,這裏咱們大懸浮窗作的比較簡單,就只有兩個按鈕。大懸浮窗展現的時候手機的全部其它程序是不可點的,由於焦點都在懸浮窗上了。點擊返回按鈕會從新展現小懸浮窗,點擊關閉懸浮窗按鈕,Service也會一塊兒停掉。

                                            

360手機衛士的一鍵加速功能咱們就不作了,就像獨孤九劍同樣,重要的是劍意而不是劍招,我相信你們學會了建立懸浮窗的基本原理後能夠作出比360更有創意的東西。

若是你們還有什麼疑問,請在下面留言。

對桌面懸浮窗感興趣的朋友能夠繼續閱讀 Android桌面懸浮窗進階,QQ手機管家小火箭效果實現 。

源碼下載,請點擊這裏

補充:

有朋友跟我反應,上面的代碼在Android 3.0以上的系統運行會崩潰,我看了一下,確實如此,主要是3.0以後想要獲取正在運行的任務,須要加上權限聲明。在AndroidManifest.xml中加入 
<uses-permission android:name="android.permission.GET_TASKS" /> 
便可解決此問題。
相關文章
相關標籤/搜索