I am using MvvmCross framework and I want to invoke a method defined in Android project from Core project. I tried This solution but I am getting the following error
Unhandled Exception: System.InvalidOperationException: You MUST call Xamarin.Forms.Init(); prior to using it. occurred
As i am not using Xamarin Forms so I know this will not work. Is there any workaround or any other way to accomplish this?
Finally, found the answer. Here are the steps
I - Get the nuget package "Xamarin.Forms.Labs" in your android (UI) project, apparently now it is Scorchio.NinjaCoder.Xamarin.Forms.Labs
II - Use the following code in SetUp.cs as shown below
using Android.Content;
using MvvmCross.Core.ViewModels;
using MvvmCross.Droid.Platform;
using Xamarin.Forms.Labs.Services;
namespace SomeProject.UI.Droid
{
public class Setup : MvxAndroidSetup
{
public Setup(Context applicationContext) : base(applicationContext)
{
var resolverContainer = new SimpleContainer();
resolverContainer.Register<IViewMethodCallService>(t => new ViewMethodCallService());
Resolver.SetResolver(resolverContainer.GetResolver());
}
protected override IMvxApplication CreateApp()
{
return new App();
}
}
}
Where "IViewMethodCallService" is the interface, having the signature of the method e.g. TestMethod(), in your PCL project and "ViewMethodCallService.cs" is implementation of that interface in UI or Android project.
III - Now create an object of the interface "IViewMethodCallService" as shown below
IViewMethodCallService callMethod= Resolver.Resolve<IViewMethodCallService>();
callMethod.TestMethod();
The "ViewMethodCallService.cs" looks like this
using Android.Util;
[assembly: Xamarin.Forms.Dependency(typeof(ViewMethodCallService))]
namespace SomeProject.UI.Droid
{
public class ViewMethodCallService : Java.Lang.Object, IViewMethodCallService
{
public ViewMethodCallService()
{
}
public void TestMethod()
{
Log.Info("Hurrayyyyyyyyyyyyyyyyyyyyyyyyyy", "And I am calling this service");
}
}
}
I got this answer from this question and the link mentioned in question if you wish to do more research. Hope this help someone.