How to know the current OS / platform of the execu

2019-04-18 16:05发布

问题:

Using Xamarin.Android and Xamarin.iOS, I need to now the current OS in a shared code section. Be it an enum, an int or a string, it doesn't matter.

I tried this:

System.Environment.OSVersion

Which is always "Unix" with some kernel version informations.

There are info on Android for example like

Android.OS.Build.VERSION

But it needs to be in the Android specific code section. Is there any way of knowing the current OS in a common library?

回答1:

You can also try this and its probably the best solution I found :

if(Device.RuntimePlatform == Device.iOS)
{
    //iOS stuff
}
else if(Device.RuntimePlatform == Device.Android)
{

}


回答2:

I'm using DeviceInfo plugin. It supports Android, iOs, Windows Phone Silverlight, Windows Phone RT, Windows Store RT, Windows 10 UWP and it works perfectly.

It can be used in PCL like this (you must add the plugin to the platform projects and to PCL):

var platform = CrossDeviceInfo.Current.Platform;
    switch(platform){
        case Platform.iOS:
            // iOS
            break;
        case Platform.Android:
            // Android
            break; 
    }

This kind of code isn't a good practice in PCL, its better to use Dependency Injection (this plugin use that) to customize platform specific behaviour.



回答3:

Using reflection, try to retrieve the value of the Monotouch.Version property (and the equivalent for MfA: Android.OS.Build.VERSION). One of the calls will fail, the other should succeed; that's why you have to use reflection. That's for a real runtime check.

But as your app is compiled twice, you can fix that value at compile time.

#if MONOTOUCH
    var platform = "iOS"
#else
    var platform = "Android"
#endif