在做Android应用时,经常需要执行shell脚本,以快速实现某些功能;

在Android应用程序中执行shell脚本可以省去一大堆繁琐的代码,还可以避免不必要的错误;

比如:拷贝文件夹时,可以执行shell命令中的 cp 命令达到目的;而在代码中实现拷贝文件夹时,不仅需要编写一大堆繁琐的代码,还容易陷入递归死循环的错误中;

比如:获取文件系统的读写权限,只需要执行shell脚本中一句 mount -o rw,remount / 就能轻松搞定;

比如:删除文件夹下某一个文件、或者某一类文件、或者全部文件,只需要执行shell脚本中的一句 rm -f  *(利用*通配符进行匹配) 就能轻松搞定;

再比如:静默安装时,只需要执行shell脚本中一句 pm install -r 便可达到目的;

如果这些都用代码来实现,不仅代码量增加,还容易造成很多bug,吃力不讨好!

  1. package com.example.test;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.DataOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7.  
  8. import android.util.Log;
  9.  
  10. /**
  11. * 执行shell脚本工具类
  12. * @author Mountain
  13. *
  14. */
  15. public class CommandExecution {
  16.  
  17. public static final String TAG = "CommandExecution";
  18.  
  19. public final static String COMMAND_SU = "su";
  20. public final static String COMMAND_SH = "sh";
  21. public final static String COMMAND_EXIT = "exit\n";
  22. public final static String COMMAND_LINE_END = "\n";
  23.  
  24. /**
  25. * Command执行结果
  26. * @author Mountain
  27. *
  28. */
  29. public static class CommandResult {
  30. public int result = -1;
  31. public String errorMsg;
  32. public String successMsg;
  33. }
  34.  
  35. /**
  36. * 执行命令—单条
  37. * @param command
  38. * @param isRoot
  39. * @return
  40. */
  41. public static CommandResult execCommand(String command, boolean isRoot) {
  42. String[] commands = {command};
  43. return execCommand(commands, isRoot);
  44. }
  45.  
  46. /**
  47. * 执行命令-多条
  48. * @param commands
  49. * @param isRoot
  50. * @return
  51. */
  52. public static CommandResult execCommand(String[] commands, boolean isRoot) {
  53. CommandResult commandResult = new CommandResult();
  54. if (commands == null || commands.length == 0) return commandResult;
  55. Process process = null;
  56. DataOutputStream os = null;
  57. BufferedReader successResult = null;
  58. BufferedReader errorResult = null;
  59. StringBuilder successMsg = null;
  60. StringBuilder errorMsg = null;
  61. try {
  62. process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH);
  63. os = new DataOutputStream(process.getOutputStream());
  64. for (String command : commands) {
  65. if (command != null) {
  66. os.write(command.getBytes());
  67. os.writeBytes(COMMAND_LINE_END);
  68. os.flush();
  69. }
  70. }
  71. os.writeBytes(COMMAND_EXIT);
  72. os.flush();
  73. commandResult.result = process.waitFor();
  74. //获取错误信息
  75. successMsg = new StringBuilder();
  76. errorMsg = new StringBuilder();
  77. successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
  78. errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
  79. String s;
  80. while ((s = successResult.readLine()) != null) successMsg.append(s);
  81. while ((s = errorResult.readLine()) != null) errorMsg.append(s);
  82. commandResult.successMsg = successMsg.toString();
  83. commandResult.errorMsg = errorMsg.toString();
  84. Log.i(TAG, commandResult.result + " | " + commandResult.successMsg
  85. + " | " + commandResult.errorMsg);
  86. } catch (IOException e) {
  87. String errmsg = e.getMessage();
  88. if (errmsg != null) {
  89. Log.e(TAG, errmsg);
  90. } else {
  91. e.printStackTrace();
  92. }
  93. } catch (Exception e) {
  94. String errmsg = e.getMessage();
  95. if (errmsg != null) {
  96. Log.e(TAG, errmsg);
  97. } else {
  98. e.printStackTrace();
  99. }
  100. } finally {
  101. try {
  102. if (os != null) os.close();
  103. if (successResult != null) successResult.close();
  104. if (errorResult != null) errorResult.close();
  105. } catch (IOException e) {
  106. String errmsg = e.getMessage();
  107. if (errmsg != null) {
  108. Log.e(TAG, errmsg);
  109. } else {
  110. e.printStackTrace();
  111. }
  112. }
  113. if (process != null) process.destroy();
  114. }
  115. return commandResult;
  116. }
  117.  
  118. }

如果能在android应用中执行shell脚本来达到目的,可以省去一大堆代码,避免很多易犯的错误,简洁高效,何乐而不为呢?!

下面给出一个在Android应用中执行shell脚本的工具类的示例,供大家参考:

