Skip to content

Instantly share code, notes, and snippets.

@hvisser
Created January 23, 2018 11:44
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hvisser/e716105f4e3cf2908ea463dbdb50679c to your computer and use it in GitHub Desktop.
Save hvisser/e716105f4e3cf2908ea463dbdb50679c to your computer and use it in GitHub Desktop.
Enables demo mode on a device for the purpose of taking screenshots
class DemoModeEnabler {
fun enable() {
executeShellCommand("settings put global sysui_demo_allowed 1")
sendCommand("exit")
sendCommand("enter")
sendCommand("notifications", "visible" to "false")
sendCommand("network", "wifi" to "hide")
sendCommand("battery", "level" to "100", "plugged" to "false")
sendCommand("clock", "hhmm" to "1000")
}
fun disable() {
sendCommand("exit")
}
private fun sendCommand(command: String, vararg extras: Pair<String, Any>) {
val exec = StringBuilder("am broadcast -a com.android.systemui.demo -e command $command")
for ((key, value) in extras) {
exec.append(" -e $key $value")
}
executeShellCommand(exec.toString())
}
private fun executeShellCommand(command: String) {
waitForCompletion(InstrumentationRegistry.getInstrumentation().uiAutomation.executeShellCommand(command))
}
private fun waitForCompletion(descriptor: ParcelFileDescriptor) {
val reader = BufferedReader(InputStreamReader(ParcelFileDescriptor.AutoCloseInputStream(descriptor)))
reader.use {
it.readText()
}
}
}
class DemoModeRule: TestRule {
private val helper = DemoModeEnabler()
override fun apply(base: Statement, description: Description): Statement {
return DemoModeStatement(base)
}
private inner class DemoModeStatement(private val base: Statement) : Statement() {
override fun evaluate() {
helper.enable()
base.evaluate()
helper.disable()
}
}
}
@Sloy
Copy link

Sloy commented Feb 12, 2018

Thanks for the code!
Just a tip: better to wrap the rule in a try/finally, to disable it in case a test fail also.

helper.enable()
try{
  base.evaluate()
}finally {
  helper.disable()
}

@JorisPotier
Copy link

Hi @hvisser, is it working for non rooted device?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment