本质上我只是在寻找相当于https://developer.apple.com/documentation/xctest/xcuiapplication/1500637-terminate与https://developer.apple.com/documentation/xctest/xcuiapplication/相结合1500467-启动.
我正在 Android 中编写一个工具测试,其中我想关闭整个应用程序,然后再次启动它,以检查重新启动应用程序时的流程是否正确,就像现实生活中经常发生的那样。但是我无法让它工作。我有这行代码:
@get:Rule
val app = createAndroidComposeRule<MainActivity>()
要关闭应用程序,我尝试使用以下方法:
val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
device.pressRecentApps()
val displayWidth = device.displayWidth
val displayHeight = device.displayHeight
val startX = displayWidth / 2
val startY = (displayHeight * 0.6).toInt() // Start from 80% of the screen height
val endY = (displayHeight * 0.2).toInt() // End at 20% of the screen height
delay(500L)
device.swipe(startX, startY, startX, endY, 3)
这看起来像是关闭应用程序,但从测试来看,它仍然将应用程序保留在内存中。当我使用此代码时,我注意到另一个应用程序已启动,但在现有应用程序旁边,因为它未关闭:
val context = InstrumentationRegistry.getInstrumentation().context
val intent = context.packageManager.getLaunchIntentForPackage(packageName)!!
// From ChatGPT
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_CLEAR_TASK) // Clear the task stack
context.startActivity(intent)
为新应用程序执行代码,但 UI 仍然来自旧应用程序。这可能是因为我正在使用
app
变量来做事情。我尝试分配一个新的 app
变量,但随后出现错误,因为它未设置。
如何重新启动应用程序的新实例?
我认为你最好的选择实际上是通过 adb 命令来完成此操作。您可以使用 UiAutomation.executeShellCommand 方法,该方法可从 API 21 获得:
fun adbCommand(cmd: String) {
if (Build.VERSION.SDK_INT < 21) {
return
}
val automation = InstrumentationRegistry.getInstrumentation().uiAutomation
val pfd = automation.executeShellCommand(cmd)
try {
FileInputStream(pfd.fileDescriptor).readBytes()
} catch (e: Throwable) {
// ignored
}
pfd.close()
}
然后像这样使用它来杀死并重新启动应用程序:
adbCommand("am force-stop com.package.name")
adbCommand("am start -n com.package.name/com.package.name.MainActivity")
或者尝试通过模拟按下主页按钮来关闭应用程序。尝试将应用程序发送到后台以确保其在重新启动之前已关闭。
val设备= UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) device.pressHome()
然后使用新实例重新启动应用程序,您可以使用 Intent 来启动应用程序的主要活动。等待一段时间然后重新初始化UI测试