如何从 Xamarin Forms 项目调用 Android 和 iOS 项目中可用的方法?

Moh*_*eeq 1 c# dependencies xamarin.forms

我的 Xamarin Forms 页面中有一个按钮。每当单击按钮时,如果设备是 Android,我需要调用 Android 项目(在 MainActivity.cs 中)中的方法,如果设备是 iPhone,我需要调用 iOS 项目(在 AppDelegate.cs 中)中的方法。

有人可以帮我我该怎么做吗?

Xamarin Forms 中的方法

private async void BtnStart_Clicked(object sender, EventArgs e)
{
    //if Android call StartBeepWork in MainActivity.cs else call StartBeepWork in AppDelegate.cs
}
Run Code Online (Sandbox Code Playgroud)

MainActivity.cs和AppDelegate.cs中的方法

public void StartBeepWork()
{
    //process
}
Run Code Online (Sandbox Code Playgroud)

Kne*_*lis 5

这就是DependencyService的用途。因此,您在共享项目中定义接口,并在特定于平台的项目中为每个支持的平台实现它。

public interface IBeepWork
{
    void Start();
}
Run Code Online (Sandbox Code Playgroud)

在您的 Android 项目中:

[assembly: Dependency(typeof(BeepWorkAndroid))]
public class BeepWorkAndroid : IBeepWork
{
    public void Start()
    {
        // Android-specific implementation
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以对 iOS 项目执行相同的操作:

[assembly: Dependency(typeof(BeepWorkiOS))]
public class BeepWorkiOS : IBeepWork
{
    public void Start()
    {
        // iOS-specific implementation
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的代码隐藏中,您可以通过调用来解析特定于平台的实例DependencyService.Get

private async void BtnStart_Clicked(object sender, EventArgs e)
{
    DependencyService.Get<IBeepWork>().Start();
}
Run Code Online (Sandbox Code Playgroud)