据我所知,您只能使用root特权运行命令行命令。您可以使用我制作的将根访问权限包装在您的代码中的通用类:http : //muzikant-android.blogspot.com/2011/02/how-to-get-root-access-and-execute.html

您需要做的就是扩展此类并重写getCommandsToExecute方法以返回要以root用户身份执行的命令。

public abstract class ExecuteAsRootBase

{

public static boolean canRunRootCommands()

{

boolean retval = false;

Process suProcess;

try

{

suProcess = Runtime.getRuntime().exec("su");

DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());

DataInputStream osRes = new DataInputStream(suProcess.getInputStream());

if (null != os && null != osRes)

{

// Getting the id of the current user to check if this is root

os.writeBytes("id\n");

os.flush();

String currUid = osRes.readLine();

boolean exitSu = false;

if (null == currUid)

{

retval = false;

exitSu = false;

Log.d("ROOT", "Can't get root access or denied by user");

}

else if (true == currUid.contains("uid=0"))

{

retval = true;

exitSu = true;

Log.d("ROOT", "Root access granted");

}

else

{

retval = false;

exitSu = true;

Log.d("ROOT", "Root access rejected: " + currUid);

}

if (exitSu)

{

os.writeBytes("exit\n");

os.flush();

}

}

}

catch (Exception e)

{

// Can't get root !

// Probably broken pipe exception on trying to write to output stream (os) after su failed, meaning that the device is not rooted

retval = false;

Log.d("ROOT", "Root access rejected [" + e.getClass().getName() + "] : " + e.getMessage());

}

return retval;

}

public final boolean execute()

{

boolean retval = false;

try

{

ArrayList commands = getCommandsToExecute();

if (null != commands && commands.size() > 0)

{

Process suProcess = Runtime.getRuntime().exec("su");

DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());

// Execute commands that require root access

for (String currCommand : commands)

{

os.writeBytes(currCommand + "\n");

os.flush();

}

os.writeBytes("exit\n");

os.flush();

try

{

int suProcessRetval = suProcess.waitFor();

if (255 != suProcessRetval)

{

// Root access granted

retval = true;

}

else

{

// Root access denied

retval = false;

}

}

catch (Exception ex)

{

Log.e("ROOT", "Error executing root action", ex);

}

}

}

catch (IOException ex)

{

Log.w("ROOT", "Can't get root access", ex);

}

catch (SecurityException ex)

{

Log.w("ROOT", "Can't get root access", ex);

}

catch (Exception ex)

{

Log.w("ROOT", "Error executing internal operation", ex);

}

return retval;

}

protected abstract ArrayList getCommandsToExecute();

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