1

I am trying to execute commands from my android app, in order to configure some aspects of my device by code. For example, I am trying to lock my device using this code (from a class that extends the class MainActivity):

Process p=Runtime.getRuntime().exec("su");
DataOutputStream dos = new DataOutputStream(p.getOutputStream());
dos.writeBytes("adb shell input keyevent 26");
dos.writeBytes("exit\n");
dos.flush();
dos.close();
p.waitFor();

When I run it, I receive:

java.io.Exception: Error running exec(). Command: [su] Working directory: null Environment: null

My device is not rooted. I have tried others ways to do that, but have been unsuccessful.

Any idea?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Angel C
  • 31
  • 4

2 Answers2

0

I don't think that you can do this without rooting your app. So, try to do this on a rooted device.

Once rooted you can try checking root permissions and then perform these tasks.

To check root permissions as mentioned here:

 public boolean isRooted() {
    // get from build info
    String buildTags = android.os.Build.TAGS;
    if (buildTags != null && buildTags.contains("test-keys")) {
        return true;
    }
    // check if /system/app/Superuser.apk is present
    try {
        File file = new File("/system/app/Superuser.apk");
        if (file.exists()) {
            return true;
        }
    } catch (Exception exception) {
        // ignore
        exception.printStackTrace();
    }
    String[] commands = {
            "/system/xbin/which su",
            "/system/bin/which su",
            "which su"
    };
    for (String command : commands) {
        try {
            Runtime.getRuntime().exec(command);
            return true;
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    Log.d("message-startUp: ", "RootUtil");
    return false;
}
  • I have done a test with a rooted device and at least, it ask for root permission to execute the command. I don't know if it is for the "su" explicit in my command. Is there a list of commands that can be executed in unrooted devices? – Angel C May 22 '18 at 08:26
0

I have gotten the null working directory error several times and it has always been an issue with my command. Try this:

Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c", "input keyevent 26"});
proc.waitFor();

This should at least solve the 'null Environment' error.

Jeff.H
  • 403
  • 4
  • 14