Android程序执行shell脚本的更多相关文章

  1. Java SSH远程执行Shell脚本实现(转)

    前言 此程序需要ganymed-ssh2-build210.jar包(下载地址:http://www.ganymed.ethz.ch/ssh2/) 为了调试方便,可以将\ganymed-ssh2-bu ...

  2. C程序调用shell脚本共有三种方法

    C程序调用shell脚本共有三种法子 :system().popen().exec系列函数call_exec1.c ,内容为:system() 不用你自己去产生进程,它已经封装了,直接加入自己的命令e ...

  3. Java实践 — SSH远程执行Shell脚本(转)

    原文地址:http://www.open-open.com/lib/view/open1384351384024.html 1. SSH简介         SSH是Secure Shell的缩写,一 ...

  4. 利用python执行shell脚本 并动态传参 及subprocess基本使用

    最近工作需求中 有遇到这个情况  在web端获取配置文件内容 及 往shell 脚本中动态传入参数 执行shell脚本这个有多种方法   最后还是选择了subprocess这个python标准库 su ...

  5. Scala进阶之路-进程控制之执行shell脚本

    Scala进阶之路-进程控制之执行shell脚本 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 废话不多说,我这里直接放一个案例. /* @author :yinzhengjie ...

  6. Java实践 — SSH远程执行Shell脚本

    1. SSH简介         SSH是Secure Shell的缩写,一种建立在应用层和传输层基础上的安全协议.SSH在连接和传送过程中会加密所有数据,可以用来在不同系统或者服务器之间进行安全连接 ...

  7. 执行shell脚本时提示bad interpreter:No such file or directory的解决办法

    执行shell脚本时提示bad interpreter:No such file or directory的解决办法 故障现象:在终端直接cd /var正常,在shell脚本中执行则报错.原因是脚本是 ...

  8. Linux下如何执行Shell脚本

    Linux下你可以有两种方式执行Shell脚本: 1.用shell程序执行脚本:根据你的shell脚本的类型,选择shell程序,常用的有sh,bash,tcsh等(一般来说第一行#!/bin/bas ...

  9. 在PHP中调用php_ssh实现远程登陆linux服务器并执行shell脚本。

    这个功能主要用于在web端利用程序对远程服务器进行操作,通过PHP_ssh执行shell脚本来实现. 首先要安装php_ssh2组件,linux中centos7下有ssh2源,直接安装.window下 ...

随机推荐

  1. 转: Linux与JVM的内存关系分析

    Linux与JVM的内存关系分析 引言 在一些物理内存为8g的服务器上,主要运行一个Java服务,系统内存分配如下:Java服务的JVM堆大小设置为6g,一个监控进程占用大约600m,Linux自身使 ...

  2. 可伸缩Web架构与分布式系统(1)

    开源软件近年来已变为构建一些大型网站的基础组件.并且伴随着网站的成长,围绕着它们架构的最佳实践和指导准则已经显露.这篇文章旨在涉及一些在设计大型网站时需要考虑的关键问题和一些为达到这些目标所使用的组件 ...

  3. iOS Core ML与Vision初识

    代码地址如下:http://www.demodashi.com/demo/11715.html 教之道 贵以专 昔孟母 择邻处 子不学 断机杼 随着苹果新品iPhone x的发布,正式版iOS 11也 ...

  4. Linux-信号详解

    1.Linux支持的所有信号: $ kill -l ) SIGHUP ) SIGINT ) SIGQUIT ) SIGILL ) SIGTRAP ) SIGABRT ) SIGBUS ) SIGFPE ...

  5. IIS各种问题汇总

    1.不能在此路径中使用此配置节.如果在父级别上锁定了该节,便会出现这种情况.锁定是默认设置的(overrideModeDefault="Deny"),或者是通过包含 overrid ...

  6. msbuild,Build failed with Error MSB3073 exited with code 1

    1. 接手以前的老项目,因为项目比较大,所以用Developer Command Prompt 的msbuild命令编译比较快一些,常用命令如下 devenv /?             帮助 ms ...

  7. paho-mqtt 学习笔记

    Installation The latest stable version is available in the Python Package Index (PyPi) and can be in ...

  8. Android startActivities()的使用

    startActivities()和startActivity类似,也是界面跳转: Intent[] intents = new Intent[2]; intents[0] = new Intent( ...

  9. Linux下(centos6.8)JDK1.8的安装与配置

    今天说下在Linux(centos6.8)系统下的JDK安装与配置. 据我所知的jdk安装方式有三种(rpm.yum方式没用过,暂且不提)今天只说解压安装方式: 一.解压jdk安装包: 附上jdk1. ...

  10. Redis之最大内存置换策略

    0.前言 Redis默认最大内存大小是应用程序可访问的内存大小, 32位windows下是2GB, linux下是3GB. 64位下可以访问的内存为2^64字节, Redis提供了maxmemory字 ...