DependencyService 类是允许 Xamarin.Forms 应用程序从共享代码 调用本机平台功能的服务定位器。
必须使用 DependencyService 注册平台实现,然后从共享代码进行解析,才能调用它们。
用DependencyService的理由: 由于 Xamarin.Forms 不包含此功能,因此有必要使用 DependencyService 来访问每个平台上的本机 API。
介绍
使用 DependencyService 调用本机平台功能的过程用于:
- 有关详细信息,请参阅创建接口。
- 有关详细信息,请参阅在各个平台上实现接口。
- 有关详细信息,请参阅注册平台实现。
- 有关详细信息,请参阅解析平台实现。
下图说明了如何在 Xamarin.Forms 应用程序中调用本机平台功能:
1、创建接口
应将此接口置于共享代码项目中。
下面的示例说明了可用于检索设备方向的 API 接口:
public interface IDeviceOrientationService { DeviceOrientation GetOrientation(); }
2、在各个平台上实现此接口
创建定义与本机平台功能交互的 API 的接口后,必须在各个平台项目中实现此接口。
Android
下面的代码示例演示 Android 上的 IDeviceOrientationService 接口实现:
namespace DependencyServiceDemos.Droid { public class DeviceOrientationService : IDeviceOrientationService { public DeviceOrientation GetOrientation() { IWindowManager windowManager = Android.App.Application.Context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>(); SurfaceOrientation orientation = windowManager.DefaultDisplay.Rotation; bool isLandscape = orientation == SurfaceOrientation.Rotation90 || orientation == SurfaceOrientation.Rotation270; return isLandscape ? DeviceOrientation.Landscape : DeviceOrientation.Portrait; } } }