AIDL

Using AIDL files in Xamarin

 

If you ever need to use inter process communication you have the option of using AIDL (Android Interface Definition Language). To do so, import your AIDL file(s) into your Xamarin solution. Define your class that will call the service described by the aidl file. Init an intent to bind to the Service. Then implement a ServiceConnection class that inherits from java.lang.Object and implements IServiceConnection.


using System;
using Android.Content;
using Aidlservice;
using Android.OS;
using Android.App;

namespace AidlExample
{
    public class MyClass
    {

        IWoyouService woyouService;
        WoyouServiceConnection serviceConn;

        public void Init(Context context)
        {
            serviceConn = new WoyouServiceConnection();

            var intent = new Intent();
            intent.SetPackage("aidlservice");

            intent.SetAction("aidlservice.IWoyouService");
            context.StartService(intent);
            context.BindService(intent, serviceConn, Bind.AutoCreate);
        }

        public void DoSomething(String msg, ICallback callback)
        {
            woyouService = serviceConn.GetService();

            if (woyouService != null)
            {
                try
                {
                    woyouService.MyMethod(msg, callback);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.Print(string.Format("Error: {0}", ex.Message));
                }
            }
        }
    }

    public class WoyouServiceConnection : Java.Lang.Object, IServiceConnection
    {
        public new void Dispose()
        {
            base.Dispose();
        }

        public IWoyouService GetService()
        {
            return woyouService;
        }

        IWoyouService woyouService = null;

        public void OnServiceDisconnected(ComponentName name)
        {
            woyouService = null;
        }        

        public void OnServiceConnected(ComponentName name, IBinder service)
        {
            woyouService = IWoyouServiceStub.AsInterface(service);
        }
    }

}
 

And remember to set the build action of the AIDL files to AndroidInterfaceDescription