Check Root Access with Xamarin.Android




Hey today i want to share with you a simple method to check if the device has a Root Access its very useful if you want to use a low level resources from your android device

And here's the little class ExecuteAsRootBase.cs

using System;
using Java.Lang;
using System.Collections.Generic;

namespace RootAccess
{
 public static class ExecuteAsRootBase
 {
  public static bool canRunRootCommands()
  {
   bool retval = false;
   Process suProcess;
   try
   {
    suProcess = Runtime.GetRuntime().Exec("su");
    var os = new Java.IO.DataOutputStream(suProcess.OutputStream);
    var osRes = new Java.IO.DataInputStream(suProcess.InputStream);
    if (null != os && null != osRes)
    {
     os.WriteBytes("id\n");
     os.Flush();
     string currUid = osRes.ReadLine();
     bool exitSu = false;
     if (null == currUid)
     {
      retval = false;
      exitSu = false;
      Console.WriteLine("Can't get root access or denied by user");
     }
     else if (true == currUid.Contains("uid=0"))
     {
      retval = true;
      exitSu = true;
      Console.WriteLine("Root access granted");
     }
     else
     {
      retval = false;
      exitSu = true;
      Console.WriteLine("Root access rejected: " + currUid);
     }

     if (exitSu)
     {
      os.WriteBytes("exit\n");
      os.Flush();
     }
    }
   }
   catch (Java.Lang.Exception e)
   {
    retval = false;
    Console.WriteLine("Root access rejected [" + e.Class.Name + "] : " + e.Message);
   }

   return retval;
  }
 }
}

Now after this you can check the access with this code and also if are sure that you have root access now you can run low level unix commands:

bool rootaccess = ExecuteAsRootBase.canRunRootCommands();
if(rootaccess){
 Java.Lang.Runtime.GetRuntime().Exec ("su -c" + "command to exec");
}

Theres is all for today you access to the full code source at my github:

https://github.com/AlejandroRuiz/Mono/tree/master/RootAccess

Happy Code


Comentarios

  1. Hi Author just now i found your blog its really awesome. Keep this work. It will more helpful for xamarin app developers.
    Hire affordable Xamarin Developer

    ResponderEliminar

Publicar un comentario

Entradas populares de este blog

Xamarin Month: Fall in Love with Xamarin.Forms Shell

ASP.NET Core Identity with Cosmos DB (MongoDB) Part2: ASP.NET Core Code

C# Interface Ejemplo Sencillo