Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close an Android app using UiAutomator?

How can I close an especific Android app using UiAutomator API? Like when you manually press the Recents button and swipe the app you want to close.

like image 547
Marcelo Avatar asked Oct 02 '14 12:10

Marcelo


People also ask

Can UIAutomator app access other apps?

It is possible to run UiAutomator from an application, you just need to have your Test jar on the device and give your application su permissions. And your device will perform whatever your UiAutomatorTestCase would perform.

How do you use the UIAutomator in Appium?

If you go to android SDK>tools>UIAutomator. Make sure device is connected, tap on green button on top left side. This will take the screenshot of your current screen on the device. This way you can point mouse on the screen to detect elements.

How do you inspect element with UIAutomator?

Q #12) How do you inspect an element in UIAutomator? Answer: Once you are done with the setup, open a command prompt, and enter the command UIAutomatorViewer. A window will be displayed on your PC. Connect the mobile to a PC and click on the Device screenshot (uiautomator dump) second icon at the top.


2 Answers

Better way (not device, OS version, UI or orientation specific):

Runtime.getRuntime().exec(new String[] {"am", "force-stop", "pkg.name.of.your.app"});

Tested and working on a Nexus 5X with android 6.0

like image 137
Tolstoyevsky Avatar answered Oct 06 '22 11:10

Tolstoyevsky


This is how I kill all android apps at once with uiautomator:

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();
    }
}
like image 24
user597159 Avatar answered Oct 06 '22 11:10

user597159