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
   try { 
           if (p.exitValue() != 255) { 
        	  // TODO Code to run on success
           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



  1. elviento0891

    This was a great help, I appreciate this post!

  2. rndmania

    ‘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. mat

    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. rndmania

    ‘rooted’ gets using shell command ‘mount’ ?

  5. mat

    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

    How can I use this to access another applications database?

  7. WeldFire

    Hello Mat,
    You say you can use this method to “write a file into a place we do not have permission to access usually” do you have to try and copy files using os.writebytes()? or just a FileOutputStream?

  8. mat

    @WeldFire Sorry I missed your comment, I’ve been quite busy lately. I don’t know an incredible amount about this as I never really ended up using it, but I imagine there is a way to use FileOutputStream, maybe even if you just need to turn it into a byte array (which you could then use with os.writebytes())

    Deleted your comment on other post as I’ve answered here

  9. Rocker

    Thank you Mat. I tried to modify the hosts file but not success.

    String cmd = String.format(“echo %s >> /etc/hosts\n”, entry);

    Do you have any idea?

  10. juwon

    I have an huawei ascending 2 and it says I don’t have root access what app can I install dat. allows this. permission my email is contact me if u have any information

  11. Jonathan

    Is there also a way to make the app detect when superuser permissions have been denied? Currently this code doesn’t seem to test that possibility.

  12. […] Inspirado en el código de ésta web. […]

  13. BTR Naidu

    Nice info but how to make your jni (C Function) run as root?

    Have something like this in my code.

    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?\” > /data/temporary.txt\n” );

    // Close the terminal
    try {
    if (p.exitValue() != 255) {
    // Code to run on success
    tv.setText( stringFromJNI() ); // This function returns with permission denied error.
    else {
    // Code to run on unsuccessful
    tv.setText(“not root”);
    } catch (InterruptedException e) {
    // Code to run in interrupted exception
    tv.setText(“not root”);
    } catch (IOException e) {
    // Code to run in input/output exception
    tv.setText(“not root”);
    } // end SU block

    I have the file created in /data folder but I guess that echo runs in a child shell whereas my jni lib gets loaded an android app env. How to make sure that the jni code runs in super user mode as well?

    Thanks in advance.

  14. […] Like this:LikeBe the first to like this post. Comments RSS feed […]

  15. Nitish

    how to use it frnds!!

  16. Eduardo

    Hi BTR Naidu,

    Did you find out an answer to your question?



  17. Krishnamurthy

    I am trying to run ubuntu-linux in andriiod but at command propmpt when i give “su” command the error message “permission denied” please help

  18. […] either Allow or Block it from root access. This approach might not work if the user is not rooted. Here is a way you can test […]

  19. amir

    can we acces “/data/data/com.whatsapp/databases/msgstore.db” file

  20. Frank

    Great Post!

    I use it to change the rights to a file and then read/write in normal way:

    os.writeBytes(“chmod 777 ” + PROPERTY_FILE + “\n”);

  21. kai-zhou

    perfect, that’s what i need

  22. haftay

    Great full code it successfully access the file .thank you

  23. Basil

    Here is tutorial on creating root app using library:

  24. aung


  25. aung


  26. aung


  27. aung
  28. aung


  29. aung

    2weettyggfuugfdstvyccyxf္​ပါငရာ ့လခအထခအ ာာလပပလပခf9ccoocococococtctictct

  30. aung
  31. David

    I know this is an old post. But I am following the sample in my own app. Can you explain the result code 255? Is that some special error code if the su binary fails? In my simple tests, it seems that the result code I am getting is the result of the command run by su. These are generally 0 for success and non-zero (I am getting 1) for non-success. So I am confused by your treatment of any result != 255 as a success. Thanks for the post and your elaboration.

  32. android rooting

    This excellent website really has all the info I wanted about this subject
    and didn’t know who to ask.

  33. professional quality beat

    Awesome! Its actually awesome piece of writing, I have got much clear idea regarding from this article.

  34. Kathlene Griffel

    I truly got into this article. I found it to be interesting and loaded with unique points of interest. I like to digest material that makes me think. ThanksThank you for sharing this great content.


    With advanced technological improvements, various form of features are implemented and integrated with all the hotel booking engines online
    in order that they be effective and help customers in a very greater way.
    The best way to enjoy and feel things are by staying in one of the harmonious luxurious hotel’s about the
    island. There are, however, still a lot of areas which can be yet to be discovered with the
    masses, will be more low key and wallet-friendly.


    Investors remain cautious and may even continue to do so until gold decides
    whether or not it’s going to embody its traditional safety status or not.
    Familiarize yourself with certain regulations with regards to your restrictions on abandoned properties in storage facilities.

    However, up to she adores getting a mommy,
    she moreover really loves as a lady wonderful that’s constructed of.


    Buying a property overseas is an extremely exciting prospect but never rush the decision. Just think about all of the famous sports stars and millionaire identities and you will realise one important thing about them and that’s, a primary reason these people are mega-rich
    and successful is since they all have a very mentor or coach.
    Because it seems there are other people now who are
    focused on retirement than ever before before.


    Some examples are perhaps someone asking to get land to use as an allotment
    so it is bought cheaply. Sometimes owners with the ransom strips are unknown or it can be a
    development company that has gone into administration. They are predicting
    this due to the political upheaval containing occurred inside the last two months.


    Some people think they are able to lower your expenses by in the role of their own general contractor.
    Anything Involving Wall Removal – Any given interior wall might be a structural part of your home.

    There are many people available in the world that prefer to
    are Contractors because it fits their personal needs.


    Home buyers try every possible option available to find flats in Bangalore at reasonable price.
    You can search for your listing cost free and without the obligation. With the implementation with the new
    guidance values, the prices of Bangalore property are expected to shoot up.

  41. TxOs

    Thanks, it is a very useful code!!

  42. […] de ese Proceso tiene privilegios de root: Process p = Runtime.getRuntime().exec("su"); Ver este blog post para el ejemplo […]

Leave a Comment

Your email address will not be published. Required fields are marked *