Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FannyDemey/a49c35ff3f864ca5edd5240c24a0d034 to your computer and use it in GitHub Desktop.
Save FannyDemey/a49c35ff3f864ca5edd5240c24a0d034 to your computer and use it in GitHub Desktop.
CustomLocalAccessibilityManager
import android.content.Context
import android.os.Build
import androidx.annotation.DoNotInline
import androidx.annotation.RequiresApi
import androidx.compose.ui.platform.AccessibilityManager
class AndroidAccessibilityManager(context: Context) : AccessibilityManager {
private companion object {
const val FlagContentIcons = 1
const val FlagContentText = 2
const val FlagContentControls = 4
}
private val accessibilityManager = context.getSystemService(Context.ACCESSIBILITY_SERVICE) as
android.view.accessibility.AccessibilityManager
override fun calculateRecommendedTimeoutMillis(
originalTimeoutMillis: Long,
containsIcons: Boolean,
containsText: Boolean,
containsControls: Boolean,
): Long {
if (originalTimeoutMillis >= Int.MAX_VALUE) {
return originalTimeoutMillis
}
var uiContentFlags = 0
if (containsIcons) {
uiContentFlags = uiContentFlags or FlagContentIcons
}
if (containsText) {
uiContentFlags = uiContentFlags or FlagContentText
}
if (containsControls) {
uiContentFlags = uiContentFlags or FlagContentControls
}
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val recommended = Api29Impl.getRecommendedTimeoutMillis(
accessibilityManager,
originalTimeoutMillis.toInt(),
uiContentFlags,
)
if (recommended == Int.MAX_VALUE) {
Long.MAX_VALUE
} else {
recommended.toLong()
}
} else if (containsControls && accessibilityManager.isTouchExplorationEnabled) {
Long.MAX_VALUE
} else {
originalTimeoutMillis
}
}
fun isTalkbackEnabled(): Boolean {
return accessibilityManager.isEnabled && accessibilityManager.isTouchExplorationEnabled
}
}
@RequiresApi(Build.VERSION_CODES.Q)
internal object Api29Impl {
@DoNotInline
fun getRecommendedTimeoutMillis(
accessibilityManager: android.view.accessibility.AccessibilityManager,
originalTimeout: Int,
uiContentFlags: Int,
): Int {
return accessibilityManager.getRecommendedTimeoutMillis(originalTimeout, uiContentFlags)
}
}
val CustomLocalAccessibilityManager = staticCompositionLocalOf<AndroidAccessibilityManager?> { null }
@Composable
fun DemoCompositionLocalAccessibility() {
Column() {
CompositionLocalProvider(
CustomLocalAccessibilityManager provides AndroidAccessibilityManager(LocalContext.current),
) {
Column {
Text("Texte 1")
if (CustomLocalAccessibilityManager.current?.isTalkbackEnabled() == true) {
Text("Talkback enabled")
} else {
Text("No")
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment