转帖:http://www.stealthcopter.com/blog/2010/01/android-requesting-root-access-in-your-app/
This snippet shows how root access can be requested inside an application in order to write a file into a place we do not have permission to access usually. Requesting root access will only work if your phone allows it, or it has been ‘rooted’ (hacked to allow superuser permissions).
- Process p;
- try {
- // Preform su to get root privledges
- p = Runtime.getRuntime().exec("su");
- // Attempt to write a file to a root-only
- DataOutputStream os = new DataOutputStream(p.getOutputStream());
- os.writeBytes("echo /"Do I have root?/" >/system/sd/temporary.txt/n");
- // Close the terminal
- os.writeBytes("exit/n");
- os.flush();
- try {
- p.waitFor();
- if (p.exitValue() != 255) {
- // TODO Code to run on success
- toastMessage("root");
- }
- else {
- // TODO Code to run on unsuccessful
- toastMessage("not root");
- }
- } catch (InterruptedException e) {
- // TODO Code to run in interrupted exception
- toastMessage("not root");
- }
- } catch (IOException e) {
- // TODO Code to run in input/output exception
- toastMessage("not root");
- }
Where my “toastMessage” is just a function which creates a toast to display on the screen. On phones with superuser permissions installed (root access) this will display a dialog asking the user to allow or deny the application permission to have root access: