全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

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

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 


相关文章: 微信小程序 五星评分(包括半颗星评分)实例代码  在线ppt制作网站有哪些,请推荐几个好的课件下载的网站?  如何规划企业建站流程的关键步骤?  如何选购建站域名与空间?自助平台全解析  如何在IIS中新建站点并配置端口与IP地址?  建站主机功能解析:服务器选择与快速搭建指南  网站制作和推广的区别,想自己建立一个网站做推广,有什么快捷方法马上做好一个网站?  网站网页制作专业公司,怎样制作自己的网页?  如何用免费手机建站系统零基础打造专业网站?  如何获取上海专业网站定制建站电话?  Python lxml的etree和ElementTree有什么区别  如何在阿里云虚拟机上搭建网站?步骤解析与避坑指南  广州网站制作公司哪家好一点,广州欧莱雅百库网络科技有限公司官网?  如何挑选优质建站一级代理提升网站排名?  定制建站是什么?如何实现个性化需求?  如何打造高效商业网站?建站目的决定转化率  香港服务器建站指南:免备案优势与SEO优化技巧全解析  天津个人网站制作公司,天津网约车驾驶员从业资格证官网?  合肥做个网站多少钱,合肥本地有没有比较靠谱的交友平台?  如何在万网主机上快速搭建网站?  Swift中swift中的switch 语句  如何快速搭建自助建站会员专属系统?  高端企业智能建站程序:SEO优化与响应式模板定制开发  如何在阿里云部署织梦网站?  如何撰写建站申请书?关键要点有哪些?  如何快速搭建高效WAP手机网站?  上海网站制作网页,上海本地的生活网站有哪些?最好包括生活的各个方面的?  宝盒自助建站智能生成技巧:SEO优化与关键词设置指南  宠物网站制作html代码,有没有专门介绍宠物如何养的网站啊?  Android自定义控件实现温度旋转按钮效果  如何快速搭建FTP站点实现文件共享?  实例解析angularjs的filter过滤器  子杰智能建站系统|零代码开发与AI生成SEO优化指南  如何在阿里云通过域名搭建网站?  个人摄影网站制作流程,摄影爱好者都去什么网站?  微信小程序制作网站有哪些,微信小程序需要做网站吗?  制作销售网站教学视频,销售网站有哪些?  电脑免费海报制作网站推荐,招聘海报哪个网站多?  宝塔面板创建网站无法访问?如何快速排查修复?  新网站制作渠道有哪些,跪求一个无线渠道比较强的小说网站,我要发表小说?  活动邀请函制作网站有哪些,活动邀请函文案?  高配服务器限时抢购:企业级配置与回收服务一站式优惠方案  如何用y主机助手快速搭建网站?  如何通过NAT技术实现内网高效建站?  如何在Windows 2008云服务器安全搭建网站?  如何选择建站程序?包含哪些必备功能与类型?  建站主机CVM配置优化、SEO策略与性能提升指南  邀请函制作网站有哪些,有没有做年会邀请函的网站啊?在线制作,模板很多的那种?  太平洋网站制作公司,网络用语太平洋是什么意思?  儿童网站界面设计图片,中国少年儿童教育网站-怎么去注册? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。