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

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

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

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

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

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

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

package com.example.test;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader; import android.util.Log; /**
* 执行shell脚本工具类
* @author Mountain
*
*/
public class CommandExecution { public static final String TAG = "CommandExecution"; public final static String COMMAND_SU = "su";
public final static String COMMAND_SH = "sh";
public final static String COMMAND_EXIT = "exit\n";
public final static String COMMAND_LINE_END = "\n"; /**
* Command执行结果
* @author Mountain
*
*/
public static class CommandResult {
public int result = -1;
public String errorMsg;
public String successMsg;
} /**
* 执行命令—单条
* @param command
* @param isRoot
* @return
*/
public static CommandResult execCommand(String command, boolean isRoot) {
String[] commands = {command};
return execCommand(commands, isRoot);
} /**
* 执行命令-多条
* @param commands
* @param isRoot
* @return
*/
public static CommandResult execCommand(String[] commands, boolean isRoot) {
CommandResult commandResult = new CommandResult();
if (commands == null || commands.length == 0) return commandResult;
Process process = null;
DataOutputStream os = null;
BufferedReader successResult = null;
BufferedReader errorResult = null;
StringBuilder successMsg = null;
StringBuilder errorMsg = null;
try {
process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH);
os = new DataOutputStream(process.getOutputStream());
for (String command : commands) {
if (command != null) {
os.write(command.getBytes());
os.writeBytes(COMMAND_LINE_END);
os.flush();
}
}
os.writeBytes(COMMAND_EXIT);
os.flush();
commandResult.result = process.waitFor();
//获取错误信息
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);
commandResult.successMsg = successMsg.toString();
commandResult.errorMsg = errorMsg.toString();
Log.i(TAG, commandResult.result + " | " + commandResult.successMsg
+ " | " + commandResult.errorMsg);
} catch (IOException e) {
String errmsg = e.getMessage();
if (errmsg != null) {
Log.e(TAG, errmsg);
} else {
e.printStackTrace();
}
} catch (Exception e) {
String errmsg = e.getMessage();
if (errmsg != null) {
Log.e(TAG, errmsg);
} else {
e.printStackTrace();
}
} finally {
try {
if (os != null) os.close();
if (successResult != null) successResult.close();
if (errorResult != null) errorResult.close();
} catch (IOException e) {
String errmsg = e.getMessage();
if (errmsg != null) {
Log.e(TAG, errmsg);
} else {
e.printStackTrace();
}
}
if (process != null) process.destroy();
}
return commandResult;
} }

如果能在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. fastestmirror不能使用

    fastestmirror不能使用,fastestmirror是yum的一个加速插件 处理办法就是禁用这个插件 方法两种 第一种 vi /etc/yum/pluginconf.d/fastestmir ...

  2. knowledgeroot 配置

    首先下载 KnowledgeRoot 的安装包,就是一个压缩文件,解压缩后放到 WebRoot 下面 在浏览器中打开网站,自动提示进行安装,安装的过程很简单,安装结束后即可以使用. 安装包创建的数据库 ...

  3. arm-linux-gdb+gdbserver环境搭建以及远程调试

    0) gdb源码下载:http://ftp.gnu.org/gnu/gdb/ 1) 编译arm-linux-gdb 指定交叉编译工具链的位置 export PATH=$PATH:/usr/local/ ...

  4. selenuim-webdriver注解之@FindBy、@FindBys、@FindAll的区别

    selenium-webdriver中获取页面元素的方式有很多,使用注解获取页面元素是其中一种途径, 方式有3种:@FindBy.@FindBys.@FindAll.下文对3中类型的区别和使用场景进行 ...

  5. JavaScript 创建对象的几种模式

    在JavaScript中虽说可以用Object的构造函数或者字面量创建单个对象,但是用这些方式来创建多个对象时就有一个明显的缺点,产生了大量的重复代码.为解决这些问题,许多模式就应运而生. 1. 工厂 ...

  6. (一)Linux——Linux基本概念

    Linux是一种自由和开放源码的类UNIX操作系统,使用Linux内核.目前存在着许多不同的Linux发行版,可安装在各种各样的电脑硬件设备,从手机.平板电脑.路由器和影音游戏控制台,到桌上型电脑,大 ...

  7. ASP.NET MVC:创建 ModelBinder 自动 Trim 所有字符串

    ASP.NET MVC:创建 ModelBinder 自动 Trim 所有字符串 2010-12-29 21:32 by 鹤冲天, 4289 阅读, 14 评论, 收藏, 编辑 用户输入的字符串前后的 ...

  8. 利用python批量缩放图片

    废话少说,上代码: import matplotlib as mpl mpl.use('Agg') import os import matplotlib.pyplot as plt from sci ...

  9. Silverlight实例教程 - Validation数据验证DataAnnotation机制和调试技巧(转载)

    Silverlight 4 Validation验证实例系列 Silverlight实例教程 - Validation数据验证开篇 Silverlight实例教程 - Validation数据验证基础 ...

  10. wxPython 4.0.0b2安装

    https://www.cnblogs.com/NanShan2016/p/5518235.html 亮的界面是一个GUI程序必不可少的一部分,wxPython可以做到这一点,加之Python强大的功 ...