Skip to content

Instantly share code, notes, and snippets.

@miguelhincapie
Created April 4, 2020 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miguelhincapie/c80896756dd857c4bc38bc0db91e3420 to your computer and use it in GitHub Desktop.
Save miguelhincapie/c80896756dd857c4bc38bc0db91e3420 to your computer and use it in GitHub Desktop.
Decoupled Kotlin class which allows start or stop TalkBack service.
class TalkBackFacade @Inject constructor(private val contextWeakReference: WeakReference<Context>) {
fun isTalkBackEnabled() = Settings.Secure.getString(
contextWeakReference.get()?.contentResolver,
Settings.Secure.ACCESSIBILITY_ENABLED
)?.toInt()?.toBoolean()
?: false
fun enableTalkBack() = changeAccessibilityServicesState(
true,
TALK_BACK_SERVICE_NAME
)
fun disableTalkBack() = changeAccessibilityServicesState(
false,
TALK_BACK_SERVICE_NAME_DISABLED
)
private fun changeAccessibilityServicesState(
enable: Boolean,
accessibilityServiceName: String
): Boolean {
return try {
Settings.Secure.putString(
contextWeakReference.get()?.contentResolver,
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
accessibilityServiceName
)
Settings.Secure.putString(
contextWeakReference.get()?.contentResolver,
Settings.Secure.ACCESSIBILITY_ENABLED,
enable.intValue().toString()
)
true
} catch (e: SecurityException) {
Log.e("AccessibilityHelper", e.message.toString())
false
}
}
}
// Consants and ext functions moved here for easily access
private const val TALK_BACK_SERVICE_NAME = "com.google.android.marvin.talkback/.TalkBackService"
private const val TALK_BACK_SERVICE_NAME_DISABLED = ""
fun Int.toBoolean() = this == 1
fun Boolean.intValue() = if (this) 1 else 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment