Last active
July 30, 2021 08:09
-
-
Save piekie/8b058f2147e5e298710b30f86e2bcfc7 to your computer and use it in GitHub Desktop.
Utils : Kill and Force-Stop functions for android app.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing this. I want to draw your attention that this part is not reliable: