Android SU permission from application

Hi,

I need to execute su commands from my application.

I tried execSuCmd from KhadasApi with no luck. Then I tried Runtime.getRuntime().exec(), no luck either…

The main issue seems to be from SELinux (avc).

Do you have any solution for this behavior ? I don’t want to use Magisk as the user does not have physical access to the board and recompiling the Android system image should be the last solution.

I have the latest Android firmware VIM3_Pie_V210908 and I sign my apk with my own jks.

Regards,

public static String exec(String command) {

    Process process = null;
    BufferedReader reader = null;
    InputStreamReader is = null;
    DataOutputStream os = null;

    try {
        process = Runtime.getRuntime().exec("su");
        is = new InputStreamReader(process.getInputStream());
        reader = new BufferedReader(is);
        os = new DataOutputStream(process.getOutputStream());
        os.writeBytes(command + "\n");
        os.writeBytes("exit\n");
        os.flush();
        int read;
        char[] buffer = new char[4096];
        StringBuilder output = new StringBuilder();
        while ((read = reader.read(buffer)) > 0) {
            output.append(buffer, 0, read);
        }
        process.waitFor();
        return output.toString();
    } catch (IOException | InterruptedException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (os != null) {
                os.close();
            }

            if (reader != null) {
                reader.close();
            }

            if (is != null) {
                is.close();
            }

            if (process != null) {
                process.destroy();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

exec(“chmod 777 /data”);
this is my usage,you can try again

1 Like

Your code is working.

Thanks.