如何使用UiAutomator API关闭特定的Android应用?就像当您手动按下“最近”按钮并滑动要关闭的应用程序一样。
最好的选择是使用getUiDevice.pressRecentApps,这将为您加载最近的应用程序,然后使用uiautomator查看器截取屏幕截图,您可以查看已加载的屏幕的xml。然后,您可以使用此xml选择要使用的对象
UiObject app = new UIObject(new UiSelector().resourceId("The id of the app");
app.swipeLeft(100);
或者是对的
这应该可以关闭你的应用程序。 xml将取决于您使用的Android风格和设备。
更好的方式(不是设备,操作系统版本,UI或特定方向):
Runtime.getRuntime().exec(new String[] {"am", "force-stop", "pkg.name.of.your.app"});
测试和使用Android 6.0的Nexus 5X
当它只是一个将在最近的应用程序列表中的应用程序时,这对我有用。
if(mDevice.pressRecentApps()) {
Thread.sleep(1000);
int startX = 300; int startY =835; int endX = 1000; int endY = 835; // co-ordinates refer to x-axis from left of screen to right.
int steps = 8;// speed at which the app closes
mDevice.swipe(startX,startY,endX,endY,steps);
}
这是我用uiautomator一次性杀死所有Android应用程序的方法:
public static void killApps()
{
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
try
{
device.pressHome();
device.pressRecentApps();
// Clear all isn't always visible unless you scroll all apps down
int height = device.getDisplayHeight();
int width = device.getDisplayWidth();
device.swipe(width/2,height/2, width/2, height, 50);
UiObject clear = device.findObject(new UiSelector()
.resourceId("com.android.systemui:id/button")
.text("CLEAR ALL")
);
if (clear.exists())
{
clear.click();
}
}
catch (RemoteException e)
{
e.printStackTrace();
}
catch (UiObjectNotFoundException e)
{
e.printStackTrace();
}
}
在@ user597159的解决方案的基础上,我得到以下内容来关闭Pixel 2 for Firebase测试实验室的所有应用程序(即“walleye”设备类型):
private void killAllApps() throws Exception {
boolean keepSwiping = true;
int maxSwipeAttempts = 10;
for (int swipeAttempt=0; swipeAttempt<maxSwipeAttempts && keepSwiping; swipeAttempt++) {
int height = uiDevice.getDisplayHeight();
int width = uiDevice.getDisplayWidth();
uiDevice.swipe(width / 2, height / 2, width, height / 2, 50);
UiObject clearAll1 = uiDevice.findObject(new UiSelector().text("Clear all"));
UiObject clearAll2 = uiDevice.findObject(new UiSelector().textStartsWith("Clear all"));
UiObject clearAll3 = uiDevice.findObject(new UiSelector().textContains("Clear all"));
UiObject clear = clearAll1.exists() ? clearAll1 :
(clearAll2.exists() ? clearAll2 : clearAll3);
if (clear.exists()) {
Logger.debug(TAG, "Attempting to close app by killAllApps and found clear=all button on swipeAttempt=" + swipeAttempt);
clear.click();
keepSwiping = false;
} else {
Logger.debug(TAG, "Attempting to close app by killAllApps but have to keep swiping swipeAttempt=" + swipeAttempt);
keepSwiping = true;
}
}
}
关于像素2的注释,拼写为“全部清除”而不是“全部清除”。
我无法获得其他一些解决方案。我得到了UiObjectNotFoundException
以下内容:
app = uiDevice.findObject(new UiSelector().textContains("SDK Test App"));
还有:
app = uiDevice.findObject(new UiSelector().className(com.locuslabs.android.sdk.SdkTestApplication.class));
换句话说,app.exists()
为这些尝试在应用上向上滑动以关闭Pixel 2的方法返回false。