private static String runRootShell(String[] cmds){
String result = null;
int ret = -1;
java.lang.Process process;
try {
process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
for(int i=0; i< cmds.length; i++) {
os.writeBytes(cmds[i] + "\n");
}
os.writeBytes("exit\n");
os.flush();
try {
ret = process.waitFor();
Log.d("lx", "ret= " + ret);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
os.close();
ByteArrayOutputStream resultOutStream = new ByteArrayOutputStream();
InputStream errorInStream = new BufferedInputStream(process.getErrorStream());
InputStream processInStream = new BufferedInputStream(process.getInputStream());
int num = 0;
byte[] bs = new byte[1024];
while((num=errorInStream.read(bs))!=-1){
resultOutStream.write(bs,0,num);
}
while((num=processInStream.read(bs))!=-1){
resultOutStream.write(bs,0,num);
}
result=new String(resultOutStream.toByteArray());
println( "result: " + result);
errorInStream.close();
errorInStream=null;
processInStream.close();
processInStream=null;
resultOutStream.close();
resultOutStream=null;
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
result = "result code: " + ret + " details: " +result;
return result;
}
// 执行示例
runRootShell(new String[]{"rm -r /data/data/test",
"ls", "ls"});
PS:
InputStreamReader ir = new InputStreamReader(process .getInputStream());
LineNumberReader input = new LineNumberReader(ir);
int ret = process.waitFor();
while ((line = input.readLine()) != null){
println("result: " + line);
}
看到网上很多人采用上面的方法获取shell执行结果。 实际测试后发现有很多情况下readLine()并不会被执行,或者也并不能完全返回执行结果。