㈠ android 系統級的懸浮窗實現
當我們在使用的app的時候,如果需要實時觀測到某個功能的實時進度並且不影響其他的操作的時候或者不影響使用其他應用的時候,系統級的懸浮球是個非常不錯的選擇。
public class QueueUpFloatService extends Service {
/**
* 啟動服務並傳值
*
* @param activity 啟動服務的activity
* @param modeBean 數據對象
*/
public static void launchService(Activity activity, ModeBean modeBean) {
try {
Intent intent =new Intent(activity, QueueUpFloatService.class);
Bundle bundle =new Bundle();
bundle.putSerializable(KEY_MODEL, modeBean);
intent.putExtras(bundle);
activity.startService(intent);
}catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
@Override
public void onCreate() {
super.onCreate();
//加一點簡單的動畫
buttonScale = (ScaleAnimation) AnimationUtils.loadAnimation(this, R.anim.anim_float);
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
layoutParams =new WindowManager.LayoutParams();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
}else {
layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
}
layoutParams.format = PixelFormat.RGBA_8888;
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
layoutParams.width = ScreenUtils.dp2px(66);
layoutParams.height = ScreenUtils.dp2px(66);
layoutParams.x = ScreenUtils.getRealWidth() - ScreenUtils.dp2px(60);
layoutParams.y = ScreenUtils.deviceHeight() *2 /3;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
ModeBean modeBean = (ModeBean) intent.getExtras().getSerializable(KEY_MODEL);
LayoutInflater layoutInflater = LayoutInflater.from(this);
floatView = layoutInflater.inflate(R.layout.view_float, null);
RelativeLayout rlFloatParent =floatView.findViewById(R.id.rl_float_parent);
rlFloatParent.startAnimation(buttonScale);
TextView tvIndex =floatView.findViewById(R.id.tv_queue_index);
tvIndex.setText(modeBean.title);
floatView.findViewById(R.id.iv_close_float).setOnClickListener(v -> stopSelf());
//修改懸浮球的滑動實現
floatView.setOnTouchListener(new FloatingOnTouchListener());
windowManager.addView(floatView, layoutParams);
return super.onStartCommand(intent, flags, startId);
}
private class View.OnTouchListener {
private int x;
private int y;
private long downTime;
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downTime = System.currentTimeMillis();
x = (int) event.getRawX();
y = (int) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int nowX = (int) event.getRawX();
int nowY = (int) event.getRawY();
int movedX = nowX -x;
int movedY = nowY -y;
x = nowX;
y = nowY;
layoutParams.x =layoutParams.x + movedX;
layoutParams.y =layoutParams.y + movedY;
windowManager.updateViewLayout(view, layoutParams);
break;
case MotionEvent.ACTION_UP:
/* *
* 這里根據手指按下和抬起的時間差來判斷點擊事件還是滑動事件
* */
if ((System.currentTimeMillis() -downTime) <200) {
//檢測應用在前台還是後台
if (AppUtils.isAppIsInBackground()) {
AppUtils.moveToFront(CloseActivityUtils.activityList.get(CloseActivityUtils.activityList.size() -1).getClass());
} else {
//檢測棧頂是否為SecondActivity 不是就打開SecondActivity
if (!CloseActivityUtils.activityList.get(CloseActivityUtils.activityList.size() -1)
.getClass().getSimpleName().contains("SecondActivity")) {
SecondActivity.launchActivity(CloseActivityUtils.activityList.get(CloseActivityUtils.activityList.size() -1));
}
}
}
break;
default:
break;
}
return false;
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (null ==floatView) {
return;
}
windowManager.removeView(floatView);
windowManager=null;
}
㈡ 如何在Android中實現懸浮Activity
在Android中實現懸浮Activity可以通過以下方式完成:
1、將需要懸浮的Activity設置dialog的樣式主題,定義樣式文件如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="FullHeightDialog" parent="android:style/Theme.Dialog">
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
</style>
</resources>
2、在在清單文件中給activity設置theme
<activity
android:name=".MainActivity"
android:configChanges="locale|keyboardHidden|orientation"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/FullHeightDialog"
㈢ android 怎麼設置 懸浮activity
Android懸浮窗實現
下面實現來自於android學習手冊,裡面有實現的可運行的例子還有源碼。android學習手冊包含9個章節,108個例子,源碼文檔隨便看,例子都是可交互,可運行,源碼採用android studio目錄結構,高亮顯示代碼,文檔都採用文檔結構圖顯示,可以快速定位。360手機助手中下載,圖標上有貝殼
實現基礎
Android懸浮窗實現使用WindowManager ,WindowManager介紹
通過Context.getSystemService(Context.WINDOW_SERVICE)可以獲得 WindowManager對象。
每一個WindowManager對象都和一個特定的 Display綁定。
想要獲取一個不同的display的WindowManager,可以用 createDisplayContext(Display)來獲取那個display的 Context,之後再使用:Context.getSystemService(Context.WINDOW_SERVICE)來獲取WindowManager。
使用WindowManager可以在其他應用最上層,甚至手機桌面最上層顯示窗口。
調用的是WindowManager繼承自基類的addView方法和removeView方法來顯示和隱藏窗口。具體見後面的實例。
另:API 17推出了Presentation,它將自動獲取display的Context和WindowManager,可以方便地在另一個display上顯示窗口。
WindowManager實現懸浮窗需要聲明許可權
首先在manifest中添加如下許可權:
<!-- 顯示頂層浮窗 --><uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
注意:在MIUI上需要在設置中打開本應用的」顯示懸浮窗」開關,並且重啟應用,否則懸浮窗只能顯示在本應用界面內,不能顯示在手機桌面上。
服務獲取和基本參數設置
[java] view plain print?
// 獲取應用的Context
mContext = context.getApplicationContext();
// 獲取WindowManager
mWindowManager = (WindowManager) mContext
.getSystemService(Context.WINDOW_SERVICE);
參數設置:
final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
// 類型
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
// WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
// 設置flag
int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
// | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
// 如果設置了WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,彈出的View收不到Back鍵的事件
params.flags = flags;
// 不設置這個彈出框的透明遮罩顯示為黑色
params.format = PixelFormat.TRANSLUCENT;
// FLAG_NOT_TOUCH_MODAL不阻塞事件傳遞到後面的窗口
// 設置 FLAG_NOT_FOCUSABLE 懸浮窗口較小時,後面的應用圖標由不可長按變為可長按
// 不設置這個flag的話,home頁的劃屏會有問題
params.width = LayoutParams.MATCH_PARENT;
params.height = LayoutParams.MATCH_PARENT;
params.gravity = Gravity.CENTER;
// 獲取應用的Context
mContext = context.getApplicationContext();
// 獲取WindowManager
mWindowManager = (WindowManager) mContext
.getSystemService(Context.WINDOW_SERVICE);
//參數設置:
final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
// 類型
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
// WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
// 設置flag
int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
// | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
// 如果設置了WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,彈出的View收不到Back鍵的事件
params.flags = flags;
// 不設置這個彈出框的透明遮罩顯示為黑色
params.format = PixelFormat.TRANSLUCENT;
// FLAG_NOT_TOUCH_MODAL不阻塞事件傳遞到後面的窗口
// 設置 FLAG_NOT_FOCUSABLE 懸浮窗口較小時,後面的應用圖標由不可長按變為可長按
// 不設置這個flag的話,home頁的劃屏會有問題
params.width = LayoutParams.MATCH_PARENT;
params.height = LayoutParams.MATCH_PARENT;
params.gravity = Gravity.CENTER;
點擊和按鍵事件
除了View中的各個控制項的點擊事件之外,彈窗View的消失控制需要一些處理。
點擊彈窗外部可隱藏彈窗的效果,首先,懸浮窗是全屏的,只不過最外層的是透明或者半透明的:
具體實現
[java] view plain print?
package com.robert.floatingwindow;
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
/**
* 彈窗輔助類
*
* @ClassName WindowUtils
*
*
*/
public class WindowUtils {
private static final String LOG_TAG = "WindowUtils";
private static View mView = null;
private static WindowManager mWindowManager = null;
private static Context mContext = null;
public static Boolean isShown = false;
/**
* 顯示彈出框
*
* @param context
* @param view
*/
public static void showPopupWindow(final Context context) {
if (isShown) {
LogUtil.i(LOG_TAG, "return cause already shown");
return;
}
isShown = true;
LogUtil.i(LOG_TAG, "showPopupWindow");
// 獲取應用的Context
mContext = context.getApplicationContext();
// 獲取WindowManager
mWindowManager = (WindowManager) mContext
.getSystemService(Context.WINDOW_SERVICE);
mView = setUpView(context);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
// 類型
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
// WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
// 設置flag
int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
// | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
// 如果設置了WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,彈出的View收不到Back鍵的事件
params.flags = flags;
// 不設置這個彈出框的透明遮罩顯示為黑色
params.format = PixelFormat.TRANSLUCENT;
// FLAG_NOT_TOUCH_MODAL不阻塞事件傳遞到後面的窗口
// 設置 FLAG_NOT_FOCUSABLE 懸浮窗口較小時,後面的應用圖標由不可長按變為可長按
// 不設置這個flag的話,home頁的劃屏會有問題
params.width = LayoutParams.MATCH_PARENT;
params.height = LayoutParams.MATCH_PARENT;
params.gravity = Gravity.CENTER;
mWindowManager.addView(mView, params);
LogUtil.i(LOG_TAG, "add view");
}
/**
* 隱藏彈出框
*/
public static void hidePopupWindow() {
LogUtil.i(LOG_TAG, "hide " + isShown + ", " + mView);
if (isShown && null != mView) {
LogUtil.i(LOG_TAG, "hidePopupWindow");
mWindowManager.removeView(mView);
isShown = false;
}
}
private static View setUpView(final Context context) {
LogUtil.i(LOG_TAG, "setUp view");
View view = LayoutInflater.from(context).inflate(R.layout.popupwindow,
null);
Button positiveBtn = (Button) view.findViewById(R.id.positiveBtn);
positiveBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
LogUtil.i(LOG_TAG, "ok on click");
// 打開安裝包
// 隱藏彈窗
WindowUtils.hidePopupWindow();
}
});
Button negativeBtn = (Button) view.findViewById(R.id.negativeBtn);
negativeBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
LogUtil.i(LOG_TAG, "cancel on click");
WindowUtils.hidePopupWindow();
}
});
// 點擊窗口外部區域可消除
// 這點的實現主要將懸浮窗設置為全屏大小,外層有個透明背景,中間一部分視為內容區域
// 所以點擊內容區域外部視為點擊懸浮窗外部
final View popupWindowView = view.findViewById(R.id.popup_window);// 非透明的內容區域
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
LogUtil.i(LOG_TAG, "onTouch");
int x = (int) event.getX();
int y = (int) event.getY();
Rect rect = new Rect();
popupWindowView.getGlobalVisibleRect(rect);
if (!rect.contains(x, y)) {
WindowUtils.hidePopupWindow();
}
LogUtil.i(LOG_TAG, "onTouch : " + x + ", " + y + ", rect: "
+ rect);
return false;
}
});
// 點擊back鍵可消除
view.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
WindowUtils.hidePopupWindow();
return true;
default:
return false;
}
}
});
return view;
}
}