kolyaseg kolyaseg - 4 months ago 18
Android Question

Can't execute more than one shell command at a time

I need to set permissions for a file and its folder. Both are in /data/ folder on internal storage. The only way my app can do that is:

String[] cmd = { "su", "-c", "chmod 777 " + myakDB.getParentFile().getPath()};
Process process = Runtime.getRuntime().exec(cmd);
process.waitFor();

cmd = new String[] { "su", "-c", "chmod 666 " + myakDB.getPath() };
process = Runtime.getRuntime().exec(cmd);
process.waitFor();


Thus it asks the Superuser two times for permission. This is unwanted behaviour i guess for my app's users. So searching the same problem over the internet gave me the following solution (using stream):

Process process = Runtime.getRuntime().exec("su");
DataOutputStream out = new DataOutputStream(process.getOutputStream());
out.writeBytes("chmod 777 " + myakDB.getParentFile().getPath());
out.writeBytes("chmod 666 " + myakDB.getPath());
out.writeBytes("exit\n");
out.flush();


But it doesn't work. Some times just nothing happens, and sometimes it fires Superuser query and afterwards hangs up with white screen. So what's wrong with my process?

Answer

You need to add a new line after each command:

Process process = Runtime.getRuntime().exec("su");
DataOutputStream out = new DataOutputStream(process.getOutputStream());
out.writeBytes("chmod 777 " + myakDB.getParentFile().getPath() + "\n");
out.writeBytes("chmod 666 " + myakDB.getPath() + "\n");
out.writeBytes("exit\n");
out.flush();