Xamarin
不同平台的运行代码
有时候需要在不同的平台上,运行不同的代码,下面就看是说明这个需求怎么实现。
在共享的目录中处理逻辑
在Xamarin.Forms
中,有这些指令可以使用:#if, #elif, and endif.
来看一下代码
#if __IOS__
using UIKit;
#elif __ANDROID__
using Android.OS;
#elif WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_UWP
using Windows.Security.ExchangeActiveSyncProvisioning;
#endif
这就是一个完整的体系,这些指令不止作用于开头,类里面也是可以使用的。
使用各个平台的共同类
如果要实现在不同平台调用不同平台的类,则需要在每个平台的工程上都要新建一个共同类,类名、方法和命名空间,要完全一致。
Xamarin Forms
PlatformInfo platformInfo = new PlatformInfo();
IOS
using System;
using UIKit;
namespace PlatInfoSap2
{
public class PlatformInfo
{
UIDevice device = new UIDevice();
public string GetModel()
{
return device.Model.ToString();
}
public string GetVersion()
{
return String.Format("{0} {1}", device.SystemName,
device.SystemVersion);
}
}
}
Android
using System;
using Android.OS;
namespace PlatInfoSap2
{
public class PlatformInfo
{
public string GetModel()
{
return String.Format("{0} {1}", Build.Manufacturer,
Build.Model);
}
public string GetVersion()
{
return Build.VERSION.Release.ToString();
}
}
}
第二种方式使用各个平台的类
一个库通常不能访问应用程序项目中的类,那么我们是可以使用DependencyService
类来调用,各个平台的方法。
怎么做?
1.在Xamarin Forms
平台上创建一个接口,让各个平台来实现该接口
2.每个平台实现了该接口后,必须注册在Dependency
属性上
3.在Xamarin Forms
中,使用DependencyService
类的Get
方法就可以调用了
代码
IPlatformInfo platformInfo = DependencyService.Get<IPlatformInfo>();
modelLabel.Text = platformInfo.GetModel();
versionLabel.Text = platformInfo.GetVersion();