简体   繁体   中英

Create an Android Service in Xamarin and invoke its methods from a Java native client app

We have huge algorithms in .net that we have ported to Xamarin. Now our customers ask us to use them under Android / Java. My idea was to create an Android Service with Xamarin, so that our customers can write java client to start the service like this:

Intent testintent = new Intent ("com.swe.TestService");
StartService (testintent);

The question is: once launched, how can they invoke the methods that we expose on the service? For simplicity, for example, we can assume we have a method like this on the service:

public int Sum(int first, int second)
{
   return first + second;
}

Thanks in advance for help!

I'm not sure if you guys had figured it out or not. Our experience showed the solution not working in the simple way as in your post.

Xamarin doesn't support Java calling C# code, so you can't mix Java and C# code together. You are right in putting C# into a service but the service needs to be a Remote service!! Not only stared is the service, but also bound with the service. Binding is an IPC in Android. It is message driven. You can't simply invoke the C# method in Java. You have to define own protocol and implement message handlers in both C# and Java. The method calls and result returns have to transform into message sent out and back.

Remote service binding itself is similar in both Java and C#. Viewing the sample code in Android SDK ApiDemo is very helpful.

I'm also thinking about this kind of IPC. https://developer.xamarin.com/guides/android/application_fundamentals/services/out-of-process-services/

But it looks like overkill to me to deal with services if I can just setup client-server communication via UDP socket.

Old-school, old-fashioned, ultimately universal solution using UDP. I used this to connect Unity3D and regular C# application with success. Should also be working in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM