Android開發之仿360手機衛士懸浮窗效果

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

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

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

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

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

x值用於確定懸浮窗的位置,如果要橫向移動懸浮窗,就需要改變這個值。

y值用於確定懸浮窗的位置,如果要縱向移動懸浮窗,就需要改變這個值。

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

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

創建懸浮窗這種窗體需要向用戶申請權限纔可以的,因此還需要在AndroidManifest.xml中加入 android.permission.SYSTEM_ALERT_WINDOW

佈局文件

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

tools:context=".MainActivity" >

android:id="@+id/start_float_window"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Start Float Window" >

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

xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/small_window_layout"

android:layout_width="60dip"

android:layout_height="25dip"

android:background="@drawable/bg_small"

>

android:id="@+id/percent"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:gravity="center"

android:textColor="#ffffff"

/>

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

xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/big_window_layout"

android:layout_width="200dip"

android:layout_height="100dip"

android:background="@drawable/bg_big"

android:orientation="vertical"

>

android:id="@+id/close"

android:layout_width="100dip"

android:layout_height="40dip"

android:layout_gravity="center_horizontal"

android:layout_marginTop="12dip"

android:text="關閉懸浮窗"

/>

android:id="@+id/back"

android:layout_width="100dip"

android:layout_height="40dip"

android:layout_gravity="center_horizontal"

android:text="返回"

/>

代碼

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button startFloatWindow = (Button) findViewById(R.id.start_float_window);

startFloatWindow.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View arg0) {

Intent intent = new Intent(MainActivity.this, FloatWindowService.class);

startService(intent);

finish();

}

});

}

}

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

public class FloatWindowService extends Service {

/**

* 用於在線程中創建或移除懸浮窗。

*/

private Handler handler = new Handler();

/**

* 定時器,定時進行檢測當前應該創建還是移除懸浮窗。

*/

private Timer timer;

@Override

public IBinder onBind(Intent intent) {

return null;

}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

// 開啓定時器,每隔0.5秒刷新一次

if (timer == null) {

timer = new Timer();

timer.scheduleAtFixedRate(new RefreshTask(), 0, 500);

}

return super.onStartCommand(intent, flags, startId);

}

@Override

public void onDestroy() {

super.onDestroy();

// Service被終止的同時也停止定時器繼續運行

timer.cancel();

timer = null;

}

class RefreshTask extends TimerTask {

@Override

public void run() {

// 當前界面是桌面,且沒有懸浮窗顯示,則創建懸浮窗。

if (isHome() && !MyWindowManager.isWindowShowing()) {

handler.post(new Runnable() {

@Override

public void run() {

MyWindowManager.createSmallWindow(getApplicationContext());

}

});

}

// 當前界面不是桌面,且有懸浮窗顯示,則移除懸浮窗。

else if (!isHome() && MyWindowManager.isWindowShowing()) {

handler.post(new Runnable() {

@Override

public void run() {

MyWindowManager.removeSmallWindow(getApplicationContext());

MyWindowManager.removeBigWindow(getApplicationContext());

}

});

}

// 當前界面是桌面,且有懸浮窗顯示,則更新內存數據。

else if (isHome() && MyWindowManager.isWindowShowing()) {

handler.post(new Runnable() {

@Override

public void run() {

MyWindowManager.updateUsedPercent(getApplicationContext());

}

});

}

}

}

/**

* 判斷當前界面是否是桌面

*/

private boolean isHome() {

ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

List rti = mActivityManager.getRunningTasks(1);

return getHomes().contains(rti.get(0).topActivity.getPackageName());

}

/**

* 獲得屬於桌面的應用的應用包名稱

*

* @return 返回包含所有包名的字符串列表

*/

private List getHomes() {

List names = new ArrayList();

PackageManager packageManager = this.getPackageManager();

Intent intent = new Intent(Intent.ACTION_MAIN);

intent.addCategory(Intent.CATEGORY_HOME);

List resolveInfo = packageManager.queryIntentActivities(intent,

PackageManager.MATCH_DEFAULT_ONLY);

for (ResolveInfo ri : resolveInfo) {

names.add(ri.activityInfo.packageName);

}

return names;

}

}

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

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

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

public class FloatWindowSmallView extends LinearLayout {

/**

* 記錄小懸浮窗的寬度

*/

public static int viewWidth;

/**

* 記錄小懸浮窗的高度

*/

public static int viewHeight;

/**

* 記錄系統狀態欄的高度

*/

private static int statusBarHeight;

/**

* 用於更新小懸浮窗的位置

*/

private WindowManager windowManager;

/**

* 小懸浮窗的參數

*/

private WindowManager.LayoutParams mParams;

/**

* 記錄當前手指位置在屏幕上的橫座標值

*/

private float xInScreen;

/**

* 記錄當前手指位置在屏幕上的縱座標值

*/

private float yInScreen;

/**

* 記錄手指按下時在屏幕上的橫座標的值

*/

private float xDownInScreen;

/**

* 記錄手指按下時在屏幕上的縱座標的值

*/

private float yDownInScreen;

/**

* 記錄手指按下時在小懸浮窗的View上的橫座標的值

*/

private float xInView;

/**

* 記錄手指按下時在小懸浮窗的View上的縱座標的值

*/

private float yInView;

public FloatWindowSmallView(Context context) {

super(context);

windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

LayoutInflater.from(context).inflate(R.layout.float_window_small, this);

View view = findViewById(R.id.small_window_layout);

viewWidth = view.getLayoutParams().width;

viewHeight = view.getLayoutParams().height;

TextView percentView = (TextView) findViewById(R.id.percent);

percentView.setText(MyWindowManager.getUsedPercentValue(context));

}

@Override

public boolean onTouchEvent(MotionEvent event) {

switch (event.getAction()) {

case MotionEvent.ACTION_DOWN:

// 手指按下時記錄必要數據,縱座標的值都需要減去狀態欄高度

xInView = event.getX();

yInView = event.getY();

xDownInScreen = event.getRawX();

yDownInScreen = event.getRawY() - getStatusBarHeight();

xInScreen = event.getRawX();

yInScreen = event.getRawY() - getStatusBarHeight();

break;

case MotionEvent.ACTION_MOVE:

xInScreen = event.getRawX();

yInScreen = event.getRawY() - getStatusBarHeight();

// 手指移動的時候更新小懸浮窗的位置

updateViewPosition();

break;

case MotionEvent.ACTION_UP:

// 如果手指離開屏幕時,xDownInScreen和xInScreen相等,且yDownInScreen和yInScreen相等,則視爲觸發了單擊事件。

if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) {

openBigWindow();

}

break;

default:

break;

}

return true;

}

/**

* 將小懸浮窗的參數傳入,用於更新小懸浮窗的位置。

*

* @param params

* 小懸浮窗的參數

*/

public void setParams(WindowManager.LayoutParams params) {

mParams = params;

}

/**

* 更新小懸浮窗在屏幕中的位置。

*/

private void updateViewPosition() {

mParams.x = (int) (xInScreen - xInView);

mParams.y = (int) (yInScreen - yInView);

windowManager.updateViewLayout(this, mParams);

}

/**

* 打開大懸浮窗,同時關閉小懸浮窗。

*/

private void openBigWindow() {

MyWindowManager.createBigWindow(getContext());

MyWindowManager.removeSmallWindow(getContext());

}

/**

* 用於獲取狀態欄的高度。

*

* @return 返回狀態欄高度的像素值。

*/

private int getStatusBarHeight() {

if (statusBarHeight == 0) {

try {

Class c = Class.forName("com.android.internal.R$dimen");

Object o = c.newInstance();

Field field = c.getField("status_bar_height");

int x = (Integer) field.get(o);

statusBarHeight = getResources().getDimensionPixelSize(x);

} catch (Exception e) {

e.printStackTrace();

}

}

return statusBarHeight;

}

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

public class FloatWindowBigView extends LinearLayout {

/**

* 記錄大懸浮窗的寬度

*/

public static int viewWidth;

/**

* 記錄大懸浮窗的高度

*/

public static int viewHeight;

public FloatWindowBigView(final Context context) {

super(context);

LayoutInflater.from(context).inflate(R.layout.float_window_big, this);

View view = findViewById(R.id.big_window_layout);

viewWidth = view.getLayoutParams().width;

viewHeight = view.getLayoutParams().height;

Button close = (Button) findViewById(R.id.close);

Button back = (Button) findViewById(R.id.back);

close.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// 點擊關閉懸浮窗的時候,移除所有懸浮窗,並停止Service

MyWindowManager.removeBigWindow(context);

MyWindowManager.removeSmallWindow(context);

Intent intent = new Intent(getContext(), FloatWindowService.class);

context.stopService(intent);

}

});

back.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// 點擊返回的時候,移除大懸浮窗,創建小懸浮窗

MyWindowManager.removeBigWindow(context);

MyWindowManager.createSmallWindow(context);

}

});

}

}

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

