【问题标题】:How to call the method available in Android and iOS project from Xamarin Forms project?如何从 Xamarin Forms 项目调用 Android 和 iOS 项目中可用的方法?
【发布时间】:2019-06-13 07:03:36
【问题描述】:

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

有人可以帮我怎么做吗?

Xamarin 表单中的方法

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

MainActivity.cs 和 AppDelegate.cs 中的方法

public void StartBeepWork()
{
    //process
}

【问题讨论】:

    标签: c# xamarin.forms dependencies


    【解决方案1】:

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

    public interface IBeepWork
    {
        void Start();
    }
    

    在您的 Android 项目中:

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

    你可以对 iOS 项目做同样的事情:

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

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

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

    【讨论】:

    • 是的。这就是我要找的。谢谢你的例子。
    • 请帮帮我。我需要做完全相反的事情。我需要调用save方法,它位于android项目的公共项目中,我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多