網(wǎng)站首頁 編程語言 正文
Android 彈窗淺談
我們知道 Android 彈窗中,有一類彈窗會在應(yīng)用之外也顯示,這是因?yàn)樗簧昝鞒闪?strong>系統(tǒng)彈窗,除此之外還有2類彈窗分別是:子彈窗與應(yīng)用彈窗。
應(yīng)用彈窗:就是我們常規(guī)使用的 Dialog 之類彈窗,依賴于應(yīng)用的 Activity;子彈窗:依賴于父窗口,比如 PopupWindow;系統(tǒng)彈窗:比如狀態(tài)欄、Toast等,本文所講的系統(tǒng)懸浮窗就是系統(tǒng)彈窗。
系統(tǒng)懸浮窗具體實(shí)現(xiàn)
權(quán)限申請
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
代碼設(shè)計
下面的包結(jié)構(gòu)截圖,簡單展示了實(shí)現(xiàn)系統(tǒng)懸浮窗的代碼結(jié)構(gòu),更復(fù)雜的業(yè)務(wù)需要可在此基礎(chǔ)上進(jìn)行擴(kuò)展。
FloatWindowService:系統(tǒng)懸浮窗在此 Service 中彈出;
FloatWindowManager:系統(tǒng)懸浮窗管理類;
FloatLayout:系統(tǒng)懸浮窗布局;
HomeKeyObserverReceiver:
監(jiān)聽 Home 鍵;
FloatWindowUtils:系統(tǒng)懸浮窗工具類。
具體實(shí)現(xiàn)
FloatWindowService 類
class FloatWindowService : Service() { private val TAG = FloatWindowService::class.java.simpleName private var mFloatWindowManager: FloatWindowManager? = null private var mHomeKeyObserverReceiver: HomeKeyObserverReceiver? = null override fun onCreate() { TLogUtils.i(TAG, "onCreate: ") mFloatWindowManager = FloatWindowManager(applicationContext) mHomeKeyObserverReceiver = HomeKeyObserverReceiver() registerReceiver(mHomeKeyObserverReceiver, IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) mFloatWindowManager!!.createWindow() } override fun onBind(intent: Intent?): IBinder? { return null } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { return START_NOT_STICKY } override fun onDestroy() { TLogUtils.i(TAG, "onDestroy: ") mFloatWindowManager?.removeWindow() if (mHomeKeyObserverReceiver != null) { unregisterReceiver(mHomeKeyObserverReceiver) } } }
FloatWindowManager 類
包括系統(tǒng)懸浮窗的創(chuàng)建、顯示、銷毀(以及更新)。
public void addView(View view, ViewGroup.LayoutParams params); // 添加 View 到 Window public void updateViewLayout(View view, ViewGroup.LayoutParams params); //更新 View 在 Window 中的位置 public void removeView(View view); //刪除 View
FloatWindowManager 類代碼
class FloatWindowManager constructor(context: Context) { var isShowing = false private val TAG = FloatWindowManager::class.java.simpleName private var mContext: Context = context private var mFloatLayout = FloatLayout(mContext) private var mLayoutParams: WindowManager.LayoutParams? = null private var mWindowManager: WindowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager fun createWindow() { TLogUtils.i(TAG, "createWindow: start...") // 對象配置操作使用apply,額外的處理使用also mLayoutParams = WindowManager.LayoutParams().apply { type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Android 8.0以后需要使用TYPE_APPLICATION_OVERLAY,不允許使用以下窗口類型來在其他應(yīng)用和窗口上方顯示提醒窗口:TYPE_PHONE、TYPE_PRIORITY_PHONE、TYPE_SYSTEM_ALERT、TYPE_SYSTEM_OVERLAY、TYPE_SYSTEM_ERROR。 WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY } else { // 在Android 8.0之前,懸浮窗口設(shè)置可以為TYPE_PHONE,這種類型是用于提供用戶交互操作的非應(yīng)用窗口。 // 在API Level = 23的時候,需要在Android Manifest.xml文件中聲明權(quán)限SYSTEM_ALERT_WINDOW才能在其他應(yīng)用上繪制控件 WindowManager.LayoutParams.TYPE_PHONE } // 設(shè)置圖片格式,效果為背景透明 format = PixelFormat.RGBA_8888 // 設(shè)置浮動窗口不可聚焦(實(shí)現(xiàn)操作除浮動窗口外的其他可見窗口的操作) flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE // 調(diào)整懸浮窗顯示的停靠位置為右側(cè)置頂 gravity = Gravity.TOP or Gravity.END width = 800 height = 200 x = 20 y = 40 } mWindowManager.addView(mFloatLayout, mLayoutParams) TLogUtils.i(TAG, "createWindow: end...") isShowing = true } fun showWindow() { TLogUtils.i(TAG, "showWindow: isShowing = $isShowing") if (!isShowing) { if (mLayoutParams == null) { createWindow() } else { mWindowManager.addView(mFloatLayout, mLayoutParams) isShowing = true } } } fun removeWindow() { TLogUtils.i(TAG, "removeWindow: isShowing = $isShowing") mWindowManager.removeView(mFloatLayout) isShowing = false } }
FloatLayout 類及其 Layout
系統(tǒng)懸浮窗自定義View:FloatLayout
class FloatLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, defStyleRes: Int = 0) : ConstraintLayout(context, attrs, defStyleAttr, defStyleRes) { private var mTime: TCLTextView private var mDistance: TCLTextView private var mSpeed: TCLTextView private var mCalories: TCLTextView init { val view = LayoutInflater.from(context).inflate(R.layout.do_exercise_view_float_layout, this, true) mTime = view.findViewById(R.id.float_layout_tv_time) mDistance = view.findViewById(R.id.float_layout_tv_distance) mSpeed = view.findViewById(R.id.float_layout_tv_speed) mCalories = view.findViewById(R.id.float_layout_tv_calories) } }
布局文件:float_layout_tv_time
HomeKeyObserverReceiver 類
class HomeKeyObserverReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { try { val action = intent!!.action val reason = intent.getStringExtra("reason") TLogUtils.d(TAG, "HomeKeyObserverReceiver: action = $action,reason = $reason") if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS == action && "homekey" == reason) { val keyCode = intent.getIntExtra("keycode", KeyEvent.KEYCODE_UNKNOWN) TLogUtils.d(TAG, "keyCode = $keyCode") context?.stopService(Intent(context, FloatWindowService::class.java)) } } catch (ex: Exception) { ex.printStackTrace() } } companion object { private val TAG = HomeKeyObserverReceiver::class.java.simpleName } }
FloatWindowUtils 類
object FloatWindowUtils { const val REQUEST_FLOAT_CODE = 1000 private val TAG = FloatWindowUtils::class.java.simpleName /** * 判斷Service是否開啟 */ fun isServiceRunning(context: Context, ServiceName: String): Boolean { if (TextUtils.isEmpty(ServiceName)) { return false } val myManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val runningService = myManager.getRunningServices(1000) as ArrayList<ActivityManager.RunningServiceInfo> runningService.forEach { if (it.service.className == ServiceName) { return true } } return false } /** * 檢查懸浮窗權(quán)限是否開啟 */ @SuppressLint("NewApi") fun checkSuspendedWindowPermission(context: Activity, block: () -> Unit) { if (commonROMPermissionCheck(context)) { block() } else { Toast.makeText(context, "請開啟懸浮窗權(quán)限", Toast.LENGTH_SHORT).show() context.startActivityForResult(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION).apply { data = Uri.parse("package:${context.packageName}") }, REQUEST_FLOAT_CODE) } } /** * 判斷懸浮窗權(quán)限權(quán)限 */ fun commonROMPermissionCheck(context: Context?): Boolean { var result = true if (Build.VERSION.SDK_INT >= 23) { try { val clazz: Class<*> = Settings::class.java val canDrawOverlays = clazz.getDeclaredMethod("canDrawOverlays", Context::class.java) result = canDrawOverlays.invoke(null, context) as Boolean } catch (e: Exception) { TLogUtils.e(TAG, e) } } return result } }
總結(jié)
本文并未詳細(xì)討論系統(tǒng)懸浮窗的拖動功能,實(shí)現(xiàn)系統(tǒng)懸浮穿基本功能可以總結(jié)為以下幾個步驟:
1. 聲明及申請權(quán)限;
2. 構(gòu)建懸浮窗需要的控件 Service、Receiver、Manager、Layout、Util;
3. 使用 WindowManager 創(chuàng)建、顯示、銷毀(以及更新)Layout。
原文鏈接:https://blog.csdn.net/Agg_bin/article/details/121913647
相關(guān)推薦
- 2022-03-08 android整數(shù)二分模板徹底解決邊界問題_Android
- 2022-04-16 Python實(shí)現(xiàn)杰卡德距離以及環(huán)比算法講解_python
- 2022-07-15 Python計算圖片數(shù)據(jù)集的均值方差示例詳解_python
- 2022-12-06 React運(yùn)行機(jī)制超詳細(xì)講解_React
- 2022-07-15 Python中else怎么用?else的用法總結(jié)_python
- 2023-07-24 el-table文字根據(jù)首字母排序
- 2023-03-03 AJAX亂碼與異步同步以及封裝jQuery庫實(shí)現(xiàn)步驟詳解_AJAX相關(guān)
- 2022-11-23 Python?copy()與deepcopy()方法之間有什么區(qū)別_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支