Detect in Xamarin.Forms if the app is running in simulator or on real device

Sometimes you need to detect if you are using simulator (emulator) or real device, typical example can be the situation when you are running the webservices used by your application on the same computer where you are running simulator and you would like quickly check how it is working altogether.

There are separate solutions for iOS here:
https://developer.xamarin.com/recipes/ios/general/projects/environment_checks
And for Android here:
http://forums.xamarin.com/discussion/34275/detect-if-simulator-or-device

I just gathered them altogether and created dependency service for Xamarin.Forms application

Create the file “PlatformSpecificInterface.cs” in your main project and put there the code below:

using System;
using Xamarin.Forms;

namespace your_namespace
{
  public interface PlatformSpecificInterface {
    bool CheckIfSimulator();
  }
}

Create the file “PlatformSpecificImplementation.cs” in Android project and put there the code below:

using System;
using Android.OS;
[assembly: Xamarin.Forms.Dependency (typeof (your_namespace.Droid.PlatformSpecific_Droid))]
namespace your_namespace.Droid
{
  public class PlatformSpecific_Droid: PlatformSpecificInterface {
    public bool CheckIfSimulator() {
      if (Build.Fingerprint != null) {
        if (Build.Fingerprint.Contains("vbox") || 
            Build.Fingerprint.Contains("generic"))
          return true;
      }
      return false;
    }
  }
}

Create the file “PlatformSpecificImplementation.cs” in iOS project and put there the code below:

using System;
using ObjCRuntime;
[assembly: Xamarin.Forms.Dependency (typeof (your_namespace.iOS.PlatformSpecific_iOS))]
namespace your_namespace.iOS
{
  public class PlatformSpecific_iOS: PlatformSpecificInterface {
    public bool CheckIfSimulator() {
      if (Runtime.Arch == Arch.SIMULATOR)
        return true;
      return false;
    }
  }
}

Simply change the name of the namespace to the one you are using in your project (marked with RED) and you can call wherever you are in your main project the method

DependencyService.Get<PlatformSpecificInterface>().CheckIfSimulator()

to get the information about your currently running environment.

Enjoy!

, , , , ,

  1. #1 by Jay Peterson on October 12, 2016 - 17:58

    Great Job!! I was looking for this exact thing. Thanks!!

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: