安卓(Android) 怎么在本机进程中执行命令及其参数

2019年10月13日14:39:02安卓(Android) 怎么在本机进程中执行命令及其参数已关闭评论 308 1118字阅读3分43秒

1.简介

安卓(Android) 怎么在本机进程中执行命令及其参数?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import java.io.InputStream;
import java.util.Scanner;

public class Main {
  private static boolean DEBUG = System.getProperty("cts.vm-tests.debug") != null;

  
  public static void digestCommand(String[] commandAndArgs, String okIndicator) {
    RuntimeException re = null;
    try {
      String c = "";
      for (int i = 0; i < commandAndArgs.length; i++) {
        c += commandAndArgs[i] + " ";
      }
      if (DEBUG)
        System.out.print("com: " + c);
      StringBuilder sb = new StringBuilder();
      ProcessBuilder pb = new ProcessBuilder(commandAndArgs).redirectErrorStream(true);
      Process p = pb.start();

      InputStream is = p.getInputStream();
      Scanner scanner = new Scanner(is);
      int retCode = p.waitFor();
      while (scanner.hasNextLine()) {
        sb.append(scanner.nextLine());
      }
      scanner.close();
      if (retCode != 0 || (okIndicator != null && !sb.toString().contains(okIndicator))) {
        String msg = sb.toString() + "\nreturn code: " + retCode;
        re = new RuntimeException(msg);
        if (DEBUG)
          System.out.println("-> error! msg:" + msg);
      } else {
        if (DEBUG)
          System.out.println(" -> " + retCode);
      }
    } catch (Exception e) {
      throw new RuntimeException("Exception occurred: " + e.getClass().getName() + ", msg:" + e.getMessage());
    } finally {
      if (re != null) {
        throw re;
      }
    }
  }
}

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