Run native binary executable from Android app in superuser mode

Here discussed about a ready made function for run native binary executable with user privileges. Now another ready made function for run the same binary executable but with superuser privileges.


Obviously run an executable with superuser privileges is possible only in rooted phones. In a standard Android image the possibility to run the "su" tool for obtain superuser level is locked by default. Based to your phone model exist some different procedures to hack the system and unlock this feature. The following function will work only if you successfully rooted your phone:

boolean executeCommandLineSuperuser(String commandLine)
{
  boolean OperationResult = false;

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

     DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
     DataInputStream is  = new DataInputStream(suProcess.getInputStream());

     os.writeBytes(commandLine+"\n");
     os.flush();

     os.writeBytes("exit\n");
     os.flush();

     try
     {
       suProcess.waitFor();

       Log.d("executeCommandLineSuperuser", is.readLine());
   
       if(suProcess.exitValue() >= 0)
       {
         // Success
         OperationResult = true;
       }
       else
       {
         // Failed
         OperationResult = false;
       }
    }
    catch (Exception ex)
    {
      Log.e("executeCommandLineSuperuser", "Failed to run executable", ex);
    }
  }
  catch (IOException ex)
  {
    Log.w("executeCommandLineSuperuser", "Error in execute su", ex);
  }
  catch (SecurityException ex)
  {
    Log.w("executeCommandLineSuperuser", "Error in execute su", ex);
  }
  catch (Exception ex)
  {
    Log.w("executeCommandLineSuperuser", "Error in execute su", ex);
  }

  return OperationResult;
}

Just some notes here:

- The function redirect the text output result of the command run to the "logcat" debug.

- The return is a boolean value informing about the result of the run operation (that involve the execution of "su" and the execution of the command line itself). The exitValue() return the numeric value returned by the executable ran into command line itself. In the function above it supposed to have a negative value in case of error and zero or positive value in case of success. However if the result to be expected from your target executable is different you have to adapt this code by your need.

Comments

Popular posts from this blog

Access GPIO from Linux user space

Launch an app from Android shell terminal