Skip to content

Instantly share code, notes, and snippets.

@piekie
Last active July 30, 2021 08:09
Show Gist options
  • Save piekie/8b058f2147e5e298710b30f86e2bcfc7 to your computer and use it in GitHub Desktop.
Save piekie/8b058f2147e5e298710b30f86e2bcfc7 to your computer and use it in GitHub Desktop.
Utils : Kill and Force-Stop functions for android app.
public class RootUtils {
private static Process su;
public static void gainRoot() {
try {
su = Runtime.getRuntime().exec("su");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void forceStop(String packageName) {
try {
DataOutputStream stream = new DataOutputStream(su.getOutputStream());
stream.writeBytes("adb shell" + "\n");
stream.flush();
stream.writeBytes("am force-stop " + packageName + "\n");
stream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void captureScreen(String path) {
DataOutputStream os = new DataOutputStream(su.getOutputStream());
try {
os.writeBytes("adb shell" + "\n");
os.flush();
os.writeBytes("screencap -p " + path + ".png\n");
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void kill(String packageName) {
try {
DataOutputStream stream = new DataOutputStream(su.getOutputStream());
stream.writeBytes("adb shell" + "\n");
stream.flush();
stream.writeBytes("am kill " + packageName + "\n");
stream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean isRooted() {
boolean retval = false;
Process suProcess;
try {
if (su == null) {
su = Runtime.getRuntime().exec("su");
}
DataOutputStream os = new DataOutputStream(su.getOutputStream());
DataInputStream osRes = new DataInputStream(su.getInputStream());
if (null != os && null != osRes) {
// Getting the id of the current user to check if this is root
os.writeBytes("id\n");
os.flush();
String currUid = osRes.readLine();
if (null == currUid) {
retval = false;
Log.d("ROOT", "Can't get root access or denied by user");
} else if (currUid.contains("uid=0")) {
retval = true;
Log.d("ROOT", "Root access granted");
} else {
retval = false;
Log.d("ROOT", "Root access rejected: " + currUid);
}
}
} catch (Exception e) {
// Can't get root !
// Probably broken pipe exception on trying to write to output stream (os) after su failed, meaning that the device is not rooted
retval = false;
Log.d("ROOT", "Root access rejected [" + e.getClass().getName() + "] : " + e.getMessage());
}
return retval;
}
}
@acrolink
Copy link

Thanks for sharing this. I want to draw your attention that this part is not reliable:

 public static boolean isRooted() {
        boolean retval = false;
        Process suProcess;

        try {
            if (su == null) {
                su = Runtime.getRuntime().exec("su"); // this, I had to take it out of *if* condition i.e. to re-acquire the runtime always.
            }
...
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment