Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggling Android Device Network During Execution of an Instrumentation Test

Has anyone had any luck toggling the device network in the middle of an instrumentation test? I've found some hacky outdated solutions that are no longer supported such as this one.

I can't seem to find any recent answers to this problem. I'm sure this is a common testing scenario for many applications. Thanks in advance!

like image 683
John A Qualls Avatar asked Nov 26 '25 06:11

John A Qualls


1 Answers

Alright, below is a solution that I came up with to enable/disable the network during an instrumented test. Thank you for the reference to UiAutomator Sandi!

fun clickAirplaneMode(instrumentation: Instrumentation, targetContext: Context) {
    UiDevice.getInstance(instrumentation).run {
        targetContext.packageManager.getLaunchIntentForPackage("com.android.settings")?.let {intent ->
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
            targetContext.startActivity(intent)
            findObject(UiSelector().textContains("Network")).clickAndWaitForNewWindow()
            findObject(UiSelector().textContains("Airplane")).click()
        }
    }
}
like image 129
John A Qualls Avatar answered Nov 27 '25 20:11

John A Qualls



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!