本Demo的最初目的是为了从Android的dmesg获取Linux内核输出信息,判断设备是否正常运行信息,最终衍生出了这个执行Android执行shell脚本的Demo。
1 package com.android.utils;
2
3
4 import java.io.File;
5
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.util.ArrayList;
9 import java.util.List;
10
11 /**
12 * 本类主要用于在Java层执行Linux shell命令,获取一些系统下的信息
13 * 本例中的dmesg需要一些额外的权限才能使用
14 * 参考文章:
15 * 1. read android dmesg with code
16 * http://stackoverflow.com/questions/3643599/read-android-dmesg-with-code
17 * 2. Java执行带重定向或管道的shell命令的问题
18 * http://www.linuxidc.com/Linux/2012-07/64526.htm
19 *
20 * @author zengjf
21 */
22 public class ShellExecute {
23 /**
24 * 本函数用于执行Linux shell命令
25 *
26 * @param command shell命令,支持管道,重定向
27 * @param directory 在指定目录下执行命令
28 * @return 返回shell命令执行结果
29 * @throws IOException 抛出IOException
30 */
31 public static String execute ( String command, String directory )
32 throws IOException {
33
34 // check the arguments
35 if (null == command)
36 return "";
37
38 if (command.trim().equals(""))
39 return "";
40
41 if (null == directory || directory.trim().equals(""))
42 directory = "/";
43
44 String result = "" ;
45
46 List<String> cmds = new ArrayList<String>();
47 cmds.add("sh");
48 cmds.add("-c");
49 cmds.add(command);
50
51 try {
52 ProcessBuilder builder = new ProcessBuilder(cmds);
53
54 if ( directory != null )
55 builder.directory ( new File ( directory ) ) ;
56
57 builder.redirectErrorStream (true) ;
58 Process process = builder.start ( ) ;
59
60 //得到命令执行后的结果
61 InputStream is = process.getInputStream ( ) ;
62 byte[] buffer = new byte[1024] ;
63 while ( is.read(buffer) != -1 )
64 result = result + new String (buffer) ;
65
66 is.close ( ) ;
67 } catch ( Exception e ) {
68 e.printStackTrace ( ) ;
69 }
70 return result.trim() ;
71 }
72
73 /**
74 * 本函数用于执行Linux shell命令,执行目录被指定为:"/"
75 *
76 * @param command shell命令,支持管道,重定向
77 * @return 返回shell命令执行结果
78 * @throws IOException 抛出IOException
79 */
80 public static String execute (String command) throws IOException {
81
82 // check the arguments
83 if (null == command)
84 return "";
85
86 if (command.trim().equals(""))
87 return "";
88
89 return execute(command, "/");
90 }
91
92 /**
93 * 本函数用于判断dmesg中是否存在pattern字符串,执行目录被指定为:"/"
94 *
95 * @param pattern 给grep匹配的字符串
96 * @return true: dmesg中存在pattern中的字符串<br>
97 * false:dmesg中不存在pattern中的字符串
98 * @throws IOException 抛出IOException
99 */
100 public static boolean deviceExist(String pattern) throws IOException{
101
102 // check the arguments
103 if (null == pattern)
104 return false;
105
106 if (pattern.trim().equals(""))
107 return false;
108
109 return execute("dmesg | grep " + pattern).length() > 0;
110 }
111 }