【问题标题】:Xamarin: Instantiate Xamarin.Droid or Xamarin.iOS ClassXamarin:实例化 Xamarin.Droid 或 Xamarin.iOS 类
【发布时间】:2015-08-24 01:58:20
【问题描述】:

我是 Xamarin 的新手,想在我的 Xamarin.Forms 应用程序中编写一个通用的跨平台代码,用于调用 Xamarin.Droid 或 Xamarin.iOS 中的特定于平台的实现。此平台特定实现用于使用平台的位置服务。

为此,我在我的 Xamarin.Forms 项目中定义了一个名为 ILocationTracker 的接口,如下所示:

public interface ILocationTracker
    {
        void Connect();

        void Disconnect();

        void startReceivingLocationUpdates(int priority, int fastestInterval, int interval);

    }

我在我的 Xamarin.Droid 项目文件夹中写了一个名为 AndroidLocationTracker 的类,它实现 ILocationTracker 接口,并遵循 Android 平台特定接口:

  1. IGooglePlayServicesClientConnectionCallbacks,
  2. IGooglePlayServicesClientOnConnectionFailedListener,
  3. Android.Gms.Location.ILocationListener

对于Android的具体实现,我指的是以下链接:http://developer.xamarin.com/guides/android/platform_features/maps_and_location/location/

对于类的实例化,我在 Xamarin.Forms 文件夹中的 MyView.xaml.cs 中执行以下操作:

    if (Device.OS == TargetPlatform.Android) {
                    var type = Type.GetType("MyProjectName.Droid.AndroidLocationTracker");
                    tracker = (ILocationTracker)Activator.CreateInstance(type);
}

但是,我得到运行时错误

java.lang.reflect.InvocationTargetException

谁能帮助我,如何调用平台特定的类? 我错过了什么吗?还是我走错了路?

【问题讨论】:

    标签: c# android xamarin xamarin.forms


    【解决方案1】:

    在特定于平台的代码中创建特定于平台的服务(在您的情况下为 AndroidLocationTracker)。 转到您的 Android 项目并在您的 MainActivity.cs 文件中创建实例。在依赖注入容器中注册您的实例。使用这种技术,您不再需要像现在使用 if (Device.OS == TargetPlatform.Android) {} 那样询问当前平台

    一个常见的容器是Mvx,并带有 MVVMCross (https://github.com/MvvmCross/MvvmCross/wiki/Service-Location-and-Inversion-of-Control)。

    Xamarin.Forms 自带 DependencyService (http://developer.xamarin.com/guides/cross-platform/xamarin-forms/dependency-service/)。您可以在文档中找到课程注册示例。您可以通过DependencyService.Get<ILocationTracker>() 在您的共享代码中创建新实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      • 2013-10-18
      • 2013-01-05
      • 1970-01-01
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多