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