public class MyWindowManager {

/**

* 小懸浮窗View的實例

*/

private static FloatWindowSmallView smallWindow;

/**

* 大懸浮窗View的實例

*/

private static FloatWindowBigView bigWindow;

/**

* 小懸浮窗View的參數

*/

private static LayoutParams smallWindowParams;

/**

* 大懸浮窗View的參數

*/

private static LayoutParams bigWindowParams;

/**

* 用於控制在屏幕上添加或移除懸浮窗

*/

private static WindowManager mWindowManager;

/**

* 用於獲取手機可用內存

*/

private static ActivityManager mActivityManager;

/**

* 創建一個小懸浮窗。初始位置爲屏幕的右部中間位置。

*

* @param context

* 必須爲應用程序的Context.

*/

public static void createSmallWindow(Context context) {

WindowManager windowManager = getWindowManager(context);

int screenWidth = windowManager.getDefaultDisplay().getWidth();

int screenHeight = windowManager.getDefaultDisplay().getHeight();

if (smallWindow == null) {

smallWindow = new FloatWindowSmallView(context);

if (smallWindowParams == null) {

smallWindowParams = new LayoutParams();

smallWindowParams.type = LayoutParams.TYPE_PHONE;

smallWindowParams.format = PixelFormat.RGBA_8888;

smallWindowParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL

| LayoutParams.FLAG_NOT_FOCUSABLE;

smallWindowParams.gravity = Gravity.LEFT | Gravity.TOP;

smallWindowParams.width = FloatWindowSmallView.viewWidth;

smallWindowParams.height = FloatWindowSmallView.viewHeight;

smallWindowParams.x = screenWidth;

smallWindowParams.y = screenHeight / 2;

}

smallWindow.setParams(smallWindowParams);

windowManager.addView(smallWindow, smallWindowParams);

}

}

/**

* 將小懸浮窗從屏幕上移除。

*

* @param context

* 必須爲應用程序的Context.

*/

public static void removeSmallWindow(Context context) {

if (smallWindow != null) {

WindowManager windowManager = getWindowManager(context);

windowManager.removeView(smallWindow);

smallWindow = null;

}

}

/**

* 創建一個大懸浮窗。位置爲屏幕正中間。

*

* @param context

* 必須爲應用程序的Context.

*/

public static void createBigWindow(Context context) {

WindowManager windowManager = getWindowManager(context);

int screenWidth = windowManager.getDefaultDisplay().getWidth();

int screenHeight = windowManager.getDefaultDisplay().getHeight();

if (bigWindow == null) {

bigWindow = new FloatWindowBigView(context);

if (bigWindowParams == null) {

bigWindowParams = new LayoutParams();

bigWindowParams.x = screenWidth / 2 - FloatWindowBigView.viewWidth / 2;

bigWindowParams.y = screenHeight / 2 - FloatWindowBigView.viewHeight / 2;

bigWindowParams.type = LayoutParams.TYPE_PHONE;

bigWindowParams.format = PixelFormat.RGBA_8888;

bigWindowParams.gravity = Gravity.LEFT | Gravity.TOP;

bigWindowParams.width = FloatWindowBigView.viewWidth;

bigWindowParams.height = FloatWindowBigView.viewHeight;

}

windowManager.addView(bigWindow, bigWindowParams);

}

}

/**

* 將大懸浮窗從屏幕上移除。

*

* @param context

* 必須爲應用程序的Context.

*/

public static void removeBigWindow(Context context) {

if (bigWindow != null) {

WindowManager windowManager = getWindowManager(context);

windowManager.removeView(bigWindow);

bigWindow = null;

}

}

/**

* 更新小懸浮窗的TextView上的數據,顯示內存使用的百分比。

*

* @param context

* 可傳入應用程序上下文。

*/

public static void updateUsedPercent(Context context) {

if (smallWindow != null) {

TextView percentView = (TextView) smallWindow.findViewById(R.id.percent);

percentView.setText(getUsedPercentValue(context));

}

}

/**

* 是否有懸浮窗(包括小懸浮窗和大懸浮窗)顯示在屏幕上。

*

* @return 有懸浮窗顯示在桌面上返回true,沒有的話返回false。

*/

public static boolean isWindowShowing() {

return smallWindow != null || bigWindow != null;

}

/**

* 如果WindowManager還未創建,則創建一個新的WindowManager返回。否則返回當前已創建的WindowManager。

*

* @param context

* 必須爲應用程序的Context.

* @return WindowManager的實例,用於控制在屏幕上添加或移除懸浮窗。

*/

private static WindowManager getWindowManager(Context context) {

if (mWindowManager == null) {

mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

}

return mWindowManager;

}

/**

* 如果ActivityManager還未創建,則創建一個新的ActivityManager返回。否則返回當前已創建的ActivityManager。

*

* @param context

* 可傳入應用程序上下文。

* @return ActivityManager的實例,用於獲取手機可用內存。

*/

private static ActivityManager getActivityManager(Context context) {

if (mActivityManager == null) {

mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

}

return mActivityManager;

}

/**

* 計算已使用內存的百分比,並返回。

*

* @param context

* 可傳入應用程序上下文。

* @return 已使用內存的百分比,以字符串形式返回。

*/

public static String getUsedPercentValue(Context context) {

String dir = "/proc/meminfo";

try {

FileReader fr = new FileReader(dir);

BufferedReader br = new BufferedReader(fr, 2048);

String memoryLine = br.readLine();

String subMemoryLine = memoryLine.substring(memoryLine.indexOf("MemTotal:"));

br.close();

long totalMemorySize = Integer.parseInt(subMemoryLine.replaceAll("\\D+", ""));

long availableSize = getAvailableMemory(context) / 1024;

int percent = (int) ((totalMemorySize - availableSize) / (float) totalMemorySize * 100);

return percent + "%";

} catch (IOException e) {

e.printStackTrace();

}

return "懸浮窗";

}

/**

* 獲取當前可用內存,返回數據以字節爲單位。

*

* @param context

* 可傳入應用程序上下文。

* @return 當前可用內存。

*/

private static long getAvailableMemory(Context context) {

ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();

getActivityManager(context).getMemoryInfo(mi);

return mi.availMem;

}

}

到這裏就爲大家分享結束了,如果還是存在有不理解的地方,可以登錄鄭州app開發公司燚軒科技的官網查找先關的解答。

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