安卓(Android) 怎么执行shell

2019年10月13日15:11:14安卓(Android) 怎么执行shell已关闭评论 354 999字阅读3分19秒

1.简介

安卓(Android) 怎么执行shell?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;

import android.util.Log;

public class Main {

  public static final String TAG = "SystemUtil";

  public static BufferedReader shellExecute(String command, boolean requireRoot) {
    return shellExecute(new String[] { command }, requireRoot);
  }

  public static BufferedReader shellExecute(String[] commands, boolean requireRoot) {
    Process shell = null;
    DataOutputStream out = null;
    BufferedReader reader = null;
    String startCommand = requireRoot ? "su" : "sh";
    try {
      shell = Runtime.getRuntime().exec(startCommand);
      out = new DataOutputStream(shell.getOutputStream());
      reader = new BufferedReader(new InputStreamReader(shell.getInputStream()));
      for (String command : commands) {
        out.writeBytes(command + "\n");
        out.flush();
      }
      out.writeBytes("exit\n");
      out.flush();
      shell.waitFor();
    } catch (Exception e) {
      Log.e(TAG, "ShellRoot#shExecute() finished with error", e);
    } finally {
      try {
        if (out != null) {
          out.close();
        }
      } catch (Exception e) {

      }
    }
    return reader;
  }

}

 
继续阅读
编程十万个怎么办