package net.lastcoder.jumphelp;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
/**
* Auth: Administrator
* Date: 2018/1/7 0007
*/
public class CmdHelper extends Thread {
private static final String TAG = "CmdHelper";
private StreamShow errorShow = null;
private StreamShow normalShow = null;
private OutputStreamWriter outputStreamWriter = null;
private Process process;
private String cmd;
private CmdHelper(String cmd) {
this.cmd = cmd;
}
@Override
public void run() {
// 先su root出一个终端
// 终端有输入,输出,和错误,因此有3个数据流
try {
process = Runtime.getRuntime().exec("su root");
BufferedReader errorStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
// 注意,如果输入流关闭,那么终端也会关闭,process的waitFor就会有等待结束
outputStreamWriter = new OutputStreamWriter(process.getOutputStream());
// 两种输出打印
errorShow = new StreamShow(errorStreamReader, true);
errorShow.start();
normalShow = new StreamShow(inputStreamReader, true);
normalShow.start();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
try {
// 这里线程等待
outputStreamWriter.write(cmd);
outputStreamWriter.close();
int result = process.waitFor();
Log.w(TAG, "------------------------ cmd result = " + result);
errorShow.done();
normalShow.done();
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage(), e);
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, e.getMessage(), e);
}
}
private static class StreamShow extends Thread {
BufferedReader reader;
private boolean error = false;
private boolean done = false;
StreamShow(BufferedReader reader, boolean error) {
this.reader = reader;
this.error = error;
}
private void done() {
done = true;
this.interrupt();
}
@Override
public void run() {
while (!done) {
try {
String line = reader.readLine();
if (TextUtils.isEmpty(line)) {
continue;
}
if (error) {
Log.e(TAG, line);
}
else {
Log.d(TAG, line);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
}
}
@Override
public synchronized void start() {
done = false;
super.start();
}
}
/**
* 异步,第一次打开可能有授权界面
*
* @param cmd 命令,如dumpsys等
*/
public synchronized static void cmd(String cmd) {
CmdHelper rootThread = new CmdHelper(cmd);
rootThread.setName("root_process");
rootThread.start();
}
}
android获取root命令,应用内输入命令
最新推荐文章于 2024-06-27 09:53:52 发布