首页 > 解决方案 > 运行时的移动设备或模拟器

问题描述

我只想在真正的 android\iOS 设备上运行时启用记录器服务。是否有可能在核心项目级别的运行时知道我是使用 android\iOS 模拟器还是真实设备运行?

标签: xamarinxamarin.iosxamarin.android

解决方案


在 Core 项目中创建一个接口:

public interface IDevicePlatform 
{ 
    bool IsSimulator(); 
} 

iOS DependencyService注册/实现:

public class Platform_iOS : IDevicePlatform 
{  
    public IsSimulator() 
    { 
        return ObjCRuntime.Runtime.Arch == ObjCRuntime.Arch.SIMULATOR;
    }
}

Android DependencyService注册/实现:

public class Platform_Android : IDevicePlatform 
{ 
    public bool IsSimulator() 
    { 
        if (Build.Fingerprint != null) 
        { 
            if (Build.Fingerprint.Contains("vbox") ||  Build.Fingerprint.Contains("generic") || Build.Fingerprint.Contains("vsemu"))
                return true; 
        } 
        return false; 
    }
}

在 Core 中将其称为:

bool isSimulator = DependencyService.Get<IDevicePlatform>().IsSimulator();
if(isSimulator)
{
    //You are running on the Simulator
}
else
{
    //You are running on the real device
}

注意:iOS 实现是直截了当的,而 Android 是一个广阔的世界,所以,除了上面简单的 android 实现之外,还可以看看SushiHangover 的答案


推荐阅读