I've been making an Android app that clears the Cache & Data of my application. Don't forget, my device is rooted. So why doesn't this piece of code work? It clearly has Root permissions and full paths. What's the problem behind this?
try {
Process p = Runtime.getRuntime().exec("su rm -r /data/user/0/com.rick.app");
p.waitFor();
p = Runtime.getRuntime().exec("su rm -r /data/user_de/0/com.rick.app");
p.waitFor();
p = Runtime.getRuntime().exec("su rm -r /storage/emulated/0/Android/data/com.rick.app");
p.waitFor();
p = Runtime.getRuntime().exec("su rm -r /data/data/com.rick.app");
p.waitFor();
p = Runtime.getRuntime().exec("su rm -r /data/app/com.rick.app");
p.waitFor();
p = Runtime.getRuntime().exec("su rm -r /storage/emulated/obb/com.rick.app");
p.waitFor();
p = Runtime.getRuntime().exec("su rm -r /storage/emulated/0/Android/data/com.rick.app/");
p.waitFor();
//p = Runtime.getRuntime().exec("reboot");
//p.waitFor();
//Runtime.getRuntime().exec("reboot");
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
CodePudding user response:
- The command is wrong you should use sudo instead of su
- Android has a lot of limitations! by default you can't use root commands with sudo! to do it you shou *ROOT your phone
- to delete and create files in android you should add specific permissions in manifest.xml file and get permission from user
- to create, edit and remive files you should use filling methods you can find theme here
CodePudding user response:
Generally if the command will fail you wont notice it because you dont check exit code and dont redirect the process output. Consider this code using the ProcessBuilder
Process process = new ProcessBuilder().inheritIO().command("sudo rm ...").start();
process.waitFor();
int exitCode = process.exitValue();
if (exitCode != 0) {
System.err.println("Delete failed with exit code " exitCode);
}
This way we can figure out what exactly happens here. As other pointed out java has also apis to delete files via File#delete or using nio Here is a snipped to delete it recursivly
Files.walk(Paths.get("/data/data/"))
.map(Path::toFile)
.sorted(Comparator.reverseOrder())
.forEach(File::delete);
In Kotlin you can even use File#deleteRecursively
I just wanted to mention that you can actually get the cache directory via context.cacheDir()