Android 开发中使用Linux Shell实例详解

发布时间 - 2026-01-11 00:18:54    点击率:

Android 开发中使用Linux Shell实例详解

引言

Android系统是基于Linux内核运行的,而做为一名Linux粉,不在Android上面运行一下Linux Shell怎么行呢?

最近发现了一个很好的Android Shell工具代码,在这里分享一下。

Shell核心代码

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * ShellUtils
 * <ul>
 * <strong>Check root</strong>
 * <li>{@link ShellUtils#checkRootPermission()}</li>
 * </ul>
 * <ul>
 * <strong>Execte command</strong>
 * <li>{@link ShellUtils#execCommand(String, boolean)}</li>
 * <li>{@link ShellUtils#execCommand(String, boolean, boolean)}</li>
 * <li>{@link ShellUtils#execCommand(List, boolean)}</li>
 * <li>{@link ShellUtils#execCommand(List, boolean, boolean)}</li>
 * <li>{@link ShellUtils#execCommand(String[], boolean)}</li>
 * <li>{@link ShellUtils#execCommand(String[], boolean, boolean)}</li>
 * </ul>
 */
public class ShellUtils {

  public static final String COMMAND_SU    = "su";
  public static final String COMMAND_SH    = "sh";
  public static final String COMMAND_EXIT   = "exit\n";
  public static final String COMMAND_LINE_END = "\n";

  private ShellUtils() {
    throw new AssertionError();
  }

  /**
   * check whether has root permission
   * 
   * @return
   */
  public static boolean checkRootPermission() {
    return execCommand("echo root", true, false).result == 0;
  }

  /**
   * execute shell command, default return result msg
   * 
   * @param command command
   * @param isRoot whether need to run with root
   * @return
   * @see ShellUtils#execCommand(String[], boolean, boolean)
   */
  public static CommandResult execCommand(String command, boolean isRoot) {
    return execCommand(new String[] {command}, isRoot, true);
  }

  /**
   * execute shell commands, default return result msg
   * 
   * @param commands command list
   * @param isRoot whether need to run with root
   * @return
   * @see ShellUtils#execCommand(String[], boolean, boolean)
   */
  public static CommandResult execCommand(List<String> commands, boolean isRoot) {
    return execCommand(commands == null ? null : commands.toArray(new String[] {}), isRoot, true);
  }

  /**
   * execute shell commands, default return result msg
   * 
   * @param commands command array
   * @param isRoot whether need to run with root
   * @return
   * @see ShellUtils#execCommand(String[], boolean, boolean)
   */
  public static CommandResult execCommand(String[] commands, boolean isRoot) {
    return execCommand(commands, isRoot, true);
  }

  /**
   * execute shell command
   * 
   * @param command command
   * @param isRoot whether need to run with root
   * @param isNeedResultMsg whether need result msg
   * @return
   * @see ShellUtils#execCommand(String[], boolean, boolean)
   */
  public static CommandResult execCommand(String command, boolean isRoot, boolean isNeedResultMsg) {
    return execCommand(new String[] {command}, isRoot, isNeedResultMsg);
  }

  /**
   * execute shell commands
   * 
   * @param commands command list
   * @param isRoot whether need to run with root
   * @param isNeedResultMsg whether need result msg
   * @return
   * @see ShellUtils#execCommand(String[], boolean, boolean)
   */
  public static CommandResult execCommand(List<String> commands, boolean isRoot, boolean isNeedResultMsg) {
    return execCommand(commands == null ? null : commands.toArray(new String[] {}), isRoot, isNeedResultMsg);
  }

  /**
   * execute shell commands
   * 
   * @param commands command array
   * @param isRoot whether need to run with root
   * @param isNeedResultMsg whether need result msg
   * @return <ul>
   *     <li>if isNeedResultMsg is false, {@link CommandResult#successMsg} is null and
   *     {@link CommandResult#errorMsg} is null.</li>
   *     <li>if {@link CommandResult#result} is -1, there maybe some excepiton.</li>
   *     </ul>
   */
  public static CommandResult execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg) {
    int result = -1;
    if (commands == null || commands.length == 0) {
      return new CommandResult(result, null, null);
    }

    Process process = null;
    BufferedReader successResult = null;
    BufferedReader errorResult = null;
    StringBuilder successMsg = null;
    StringBuilder errorMsg = null;

    DataOutputStream os = null;
    try {
      process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH);
      os = new DataOutputStream(process.getOutputStream());
      for (String command : commands) {
        if (command == null) {
          continue;
        }

        // donnot use os.writeBytes(commmand), avoid chinese charset error
        os.write(command.getBytes());
        os.writeBytes(COMMAND_LINE_END);
        os.flush();
      }
      os.writeBytes(COMMAND_EXIT);
      os.flush();

      result = process.waitFor();
      // get command result
      if (isNeedResultMsg) {
        successMsg = new StringBuilder();
        errorMsg = new StringBuilder();
        successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
        errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String s;
        while ((s = successResult.readLine()) != null) {
          successMsg.append(s);
        }
        while ((s = errorResult.readLine()) != null) {
          errorMsg.append(s);
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (os != null) {
          os.close();
        }
        if (successResult != null) {
          successResult.close();
        }
        if (errorResult != null) {
          errorResult.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }

      if (process != null) {
        process.destroy();
      }
    }
    return new CommandResult(result, successMsg == null ? null : successMsg.toString(), errorMsg == null ? null
        : errorMsg.toString());
  }

  /**
   * result of command
   * <ul>
   * <li>{@link CommandResult#result} means result of command, 0 means normal, else means error, same to excute in
   * linux shell</li>
   * <li>{@link CommandResult#successMsg} means success message of command result</li>
   * <li>{@link CommandResult#errorMsg} means error message of command result</li>
   * </ul>
   */
  public static class CommandResult {

    /** result of command **/
    public int  result;
    /** success message of command result **/
    public String successMsg;
    /** error message of command result **/
    public String errorMsg;

    public CommandResult(int result) {
      this.result = result;
    }

    public CommandResult(int result, String successMsg, String errorMsg) {
      this.result = result;
      this.successMsg = successMsg;
      this.errorMsg = errorMsg;
    }
  }
}

ShellUtils代码引用自:Trinea

小实例

是否root

public Boolean isRooted(){
  CommandResult cmdResult = ShellUtils.execCommand("su", true);
  if (cmdResult.errorMsg.equals("Permission denied") || cmdResult.result != 0) {

    return false;
  }else{
    return true;
  }
}

复制文件

String[] commands = new String[] { "mount -o rw,remount /system", "cp /mnt/sdcard/xx.apk /system/app/" };

public boolean copyFile(String[] cmdText){
  CommandResult cmdResult = ShellUtils.execCommand(cmdText, true);
  if (cmdResult.errorMsg.equals("Permission denied") || cmdResult.result != 0) {
    return false;
  }else{
    return true;
  }
}

我暂时就举这两个例子,只要你会Shell,什么操作都是可以的。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


# Android  # Linux  # Shell的使用  # 使用Linux  # Shell的实例  # Android客制化adb shell进去后显示shell@xxx的标识  # Android shell命令行中过滤adb logcat输出的方法  # Android shell命令行中过滤adb logcat输出的几种方法  # Android 使用Shell脚本截屏并自动传到电脑上  # Android中执行java命令的方法及java代码执行并解析shell命令  # 实现android自动化测试部署与运行Shell脚本分享  # Android执行shell命令详解  # Android系统在shell中的df命令实现  # 都是  # 在这里  # 很好  # 一名  # 你会  # 这两个  # 希望能  # 谢谢大家  # 发现了  # 是基于  # private  # COMMAND_LINE_END  # exit  # throw  # permission  # check  # AssertionError  # COMMAND_EXIT  # final  # su 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 电视网站制作tvbox接口,云海电视怎样自定义添加电视源?  如何在 Telegram Web View(iOS)中防止键盘遮挡底部输入框  Laravel怎么配置不同环境的数据库_Laravel本地测试与生产环境动态切换【方法】  百度浏览器ai对话怎么关 百度浏览器ai聊天窗口隐藏  香港服务器如何优化才能显著提升网站加载速度?  Laravel如何使用withoutEvents方法临时禁用模型事件  惠州网站建设制作推广,惠州市华视达文化传媒有限公司怎么样?  如何将凡科建站内容保存为本地文件?  绝密ChatGPT指令:手把手教你生成HR无法拒绝的求职信  JavaScript如何实现错误处理_try...catch如何捕获异常?  JavaScript如何实现音频处理_Web Audio API如何工作?  Laravel怎么实现搜索高亮功能_Laravel结合Scout与Algolia全文检索【实战】  Gemini怎么用新功能实时问答_Gemini实时问答使用【步骤】  网站制作价目表怎么做,珍爱网婚介费用多少?  Windows10怎样连接蓝牙设备_Windows10蓝牙连接步骤【教程】  Python企业级消息系统教程_KafkaRabbitMQ高并发应用  Laravel如何实现API资源集合?(Resource Collection教程)  Gemini手机端怎么发图片_Gemini手机端发图方法【步骤】  Laravel广播系统如何实现实时通信_Laravel Reverb与WebSockets实战教程  如何制作新型网站程序文件,新型止水鱼鳞网要拆除吗?  如何快速搭建FTP站点实现文件共享?  Laravel如何使用Blade模板引擎?(完整语法和示例)  Laravel如何发送邮件_Laravel Mailables构建与发送邮件的简明教程  Python文件操作最佳实践_稳定性说明【指导】  详解Android中Activity的四大启动模式实验简述  Win11怎么开启自动HDR画质_Windows11显示设置HDR选项  如何在服务器上配置二级域名建站?  英语简历制作免费网站推荐,如何将简历翻译成英文?  图册素材网站设计制作软件,图册的导出方式有几种?  Laravel如何集成微信支付SDK_Laravel使用yansongda-pay实现扫码支付【实战】  Laravel如何实现全文搜索_Laravel Scout集成Algolia或Meilisearch教程  Laravel怎么在Blade中安全地输出原始HTML内容  Laravel观察者模式如何使用_Laravel Model Observer配置  怎么用AI帮你为初创公司进行市场定位分析?  QQ浏览器网页版登录入口 个人中心在线进入  Laravel如何正确地在控制器和模型之间分配逻辑_Laravel代码职责分离与架构建议  JS中页面与页面之间超链接跳转中文乱码问题的解决办法  Laravel如何自定义分页视图?(Pagination示例)  Laravel如何使用Seeder填充数据_Laravel模型工厂Factory批量生成测试数据【方法】  制作公司内部网站有哪些,内网如何建网站?  如何在万网利用已有域名快速建站?  jQuery validate插件功能与用法详解  php中::能调用final静态方法吗_final修饰静态方法调用规则【解答】  如何用西部建站助手快速创建专业网站?  如何获取上海专业网站定制建站电话?  如何快速搭建高效可靠的建站解决方案?  Laravel Facade的原理是什么_深入理解Laravel门面及其工作机制  Python自动化办公教程_ExcelWordPDF批量处理案例  网站建设保证美观性,需要考虑的几点问题!  javascript中的数组方法有哪些_如何利用数组方法简化数据处理