1 package host.exp.exponent.utils
2 
3 import android.content.Intent
4 import android.net.Uri
5 import android.provider.Settings
6 import android.widget.Switch
7 import androidx.test.InstrumentationRegistry
8 import androidx.test.uiautomator.*
9 
10 private const val LAUNCH_TIMEOUT = 5000
11 
12 object DeviceUtils {
allowDrawingOverOtherAppsnull13   fun allowDrawingOverOtherApps(uiDevice: UiDevice) {
14     // Start from the home screen
15     uiDevice.pressHome()
16 
17     // Wait for launcher
18     val launcherPackage = uiDevice.launcherPackageName
19     uiDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT.toLong())
20 
21     val context = InstrumentationRegistry.getContext()
22     // Enable draw over other apps if necessary
23     if (!Settings.canDrawOverlays(context)) {
24       // Open settings
25       val intent =
26         Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:host.exp.exponent"))
27       intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
28       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
29       context.startActivity(intent)
30 
31       // Wait for the app to appear
32       uiDevice.wait(
33         Until.hasObject(By.textContains("Permit drawing over other apps")),
34         LAUNCH_TIMEOUT.toLong()
35       )
36       val switchObject = uiDevice.findObject(UiSelector().className(Switch::class.java.name))
37       try {
38         if (!switchObject.isChecked) {
39           switchObject.click()
40         }
41       } catch (e: UiObjectNotFoundException) {
42         e.printStackTrace()
43       }
44     }
45   }
46 }
47