【Android 學習】實現仿360懸浮窗

轉載請註明出處:http://blog.csdn.net/guolin_blog/article/details/8689140

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

           

首先是一個小的懸浮窗顯示的是當前使用了百分之多少的內存,點擊一下小懸浮窗,就會彈出一個大的懸浮窗,可以一鍵加速。好,我們現在就來模擬實現一下類似的效果。

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


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

type值用於確定懸浮窗的類型,一般設爲2002,表示在所有應用程序之上,但在狀態欄之下。

flags值用於確定懸浮窗的行爲,比如說不可聚焦,非模態對話框等等,屬性非常多,大家可以查看文檔。

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

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. public static int viewWidth;
  6. /**
  7. * 記錄小懸浮窗的高度
  8. */
  9. public static int viewHeight;
  10. /**
  11. * 記錄系統狀態欄的高度
  12. */
  13. private static int statusBarHeight;
  14. /**
  15. * 用於更新小懸浮窗的位置
  16. */
  17. private WindowManager windowManager;
  18. /**
  19. * 小懸浮窗的參數
  20. */
  21. private WindowManager.LayoutParams mParams;
  22. /**
  23. * 記錄當前手指位置在屏幕上的橫座標值
  24. */
  25. private float xInScreen;
  26. /**
  27. * 記錄當前手指位置在屏幕上的縱座標值
  28. */
  29. private float yInScreen;
  30. /**
  31. * 記錄手指按下時在屏幕上的橫座標的值
  32. */
  33. private float xDownInScreen;
  34. /**
  35. * 記錄手指按下時在屏幕上的縱座標的值
  36. */
  37. private float yDownInScreen;
  38. /**
  39. * 記錄手指按下時在小懸浮窗的View上的橫座標的值
  40. */
  41. private float xInView;
  42. /**
  43. * 記錄手指按下時在小懸浮窗的View上的縱座標的值
  44. */
  45. private float yInView;
  46. public FloatWindowSmallView(Context context) {
  47. super(context);
  48. windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
  49. LayoutInflater.from(context).inflate(R.layout.float_window_small, this);
  50. View view = findViewById(R.id.small_window_layout);
  51. viewWidth = view.getLayoutParams().width;
  52. viewHeight = view.getLayoutParams().height;
  53. TextView percentView = (TextView) findViewById(R.id.percent);
  54. percentView.setText(MyWindowManager.getUsedPercentValue(context));
  55. }
  56. @Override
  57. public boolean onTouchEvent(MotionEvent event) {
  58. switch (event.getAction()) {
  59. case MotionEvent.ACTION_DOWN:
  60. // 手指按下時記錄必要數據,縱座標的值都需要減去狀態欄高度
  61. xInView = event.getX();
  62. yInView = event.getY();
  63. xDownInScreen = event.getRawX();
  64. yDownInScreen = event.getRawY() - getStatusBarHeight();
  65. xInScreen = event.getRawX();
  66. yInScreen = event.getRawY() - getStatusBarHeight();
  67. break;
  68. case MotionEvent.ACTION_MOVE:
  69. xInScreen = event.getRawX();
  70. yInScreen = event.getRawY() - getStatusBarHeight();
  71. // 手指移動的時候更新小懸浮窗的位置
  72. updateViewPosition();
  73. break;
  74. case MotionEvent.ACTION_UP:
  75. // 如果手指離開屏幕時,xDownInScreen和xInScreen相等,且yDownInScreen和yInScreen相等,則視爲觸發了單擊事件。
  76. if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) {
  77. openBigWindow();
  78. }
  79. break;
  80. default:
  81. break;
  82. }
  83. return true;
  84. }
  85. /**
  86. * 將小懸浮窗的參數傳入,用於更新小懸浮窗的位置。
  87. *
  88. * @param params
  89. * 小懸浮窗的參數
  90. */
  91. public void setParams(WindowManager.LayoutParams params) {
  92. mParams = params;
  93. }
  94. /**
  95. * 更新小懸浮窗在屏幕中的位置。
  96. */
  97. private void updateViewPosition() {
  98. mParams.x = (int) (xInScreen - xInView);
  99. mParams.y = (int) (yInScreen - yInView);
  100. windowManager.updateViewLayout(this, mParams);
  101. }
  102. /**
  103. * 打開大懸浮窗,同時關閉小懸浮窗。
  104. */
  105. private void openBigWindow() {
  106. MyWindowManager.createBigWindow(getContext());
  107. MyWindowManager.removeSmallWindow(getContext());
  108. }
  109. /**
  110. * 用於獲取狀態欄的高度。
  111. *
  112. * @return 返回狀態欄高度的像素值。
  113. */
  114. private int getStatusBarHeight() {
  115. if (statusBarHeight == 0) {
  116. try {
  117. Class<?> c = Class.forName("com.android.internal.R$dimen");
  118. Object o = c.newInstance();
  119. Field field = c.getField("status_bar_height");
  120. int x = (Integer) field.get(o);
  121. statusBarHeight = getResources().getDimensionPixelSize(x);
  122. } catch (Exception e) {
  123. e.printStackTrace();
  124. }
  125. }
  126. return statusBarHeight;
  127. }

