Android examples for Android OS:Shell
run As Root Async
import android.util.Log; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; public class Main{ private static final String TAG = RootHelpers.class.toString(); public static Process runAsRootAsync(String[] cmds, final Task.OnMessageListener listener) throws IOException { final Process su = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(su.getOutputStream()); for (String tmpCmd : cmds) { System.out.println("\n> Running command: " + tmpCmd); os.writeBytes(tmpCmd + "\n"); os.flush();// w w w . ja v a2s.c o m } os.writeBytes("exit\n"); os.flush(); if (listener != null) { Log.i(TAG, "Spawning a new Listener Thread"); final BufferedReader reader = new BufferedReader( new InputStreamReader(su.getInputStream())); //Spawn a thread that do reads and send the output to our listener! new Thread(new Runnable() { Process mProcess = su; @Override public void run() { Log.i(TAG, "Reader thread started"); android.os.Process .setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); String line = ""; try { while ((line = reader.readLine()) != null) { Log.i(TAG, line); listener.onMessage(line); } Log.i(TAG, "Reader thread exiting:" + reader); } catch (IOException e) { Log.i(TAG, "Error reading output:" + e.toString()); } } }).start(); } else Log.i(TAG, "No listener"); return su; } }