Files
VscoolOS/app/src/main/java/com/uiui/os/utils/CmdUtil.java
tongtongstudio b481df8671 version:1.1
fix:
add:应用使用数据统计
2021-12-25 17:04:52 +08:00

104 lines
2.9 KiB
Java

package com.uiui.os.utils;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class CmdUtil {
private static final String TAG = "CmdUtil";
private static final String COMMAND_SH = "sh";
private static final String COMMAND_EXIT = "exit\n";
private static final String COMMAND_LINE_END = "\n";
/**
* 运行命令
*
* @param command 命令
* @return 结果
*/
public static Result execute(String command) {
Log.i(TAG, "execute() command = " + command);
Result result = new Result();
if (TextUtils.isEmpty(command)) {
Log.w(TAG, "WARNING: command should not be null or empty");
return result;
}
Process process = null;
DataOutputStream dos = null;
try {
process = Runtime.getRuntime().exec(COMMAND_SH);
dos = new DataOutputStream(process.getOutputStream());
dos.write(command.trim().getBytes());
dos.writeBytes(COMMAND_LINE_END);
dos.flush();
dos.writeBytes(COMMAND_EXIT);
dos.flush();
result.code = process.waitFor();
result.success = readBuffer(new BufferedReader(new InputStreamReader(process.getInputStream())));
result.error = readBuffer(new BufferedReader(new InputStreamReader(process.getErrorStream())));
Log.i(TAG, "result = " + result);
} catch (IOException ioe) {
ioe.printStackTrace();
Log.e(TAG, ioe.getMessage());
} catch (InterruptedException ie) {
ie.printStackTrace();
Log.e(TAG, ie.getMessage());
} finally {
try {
if (null != dos) {
dos.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
Log.e(TAG, ioe.getMessage());
}
if (null != process) {
process.destroy();
}
}
return result;
}
private static String readBuffer(BufferedReader bufferedReader) throws IOException {
StringBuilder sb = new StringBuilder();
String s;
while ((s = bufferedReader.readLine()) != null) {
sb.append(s);
}
return sb.toString();
}
/**
* Command执行结果
*/
public static final class Result {
public static final int SUCCESS = 0;
public static final int ERROR = -1;
public int code = ERROR;
public String error;
public String success;
@Override
public String toString() {
return "Result{" +
"code=" + code +
", error='" + error + '\'' +
", success='" + success + '\'' +
'}';
}
}
}