wishmaster wishmaster - 2 months ago 29
Android Question

Xamarin.Android Detect Emulator

For iPhone I can detect that the app is running in a Simulator by doing this:

var isSumlator = ObjCRuntime.Runtime.Arch == ObjCRuntime.Arch.SIMULATOR;


What is the best equivalent for detecting the emulator in Xamarin.Android?

Answer

It depends upon your goal of if this is just for local debug testing or if you plan to leave it in your code for testing within an end-user environment.

As the world of Android is quite large, this is an ever evolving method based upon what we seen in the wild:

public bool isEmulator(bool LicensedPlayers = false)
{
    var detect = 0;
    try
    {
        var teleManager = (TelephonyManager)GetSystemService(TelephonyService);
        string networkOperator = "";
        try
        {
            networkOperator = teleManager.NetworkOperator;
            if (LicensedPlayers)
            {
                if ((teleManager.NetworkOperatorName == "T-Mobile") && 
                    (Build.Radio == "unknown") && 
                    (Build.Serial == "unknown") && 
                    (Build.Manufacturer == "samsung"))
                {
                    D.WriteLine("BlueStacks (OS-X) Player");
                    detect += 1;
                }
            }
        }
        catch
        {
            networkOperator = "";
            D.WriteLine("TelephonyService Exceptiion, custom emulator");
            detect += 1;
        }
        if (networkOperator.Contains("Android"))
        {
            D.WriteLine("Google's Android Emulator");
            detect += 1;
        }
    }
    catch
    {
        D.WriteLine("TelephonyService not available, custom emulator");
        detect += 1;
    }
    if (LicensedPlayers)
    {
        if (Build.Display.Contains("andy") || (Build.Hardware.Contains("andy")))
        {
            D.WriteLine("Andy Player");
            detect += 1;
        }
    }
    if (Build.Hardware.Contains("goldfish"))
    {
        D.WriteLine("Goldfish-based Emulator");
        detect += 1;
    }
    if (Build.Display.ToLowerInvariant().Contains("xamarin"))
    {
        D.WriteLine("Xamarin Android Player");
        detect += 1;
    }
    if (Build.Hardware.Contains("vsemu"))
    {
        D.WriteLine("Visual Studio Android Emulator");
        detect += 1;
    }
    if (Build.Host.Contains("genymobile") || (Build.Manufacturer.ToLowerInvariant().Contains("genymotion")))
    {
        D.WriteLine("Genymotion Android Emulator");
        detect += 1;
    }
    if (Build.Hardware.Contains("vbox") && Build.Hardware.Contains("86"))
    {
        D.WriteLine("VirtualBox-based Emulator");
        detect += 1;
    }
    return detect > 0;
}

Updated: Fixed XAP emulator detection on multiple platforms