android 应用程序中执行Linux 命令
ADB 无线调试命令
son = "setprop service.adb.tcp.port 5555\n" +
"stop adbd\n" +
"start adbd\n";
soff = "setprop service.adb.tcp.port -1\n" +
"stop adbd\n" +
"start adbd\n";
reboot 立即重启
//获取Ip
String getIp() {
String ip = "127.0.0.1";
WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
if (!wm.isWifiEnabled()) {
wm.setWifiEnabled(true);
}
WifiInfo wi = wm.getConnectionInfo();
int addr = wi.getIpAddress();
return intToIp(addr);
}
String intToIp(int t) {
return (t & 0xFF) + "." + ((t >> 8) & 0xFF) + "." + ((t >> 16) & 0xFF) + "." + ((t >> 24) & 0xFF);
}
//执行普通命令
String exec(String cmd) {
if (cmd.startsWith("su")|cmd.startsWith("ping")) {
return "不允许执行的命令";
}
String result = "";
Process ps = null;
ProcessBuilder pb = new ProcessBuilder(cmd);
InputStream es = null;
InputStream is = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read = -1;
ps = pb.start();
es = ps.getErrorStream();
while ((read = es.read()) != -1) {
baos.write(read);
}
baos.write('\n');
is = ps.getInputStream();
while ((read = is.read()) != -1) {
baos.write(read);
}
byte[] data = baos.toByteArray();
result = new String(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (es != null) {
es.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (ps != null) {
ps.destroy();
}
}
return result;
}
//执行root命令
String rootExec(String cmd) {
if (cmd.startsWith("su")|cmd.startsWith("ping")) {
return "不允许执行的命令";
}
String result = "";
DataOutputStream dos = null;
DataInputStream dis = null;
try {
Process ps = Runtime.getRuntime().exec("su");
dos = new DataOutputStream(ps.getOutputStream());
dis = new DataInputStream(ps.getInputStream());
dos.writeBytes(cmd + "\n");
dos.flush();
dos.writeBytes("exit\n");
dos.flush();
String line = null;
while ((line = dis.readLine())!=null) {
result += "\n"+line;
// Message ms = new Message();
// ms.obj = line;
// handler.sendMessageDelayed(ms,1000);
}
ps.waitFor();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
posted on 2017-03-20 13:08 robert_hly 阅读(2745) 评论(0) 编辑 收藏 举报