Android 13及以上系统如何检查全局触觉反馈是否开启?
Android 全局触觉反馈状态读取的版本适配方案
在Android 12及以下版本中,我们可以通过Settings.System.HAPTIC_FEEDBACK_ENABLED直接读取全局触觉反馈的开启状态,但Android 13(API 33)开始该字段被弃用,需改用基于振动使用场景的API来实现。
完整适配代码
import android.content.Context import android.os.Build import android.os.VibrationAttributes import android.os.VibrationManager import android.provider.Settings val Context.hapticEnabled: Boolean get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { val vibrationManager = getSystemService(VibrationManager::class.java) val setting = vibrationManager.getVibrationSettings(VibrationAttributes.USAGE_TOUCH) setting == VibrationManager.VIBRATION_SETTING_ON } else { @Suppress("DEPRECATION") Settings.System.getInt(contentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED) == 1 }
代码说明
- Android 13+ 实现:通过
VibrationManager的getVibrationSettings方法,传入VibrationAttributes.USAGE_TOUCH(对应触摸交互的触觉反馈场景),判断返回值是否为VIBRATION_SETTING_ON来确认触觉反馈是否开启。 - 旧版本兼容:保留原有的
Settings.System读取逻辑,添加@Suppress("DEPRECATION")注解消除弃用警告。
内容的提问来源于stack exchange,提问作者Dmitry Semenov
相关产品推荐
相关产品推荐