其中,對這個View的onTouchEvent事件進行了重寫,用於實現拖動和點擊的效果。如果發現用戶觸發了ACTION_DOWN事件,會記錄按下時的座標等數據。如果發現用戶觸發了ACTION_MOVE事件,則根據當前移動的座標更新懸浮窗在屏幕中的位置。如果發現用戶觸發了ACTION_UP事件,會和ACTION_DOWN中記下的座標對比,如果發現是相同的,則視爲用戶對懸浮窗進行了點擊。點擊小懸浮窗則打開大懸浮窗,然後我們來實現大懸浮窗的View。


在FloatWindowBigView中加入如下代碼:

  1. public class FloatWindowBigView extends LinearLayout {
  2. /**
  3. * 記錄大懸浮窗的寬度
  4. */
  5. public static int viewWidth;
  6. /**
  7. * 記錄大懸浮窗的高度
  8. */
  9. public static int viewHeight;
  10. public FloatWindowBigView(final Context context) {
  11. super(context);
  12. LayoutInflater.from(context).inflate(R.layout.float_window_big, this);
  13. View view = findViewById(R.id.big_window_layout);
  14. viewWidth = view.getLayoutParams().width;
  15. viewHeight = view.getLayoutParams().height;
  16. Button close = (Button) findViewById(R.id.close);
  17. Button back = (Button) findViewById(R.id.back);
  18. close.setOnClickListener(new OnClickListener() {
  19. @Override
  20. public void onClick(View v) {
  21. // 點擊關閉懸浮窗的時候,移除所有懸浮窗,並停止Service
  22. MyWindowManager.removeBigWindow(context);
  23. MyWindowManager.removeSmallWindow(context);
  24. Intent intent = new Intent(getContext(), FloatWindowService.class);
  25. context.stopService(intent);
  26. }
  27. });
  28. back.setOnClickListener(new OnClickListener() {
  29. @Override
  30. public void onClick(View v) {
  31. // 點擊返回的時候,移除大懸浮窗,創建小懸浮窗
  32. MyWindowManager.removeBigWindow(context);
  33. MyWindowManager.createSmallWindow(context);
  34. }
  35. });
  36. }
  37. }

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


現在兩個懸浮窗的View都已經寫好了,我們來創建MyWindowManager,代碼如下:

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

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


到這裏基本所有的代碼都已經寫完了,然後我們來看一下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. <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
  7. <uses-sdk
  8. android:minSdkVersion="8"
  9. android:targetSdkVersion="8" />
  10. <application
  11. android:allowBackup="true"
  12. android:icon="@drawable/ic_launcher"
  13. android:label="@string/app_name"
  14. android:theme="@style/AppTheme" >
  15. <activity
  16. android:name="com.demo.floatwindowdemo.MainActivity"
  17. android:label="@string/app_name" >
  18. <intent-filter>
  19. <action android:name="android.intent.action.MAIN" />
  20. <category android:name="android.intent.category.LAUNCHER" />
  21. </intent-filter>
  22. </activity>
  23. <service android:name=".FloatWindowService"></service>
  24. </application>
  25. </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" /> 
即可解決此問題。

關注我的技術公衆號,每天都有優質技術文章推送。關注我的娛樂公衆號,工作、學習累了的時候放鬆一下自己。

微信掃一掃下方二維碼即可關注:

        

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章