在做android TV 开发时,会遇到向开发板发命令的需求,这时候就需要Runtime的api来完成这个需求,代码如下:
Process process = null;
DataOutputStream os = null;
/**
* 获取板子的序列号
* @param command
* @return
*/
public void sendCmd(String command){
if (command == null) {
return ;
}
try {
if(null==process){
process = Runtime.getRuntime().exec("su");//有root权限的用这个;
os = new DataOutputStream(process.getOutputStream());
}
os.write(command.getBytes());
os.writeBytes("\n");
os.flush();
os.close();
os=null;
int result =process.waitFor();
if(result!=0){
int pid = getProcessId(process);
if (pid != 0) {
try {
android.os.Process.killProcess(pid);
} catch (Exception e) {
e.printStackTrace();
}
}
}
process.destroy();
process=null;
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 获取进程的ID
*
* @param process 进程
* @return
*/
private int getProcessId(Process process) {
String str = process.toString();
try {
int i = str.indexOf("=") + 1;
int j = str.indexOf("]");
str = str.substring(i, j);
return Integer.parseInt(str);
} catch (Exception e) {
return 0;
}
}