如何检测Android Auto导航屏幕从全屏到多窗口模式的切换?
检测Android Auto导航从全屏切换至分屏模式的方法
方法1:监听窗口布局变化(通用Android方式)
在导航页面的根View上添加布局变化监听,通过对比窗口尺寸判断模式切换:
rootView.addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom -> val currentWidth = right - left val currentHeight = bottom - top val screenWidth = resources.displayMetrics.widthPixels val screenHeight = resources.displayMetrics.heightPixels val isFullScreen = currentWidth == screenWidth && currentHeight == screenHeight val wasFullScreen = (oldRight - oldLeft) == screenWidth && (oldBottom - oldTop) == screenHeight if (wasFullScreen && !isFullScreen) { // 从全屏切换到分屏,执行对应逻辑 } else if (!wasFullScreen && isFullScreen) { // 从分屏切换回全屏,执行对应逻辑 } }
方法2:使用Android Auto专属的CarAppFocusManager(推荐)
利用Android Auto提供的服务直接监听窗口模式状态:
val carContext = getCarContext() val carAppFocusManager = carContext.getCarService(CarAppFocusManager::class.java) val focusListener = object : CarAppFocusManager.OnAppFocusChangedListener { override fun onAppFocusChanged(appFocus: Int, zone: Int) { val isMultiWindow = carAppFocusManager.isMultiWindowMode if (isMultiWindow) { // 当前处于分屏模式 } else { // 当前处于全屏模式 } } } // 注册监听 carAppFocusManager.addOnAppFocusChangedListener(focusListener) // 页面销毁时移除监听 override fun onDestroy() { super.onDestroy() carAppFocusManager.removeOnAppFocusChangedListener(focusListener) }
方法3:重写onConfigurationChanged监听配置变化
当窗口模式切换时,系统会触发配置变更回调,可在此判断多窗口状态:
override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) val isMultiWindowMode = newConfig.windowConfiguration.windowingMode == WindowConfiguration.WINDOWING_MODE_MULTI_WINDOW if (isMultiWindowMode) { // 进入分屏模式 } else { // 回到全屏模式 } }
注意:使用此方法需在Manifest的Activity标签中添加配置变更声明:
<activity android:name=".YourNavigationActivity" android:configChanges="screenSize|smallestScreenSize|screenLayout|orientation" />
内容的提问来源于stack exchange,提问作者Javier
相关产品推荐
相关产品推荐

