一:
/**
* 判断当前手机是否有ROOT权限* @return
*/
public boolean isRoot(){
boolean bool = false;
try{
if ((!new File("/system/bin/su").exists()) && (!new File("/system/xbin/su").exists())){
bool = false;
} else {
bool = true;
}
Log.d(TAG, "bool = " + bool);
} catch (Exception e) {
}
return bool;
}
二:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doSU();
}
@Override
protected void onResume() {
super.onResume();
doSU();
}
private void doSU() {
try {
Process process = Runtime.getRuntime().exec("su");// (这里执行是系统已经开放了root权限,而不是说通过执行这句来获得root权限)
DataOutputStream os = new DataOutputStream(process.getOutputStream());
// os.writeBytes("ifconfig eth0 192.168.18.122\n");
os.writeBytes("exit\n");
os.flush();
/*
* //如果已经root,但是用户选择拒绝授权,e.getMessage() = write failed: EPIPE (Broken pipe)
//如果没有root,,e.getMessage()= Error running exec(). Command: [su] Working Directory: null Environment: null
*/
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
三:
// 判断机器Android是否已经root,即是否获取root权限
public static boolean haveRoot() {
if (!mHaveRoot) {
int ret = execRootCmdSilent("echo test"); // 通过执行测试命令来检测
if (ret != -1) {
mHaveRoot = true;
} else {
Log.i(TAG, "not root!");
}
} else {
Log.i(TAG, "mHaveRoot = true, have root!");
}
return mHaveRoot;
}
// 执行命令但不关注结果输出
public static int execRootCmdSilent(String cmd) {
int result = -1;
DataOutputStream dos = null;
try {
Process p = Runtime.getRuntime().exec("su");
dos = new DataOutputStream(p.getOutputStream());
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;
}