Home > Android > Android: Requesting root access in your app

Android: Requesting root access in your app

January 17th, 2010 mat Leave a comment Go to comments

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:

android root access dialog

android request root access dialog

Ref
anddev.org

Bookmark and Share
Categories: Android Tags: , ,
  1. elviento0891
    February 24th, 2010 at 17:58 | #1

    This was a great help, I appreciate this post!

  2. May 2nd, 2010 at 20:28 | #2

    hi~!
    ‘root access dialog’ is made by you?
    or, made by android system?
    if app requires root permissions
    then automatically show up ‘root access dialog’?
    IOException raised when write a file into a place we do not have permission(ex : /system/sd/)
    and app finished..
    not show ‘root access dialog’
    i want make app writing a file into /system/
    help me..

  3. May 2nd, 2010 at 20:35 | #3

    The root access dialog is part of the android system, but its is only avaliable if you have “rooted” the phone it is running on otherwise permission is simply denied.

  4. May 3rd, 2010 at 04:51 | #4

    Thanks,
    ‘rooted’ gets using shell command ‘mount’ ?

  5. May 5th, 2010 at 00:54 | #5

    No, I think your getting confused. Mount has nothing to do with this.

    A routed phone is one that has been hacked to allow root access. Your application will only work on phones that have been rooted by the user. This is obvious for security reasons.

  6. Rob
    May 10th, 2010 at 20:44 | #6

    How can I use this to access another applications database?

  1. No trackbacks yet.
// unused langs // // // //