3

I'm trying to get if haptic feedback enabled in System Settings, i.e. globally on a device. I don't need to set this setting, just read.

We do it this way on Android 12 or lower:

Settings.System.getInt(context.contentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED) == 1

But with the release of Android 13 Google deprecated flag HAPTIC_FEEDBACK_ENABLED. Now it recommended to use android.os.VibrationAttributes.USAGE_TOUCH. It's really incomprehensible how to use it.

I need something like this:

 val hapticEnabled: Boolean
     get() = if (BuildConfig.VERSION_CODE >= Build.VERSION_CODES.TIRAMISU) {
         // here what I'm trying to find out
     } else {
         Settings.System.getInt(context.contentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED) == 1
     }

1 Answers1

0

In the new Android Version (13 or higher) you can use VibrationManager to check this, please check below:

val hapticEnabled: Boolean
    get() {
        return if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            val vibratorManager = requireContext()
                .getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
            val vibrator = vibratorManager.defaultVibrator

            vibrator.hasVibrator()
        } else {
            Settings.System.getInt(requireContext().contentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED) == 1
        }
    }
Gustavo Ross
  • 399
  • 3
  • 7
  • 1
    With vibrator.hasVibrator() I can check if the hardware as a vibrator, not if the haptic feedback enabled in system settings. – Dmitry Semenov Mar 09 '23 at 18:40
  • For the older phone check, you'll want to use the convenience method (provides default value) `Settings.System.getInt(requireContext().contentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) == 1)` to handle phones that don't have this setting without throwing an exception. – jt-gilkeson May 01 '23 at 19:36