在apk中,有时候需要root权限,例如通过apk更新系统库等system的文件等,避免升级固件,或者在apk中需要直接访问某些设备等。下面是在apk中获取root权限的方法,前提是设备已经root过了。
//通过执行su产生一个具有root权限的进程
Process p = Runtime.getRuntime().exec("su");
//然后,在向这个进程的写入要执行的命令,即可达到以root权限执行命令:
DataOutputStream dos = new DataOutputStream(p.getOutputStream());
dos.writeBytes(cmd + "\n");//cmd命令可为空
dos.flush();
或者用下面的方式:
Runtime.getRuntime().exec(new String[]{"/system/bin/su","-c", cmd});
第一次运行时,会出现请求root权限的界面,选中记住,并允许:
执行命令
工具类如下:
package blog.csdn.net.mchenys.common.utils;
import android.util.Log;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public final class CmdUtils {
private static final String TAG = "CmdUtils";
private static boolean mHaveRoot = false;
// 判断机器Android是否已经root,即是否获取root权限
public static boolean haveRoot() {
if (!mHaveRoot) {
int ret = execRootCmdSilent("echo test"); // 通过执行测试命令来检测
if (ret != -1) {
Log.i(TAG, "have root!");
mHaveRoot = true;
} else {
Log.i(TAG, "not root!");
}
} else {
Log.i(TAG, "mHaveRoot = true, have root!");
}
return mHaveRoot;
}
// 执行命令并且输出结果
public static String execRootCmd(String cmd) {
String result = "";
DataOutputStream dos = null;
DataInputStream dis = null;
try {
Process p = Runtime.getRuntime().exec("su");// 经过Root处理的android系统即有su命令
dos = new DataOutputStream(p.getOutputStream());
dis = new DataInputStream(p.getInputStream());
Log.i(TAG, cmd);
dos.writeBytes(cmd + "\n");
dos.flush();
dos.writeBytes("exit\n");
dos.flush();
String line = null;
while ((line = dis.readLine()) != null) {
Log.d("result", line);
result += line;
}
p.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;
}
// 执行命令但不关注结果输出
public static int execRootCmdSilent(String cmd) {
int result = -1;
DataOutputStream dos = null;
try {
Process p = Runtime.getRuntime().exec("su");
dos = new DataOutputStream(p.getOutputStream());
Log.i(TAG, cmd);
dos.writeBytes(cmd + "\n");
dos.flush();
dos.writeBytes("exit\n");
dos.flush();
p.waitFor();
result = p.exitValue();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}