Implementing IJavaObject on MonoDroid

Stuart picture Stuart · Dec 20, 2011 · Viewed 10.7k times · Source

I'm currently trying to implement an ILocationListener on a class in order to receive GPS updates - this is not on an Activity, just a normal C# class.

As part of the ILocationListener contract I need to support I JavaObject:

    public IntPtr Handle
    {
        get { throw new NotImplementedException(); }
    }

What should I do for this?

Also, are there any good documents and/or blog posts out there which talk about how C# classes and Java objects are bound together in MonoDroid - if I can find those documents, then I probably won't need to ask questions like this and I'll hopefully also be writing much better code.

Thanks

Answer

Greg Shackles picture Greg Shackles · Dec 20, 2011

Taken from Xamarin's docs:

There are times when you may need to implement an Android interface, such as Android.Content.IComponentCallbacks. Since all Android classes and interface extend the Android.Runtime.IJavaObject interface, the question arises: how do we implement IJavaObject?

The question was answered above: the reason all Android types need to implement IJavaObject is so that MonoDroid has an Android callable wrapper to provide to Android, i.e. a Java proxy for the given type. Since monodroid.exe only looks for Java.Lang.Object subclasses, and Java.Lang.Object implements IJavaObject, the answer is obvious: subclass Java.Lang.Object

Basically you should always inherit from Java.Lang.Object in these cases, as implementing IJavaObject yourself won't actually work since Mono for Android won't generate the callable wrapper.

If it helps, I have an example implementing ILocationListener available here. It implements it directly on an activity, but you can inherit from Java.Lang.Object instead of Activity.