網站首頁 編程語言 正文
序言
Android懸浮窗的實現,主要有四個步驟:
1. 聲明及申請權限
2. 構建懸浮窗需要的控件
3. 將控件添加到WindowManager
4. 必要時更新WindowManager的布局
一、權限申請
需要在 AndroidMainfest.xml 中聲明權限
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
在6.0以上的時候(現在基本都是6.0以上的了),還需要用戶手動打開懸浮窗權限。
int REQUEST_CODE = 520 ; ? ? ? Intent intent= new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); ? ? startActivityForResult(intent, REQUEST_CODE);
因為會跳轉到設置界面,所以最好先彈出提示框,待用戶點擊確定后再進行跳轉。
具體代碼,可以參考一下:
private static final int RESULT_CODE_BOX = 10023; ? ? @TargetApi(Build.VERSION_CODES.M) ? ? private void checkBoxPower() { ? ? ? ? if (!Settings.canDrawOverlays(mContext)) { ? ? ? ? ? ? Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + mContext.getPackageName()));//權限申請頁面 ? ? ? ? ? ? mActivity.startActivityForResult(intent, RESULT_CODE_BOX); ? ? ? ? } ? ? } ? ? @TargetApi(Build.VERSION_CODES.M) ? ? public void onActivityResult(int requestCode, int resultCode, Intent data){ ? ? ? ? if(requestCode == RESULT_CODE_BOX){ ? ? ? ? ? ? if (!Settings.canDrawOverlays(mContext)) { ? ? ? ? ? ? ? ? Log.e(TAG,"授權失敗"); ? ? ? ? ? ? } else { ? ? ? ? ? ? ? ? Log.e(TAG,"授權成功"); ? ? ? ? ? ? ? ? //啟動懸浮窗的Service ? ? ? ? ? ? ? ? Intent intent = new Intent(mActivity, FloatingService.class); ? ? ? ? ? ? ? ? mActivity.startService(intent); ? ? ? ? ? ? } ? ? ? ? } ? ? }
Settings.canDrawOverlays 為檢查是否有懸浮窗權限的方法,如果已經有權限的時候返回true。
二、懸浮窗初始化
具體代碼,可以參考一下:
private WindowManager windowManager; ? ? private WindowManager.LayoutParams layoutParams; ? ? //懸浮窗的初始位置 ? ? private static int FloatingInitialPosition_x = 50; ? ? private static int FloatingInitialPosition_y = 50; ? ? //初始化懸浮窗 ? ? private void initFrame(){ ? ? ? ? windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); ? ? ? ? layoutParams = new WindowManager.LayoutParams();//windowManager的布局 ? ? ? ? if (Build.VERSION.SDK_INT >= 26) { //8.0以上只能使用 TYPE_APPLICATION_OVERLAY窗口類型來創建懸浮窗 ? ? ? ? ? ? layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; ? ? ? ? } else { ? ? ? ? ? ? layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE; ? ? ? ? } ? ? ? ? layoutParams.format = PixelFormat.RGBA_8888;//設置圖片格式 ? ? ? ? layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; ? ? ? ? layoutParams.gravity = Gravity.LEFT | Gravity.TOP;//懸浮框在布局的位置 ? ? ? ? layoutParams.x = FloatingInitialPosition_x; //初始位置的x坐標,相對于gravity ? ? ? ? layoutParams.y = FloatingInitialPosition_y; ? ? ? ? layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;//指定長寬 ? ? ? ? layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT; ? ? ? ?? ? ? ? ? floatView = View.inflate(getApplicationContext(), R.layout.float_box_view, null); ? ? } ? ? //展示懸浮窗 ? ? private View floatView; ? ? private void showFloatingWindow() { ? ? ? ? windowManager.addView(floatView, layoutParams); ? ? }
懸浮窗需要在別的程序之上顯示,就需要通過WindowManager獲取WINDOW_SERVICE系統服務,然后通過windowManager.addView把相應的view添加進去。
8.0以上版本時,窗口類型修改為了WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
一個最簡單的懸浮窗到此就結束了。
三、拖動功能
這個功能是懸浮窗中很常見的功能,要實現這個功能就需要用到觸摸事件的處理View.OnTouchListener。
具體代碼,可以參考一下:
floatView.setOnTouchListener(new FloatingOnTouchListener()); //懸浮窗的滑動監聽 ? ? //滑動監聽 ? ? private class FloatingOnTouchListener implements View.OnTouchListener { ? ? ? ? private int x; ? ? ? ? private int y; ? ? ? ? @Override ? ? ? ? public boolean onTouch(View view, MotionEvent event) { ? ? ? ? ? ? switch (event.getAction()) { ? ? ? ? ? ? ? ? case MotionEvent.ACTION_DOWN: ? ? ? ? ? ? ? ? ? ? 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(floatView, layoutParams); ? ? ? ? ? ? ? ? ? ? break; ? ? ? ? ? ? ? ? default: ? ? ? ? ? ? ? ? ? ? break; ? ? ? ? ? ? } ? ? ? ? ? ? return false; ? ? ? ? } ? ? }
監聽滑動做成xy的變化,并刷新windowManager就可以了。
這里有一點要注意的是,如果同時使用OnTouchListener和setOnClickListener,那每次移動都會同時觸發點擊事件,所以這里需要做一個判斷。
三、只在應用內顯示
懸浮窗不需要在別的程序上顯示,也不需要在桌面上顯示,只需要它在本APP內顯示就可以了。
其中的一種方法就是監聽App是否在前臺,如果在,則顯示。如果不在則隱藏。
App不在前臺了,可能有三種情況:1、正常退出。2、home鍵回到主界面了。3、點擊任務鍵切換到別的程序。
正常退出的情況,只要我們也正常銷毀懸浮窗就好。
home鍵和多任務鍵的情況,需要對按鍵進行監聽。然后判斷當前App是否在前臺,如果不是,則是隱藏/銷毀懸浮窗。
判斷當前App是否在前臺的代碼可以參考:
public static boolean isAppOnForeground(Context context) { ? ? ? ? ActivityManager activityManager = (ActivityManager) context.getApplicationContext() ? ? ? ? ? ? ? ? .getSystemService(Context.ACTIVITY_SERVICE); ? ? ? ? String packageName = context.getApplicationContext().getPackageName(); ? ? ? ? //獲取Android設備中所有正在運行的App ? ? ? ? List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); ? ? ? ? if (appProcesses == null) ? ? ? ? ? ? return false; ? ? ? ? for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) { ? ? ? ? ? ? if (appProcess.processName.equals(packageName) ? ? ? ? ? ? ? ? ? ? && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { ? ? ? ? ? ? ? ? return true; ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? return false; ? ? }
home鍵和多任務鍵的監聽代碼,可以參考:
InnerRecevier innerReceiver = new InnerRecevier(); ? ? ? ? IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); ? ? ? ? registerReceiver(innerReceiver, intentFilter); ? ? class InnerRecevier extends BroadcastReceiver { ? ? ? ? final String SYSTEM_DIALOG_REASON_KEY = "reason"; ? ? ? ? final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps"; ? ? ? ? final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey"; ? ? ? ? @Override ? ? ? ? public void onReceive(Context context, Intent intent) { ? ? ? ? ? ? String action = intent.getAction(); ? ? ? ? ? ? if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) { ? ? ? ? ? ? ? ? String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY); ? ? ? ? ? ? ? ? if (reason != null) { ? ? ? ? ? ? ? ? ? ? if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) { ? ? ? ? ? ? ? ? ? ? ? ? Toast.makeText(MainActivity.this, "Home鍵被監聽", Toast.LENGTH_SHORT).show(); ? ? ? ? ? ? ? ? ? ? } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) { ? ? ? ? ? ? ? ? ? ? ? ? Toast.makeText(MainActivity.this, "多任務鍵被監聽", Toast.LENGTH_SHORT).show(); ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? } ? ? }
另一種方法是使用ViewGroup。 ViewGroup是不需要權限申請的,直接顯示。( ViewGroup方法 和上面的代碼是沒有關聯的)
如果是為unity游戲做的Android SDK,可以直接獲取最頂層的view,然后把懸浮窗的view加載進來。因為unity游戲大多只有一個Activity。
具體代碼,可以參考一下:(這個也可以作為廣告的容器來填充廣告,這段示例代碼當時就是用來填充廣告的)
ViewGroup view = (ViewGroup )AppActivity.getWindow().getDecorView();//獲取最頂層的view ViewGroup bannerContainer=(ViewGroup) View.inflate(AppActivity, R.layout.activity_banner_bottom, view).findViewById(R.id.bannerContainer);//為其添加一個布局 bannerContainer.addView(adVeiw);//把懸浮窗的view加進來
如果是普通的APP,并不只有一個Activity。所以需要使用到Application.ActivityLifecycleCallbacks方法。
ActivityLifecycleCallbacks為Activity生命周期監控接口的方法,它包含了一整套Activity的生命周期回調方法,只要有一個Activity觸發了聲明周期,這個接口的回調就會觸發,并且傳回觸發生命周期方法的Activity對象。
在拿到當前顯示的Activity之后,通過activity.getWindow().getDecorView() 來獲取Activity的視圖組。然后把懸浮窗的view加進去。切換Activity時,把懸浮窗的view銷毀,在新顯示的Activity同樣把懸浮窗的view加進去。
原文鏈接:https://blog.csdn.net/qq_18704911/article/details/103513237
相關推薦
- 2022-11-01 詳解golang中的閉包與defer_Golang
- 2023-05-24 Golang?HTTP編程的源碼解析詳解_Golang
- 2022-05-12 Kotlin filter 根據條件過濾數組
- 2023-01-20 GO語言函數(func)的聲明與使用詳解_Golang
- 2022-03-20 .NET?6開發TodoList應用之實現接口請求驗證_實用技巧
- 2023-02-23 Go?routine使用方法講解_Golang
- 2023-07-07 CreateObject創建vbs對象時不支持中文而報錯
- 2022-11-01 go項目打包部署的完整步驟_Golang
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支