Executes multiple commands from a shell with root privileges. - Android Android OS

Android examples for Android OS:Root

Description

Executes multiple commands from a shell with root privileges.

Demo Code


//package com.java2s;
import android.util.Log;

import java.io.DataOutputStream;
import java.io.IOException;

import java.util.ArrayList;

public class Main {
    /**//from ww w  .jav a 2 s  .  c  om
     * Executes multiple commands from a shell with root privileges.
     * @param commands a list of commands to be executed.
     * @return true if the execution was successful, otherwise false
     */
    public static boolean executeMultiple(ArrayList<String> commands) {
        boolean retval = false;

        try {
            if (null != commands && commands.size() > 0) {
                Process suProcess = Runtime.getRuntime().exec("su");

                DataOutputStream os = new DataOutputStream(
                        suProcess.getOutputStream());

                // Execute commands that require root access
                for (String currCommand : commands) {
                    os.writeBytes(currCommand + "\n");
                    os.flush();
                    Log.d("SU", "Executed: " + currCommand);
                }

                os.writeBytes("exit\n");
                os.flush();

                try {
                    int suProcessRetval = suProcess.waitFor();
                    if (255 != suProcessRetval) {
                        // Root access granted
                        retval = true;
                    } else {
                        // Root access denied
                        retval = false;
                    }
                } catch (Exception ex) {
                    Log.e("ROOT", "Error executing root action", ex);
                }
            }
        } catch (IOException ex) {
            Log.w("ROOT", "Can't get root access", ex);
        } catch (SecurityException ex) {
            Log.w("ROOT", "Can't get root access", ex);
        } catch (Exception ex) {
            Log.w("ROOT", "Error executing internal operation", ex);
        }

        return retval;
    }
}

Related Tutorials