How to call the method available in Android and iOS project from Xamarin Forms project?

thaufeethaufee Member ✭✭
edited June 13 in Xamarin.Forms

I do have a button in my Xamarin Forms Page. Whenever the button is clicked, I need to call the method in Android Project (in MainActivity.cs) if the device is Android and call the method in iOS Project (in AppDelegate.cs) if the device is iPhone.

Can someone help me how can I do this?

A method in Xamarin Forms

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

The method in MainActivity.cs and AppDelegate.cs

public void StartBeepWork()
{
    //process
}

Best Answers

  • thaufeethaufee ✭✭
    Accepted Answer

    A method in the Xamarin Forms should be like below:

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

    The > IBackgroundDependency should be like below:

    public interface IBackgroundDependency
    {
        void ExecuteCommand();
    }
    

    In your Android Project, create a class BackgroundDependency_Android.cs with below code:

    [assembly: Dependency(typeof(BackgroundDependency_Android))]
    namespace ProjectNamespace.Droid
    {
        public class BackgroundDependency_Android : Java.Lang.Object, IBackgroundDependency
        {
            public void ExecuteCommand()
            {
                StartBeepWork();
            }
        }
    }
    

    In your iOS Project, create a class BackgroundDependency_iOS.cs with below code:

    [assembly: Dependency(typeof(BackgroundDependency_iOS))]
    namespace ProjectNamespace.iOS
    {
        public class BackgroundDependency_iOS : IBackgroundDependency
        {
            public BackgroundDependency_iOS()
            {
            }
    
            public void ExecuteCommand()
            {
                StartBeepWork();
            }
    
        }
    }
    

Answers

Sign In or Register to comment.