Skip to content

Instantly share code, notes, and snippets.

@ak47akshaykulkarni
Last active December 8, 2021 05:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ak47akshaykulkarni/a294e6f2620f3c98dbb545a04db77220 to your computer and use it in GitHub Desktop.
Save ak47akshaykulkarni/a294e6f2620f3c98dbb545a04db77220 to your computer and use it in GitHub Desktop.
Exit Android application if device is rooted: Xamarin.Forms | Xamarin.Android
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Java.IO;
using Java.Lang;
using Process = Android.OS.Process;
using String = System.String;
namespace App1.Droid
{
[Activity(Label = "App1", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
if (!RootUtil.IsDeviceRooted())
{
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
else
{
Toast.MakeText(ApplicationContext, "Not supported on Rooted Devices", ToastLength.Long).Show();
FinishAffinity();
}
}
}
public class RootUtil
{
public static bool IsDeviceRooted()
{
return checkRootMethod1() || checkRootMethod2() || checkRootMethod3();
}
private static bool checkRootMethod1()
{
String buildTags = Android.OS.Build.Tags;
return buildTags != null && buildTags.Contains("test-keys");
}
private static bool checkRootMethod2()
{
string[] paths = { "/system/app/Superuser.apk", "/sbin/su", "/system/bin/su", "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su",
"/system/bin/failsafe/su", "/data/local/su", "/su/bin/su"};
foreach (string path in paths)
{
if (new File(path).Exists()) return true;
}
return false;
}
private static bool checkRootMethod3()
{
Java.Lang.Process process = null;
try
{
process = Runtime.GetRuntime().Exec(new string[] { "/system/xbin/which", "su" });
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.InputStream));
if (bufferedReader.ReadLine() != null) return true;
return false;
}
catch (Throwable t)
{
return false;
}
finally
{
if (process != null) process.Destroy();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment