run As Root - Android Android OS

Android examples for Android OS:Shell

Description

run As Root

Demo Code

/******************************************************************************
 *  DroidTV, live TV on Android devices with host USB port and a DVB tuner    *
 *  Copyright (C) 2012  Christian Ulrich <chrulri@gmail.com>                  *
 *                                                                            *
 *  This program is free software: you can redistribute it and/or modify      *
 *  it under the terms of the GNU General Public License as published by      *
 *  the Free Software Foundation, either version 3 of the License, or         *
 *  (at your option) any later version.                                       *
 *                                                                            *
 *  This program is distributed in the hope that it will be useful,           *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
 *  GNU General Public License for more details.                              *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.     *
 ******************************************************************************/
//package com.java2s;

import java.io.DataOutputStream;
import java.io.File;

import java.io.IOException;

public class Main {
    public static Process runAsRoot(String... args) throws IOException {
        if (args == null || args.length == 0)
            return null;
        Process su = run("su");
        DataOutputStream out = new DataOutputStream(su.getOutputStream());
        for (String arg : args) {
            out.writeBytes(" ");
            out.writeBytes(arg);//from  www .  j ava 2 s  . c o m
        }
        out.writeBytes("\n");
        out.writeBytes("exit\n");
        out.flush();
        return su;
    }

    public static Process run(String executable, String... args)
            throws IOException {
        return run(executable, null, null, args);
    }

    public static Process run(String executable, File workingDirectory,
            String[] envp, String... args) throws IOException {
        if (args.length > 0) {
            String[] pargs = new String[args.length + 1];
            System.arraycopy(args, 0, pargs, 1, args.length);
            pargs[0] = executable;
            args = pargs;
        } else {
            args = new String[] { executable };
        }
        return Runtime.getRuntime().exec(args, envp, workingDirectory);
    }
}

Related Tutorials