How to register my own Application subclass in Xamarin.Android?

by admin

In Java We would add a line to the manifest and pass it the namespace and name of my application:

In Xamarin, there is the [Application] attribute but the documentation states that the Name member is not supported. So how do I get my subclass registered? Where to apply the attribute to?

If I add the attribute to my subclass, I get:

System.NotSupportedException: Unable to activate instance of type Android.MyApplication from native handle 14d00019

After Reading so many blogs I have resolved it,
I have Gone through the below official documentaion and found some important informations.

There are two scenarios in which the (IntPtr, JniHandleOwnership) constructor must be manually provided on a Managed Callable Wrapper subclass:

Android.App.Application is subclassed. Application is special; the default Applicaton constructor will never be invoked, and the (IntPtr, JniHandleOwnership) constructor must instead be provided.

Virtual method invocation from a base class constructor.

Note that (2) is a leaky abstraction. In Java, as in C#, calls to virtual methods from a constructor always invoke the most derived method implementation. For example, the TextView(Context, AttributeSet, int) constructor invokes the virtual method TextView.getDefaultMovementMethod(), which is bound as the TextView.DefaultMovementMethod property. Thus, if a type LogTextBox were to (1) subclass TextView, (2) override TextView.DefaultMovementMethod, and (3) activate an instance of that class via XML, the overridden DefaultMovementMethod property would be invoked before the ACW constructor had a chance to execute, and it would occur before the C# constructor had a chance to execute.

This is supported by instantiating an instance LogTextBox through the LogTextView(IntPtr, JniHandleOwnership) constructor when the ACW LogTextBox instance first enters managed code, and then invoking the LogTextBox(Context, IAttributeSet, int) constructor on the same instance when the ACW constructor executes.


public class MyApplication : Application
public MyApplication(IntPtr handle, JniHandleOwnership ownerShip) : base(handle, ownerShip)

Leave a Reply

Your email address will not be published.