Killing Current Foreground App With ADB
Recently I've been working on an Android project that used the lock task mode. This mode can be used to set up a single-purpose Android device with your own kiosk app where the user is not allowed to exit your application. Home and back buttons have basically no effect.
When I was testing this kind of application I found it useful to kill the app with the help of ADB through a simple shell script. To kill the currently running foreground app you basically have to perform 2 steps
- Find the package name of the current foreground app
- Kill the app
Finding the Name of Current Foreground App
When you type in the following commands
adb shell dumpsys window windows | grep mCurrentFocus
you get something like this
mCurrentFocus=Window{84db45e u0 eu.sisik.apktools/eu.sisik.apktools.ApkListActivity}
From the output you can see that in my case the package name of the foreground app was eu.sisik.apktools.
Killing App With ADB
To kill(stop) an application package you can use the am command line tool
adb shell am force-stop eu.sisik.apktools
This will close the specified app.
Bringing It All Together
To force-stop only the current foreground app you can use the following script
package=`adb shell dumpsys window windows | grep mCurrentFocus | grep -oP '(?<=\s).\S*?(?=/)'`
adb shell am force-stop $package
It could certainly be written in a more simple way, but this is what I came up with and it works. In the first line I try to get the foreground package name. I do this in two steps. First I grep the line with mCurrentFocus. Then I extract the substring that starts with a space, contains no spaces, and ends with a slash (/). Then I just force-stop the package stored in the variable from the first line.
Using Bugjaeger to Kill Current Foreground App
I implemented this feature in my own app - Bugjaeger. You can find it in the Commands tab. Once you connect the target device with USB OTG cable, enable the developer options, and authorize the device (basically the same procedure as when connecting Android device to your PC), you can just tap on the play button next to Kill current foreground process.