Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.util.ArrayList;

import android.util.Log;

public class Main {
    private static String TAG = "Utilities";

    public static String runCommand(String[] commands) {
        DataOutputStream outStream = null;
        DataInputStream responseStream;
        try {
            ArrayList<String> logs = new ArrayList<String>();
            Process process = Runtime.getRuntime().exec("su");
            Log.i(TAG, "Executed su");
            outStream = new DataOutputStream(process.getOutputStream());
            responseStream = new DataInputStream(process.getInputStream());

            for (String single : commands) {
                Log.i(TAG, "Command = " + single);
                outStream.writeBytes(single + "\n");
                outStream.flush();
                if (responseStream.available() > 0) {
                    Log.i(TAG, "Reading response");
                    logs.add(responseStream.readLine());
                    Log.i(TAG, "Read response");
                } else {
                    Log.i(TAG, "No response available");
                }
            }
            outStream.writeBytes("exit\n");
            outStream.flush();
            String log = "";
            for (int i = 0; i < logs.size(); i++) {
                log += logs.get(i) + "\n";
            }
            Log.i(TAG, "Execution compeleted");
            return log;
        } catch (IOException e) {
            Log.d(TAG, e.getMessage());
        }
        return null;
    }

    public static int exec(String command) {
        Process proc = null;
        BufferedReader error = null;
        try {
            proc = Runtime.getRuntime().exec(command);
            error = toReader(proc.getErrorStream());
            int retVal = proc.waitFor();
            if (retVal != 0) {
                String line;
                while ((line = error.readLine()) != null) {
                    Log.d(TAG, "exec error:" + line);
                }
            }
            return retVal;
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
            if (proc != null) {
                proc.destroy();
            }
        }
        return -1;
    }

    public static BufferedReader toReader(InputStream is) {
        return new BufferedReader(new InputStreamReader(is), 8192);
    }
}