fix(haptics): вибра не глушится legacy-ключом системы

ColorOS держит haptic_feedback_enabled=0 при живом виброотклике -
ручной гейт убивал вибру во всём приложении. С API 33 фильтрует
платформа по USAGE_TOUCH, ниже - legacy-ключ как раньше.
This commit is contained in:
samosvalishe committed 2026-07-29 03:03:11 +03:00
1 parent 77084151f6
commit e90c5f6770
1 file changed
+31 -10
@@ -1,10 +1,13 @@
package com.freeturn.app.data
import android.content.Context
import android.media.AudioAttributes
import android.os.Build
import android.os.VibrationAttributes
import android.os.VibrationEffect
import android.os.Vibrator
import android.provider.Settings
import androidx.annotation.RequiresApi
object HapticUtil {
@@ -20,14 +23,9 @@ object HapticUtil {
@Suppress("DEPRECATION")
fun perform(context: Context, pattern: Pattern) {
// Прямой Vibrator игнорирует системный "Виброотклик при касании" -
// проверяем настройку сами (performHapticFeedback здесь не подходит: нет View).
val hapticsEnabled = try {
Settings.System.getInt(
context.contentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED, 1
) == 1
} catch (_: Exception) { true }
if (!hapticsEnabled) return
// С API 33 системный "Виброотклик при касании" применяется к USAGE_TOUCH самой платформой.
// Ниже - читаем legacy-ключ сами (на этих версиях он ещё авторитетный).
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU && !legacyHapticsEnabled(context)) return
val vibrator = context.getSystemService(Vibrator::class.java) ?: return
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val effect = when (pattern) {
@@ -81,7 +79,13 @@ object HapticUtil {
-1
)
}
try { vibrator.vibrate(effect) } catch (_: Exception) {}
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
vibrator.vibrate(effect, touchAttrs())
} else {
vibrator.vibrate(effect, legacyTouchAttrs())
}
} catch (_: Exception) {}
} else {
val duration = when (pattern) {
Pattern.SELECTION -> 20L
@@ -91,7 +95,24 @@ object HapticUtil {
Pattern.ERROR -> 100L
Pattern.LAUNCH -> 70L
}
try { vibrator.vibrate(duration) } catch (_: Exception) {}
try { vibrator.vibrate(duration, legacyTouchAttrs()) } catch (_: Exception) {}
}
}
@Suppress("DEPRECATION")
private fun legacyHapticsEnabled(context: Context): Boolean = try {
Settings.System.getInt(
context.contentResolver, Settings.System.HAPTIC_FEEDBACK_ENABLED, 1
) == 1
} catch (_: Exception) { true }
// Без атрибутов вибра уходит как USAGE_UNKNOWN - часть OEM-прошивок режет её вместе с фоновыми.
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private fun touchAttrs(): VibrationAttributes =
VibrationAttributes.createForUsage(VibrationAttributes.USAGE_TOUCH)
private fun legacyTouchAttrs(): AudioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
}