如何在Xamarin.Android中注册我自己的Application子类?

问题描述:

我有

public class MyApp : Application

在Java中,我会在清单中添加一行,并将其传递给我的应用程序的名称空间和名称:

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

<application android:icon="@drawable/icon" android:label="@string/app_name"
    android:name="com.devahead.extendingandroidapplication.MyApplication">

在Xamarin中,有 [Application] 属性,但是文档指出 Name 成员是

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 TestClient_Android.MyApplication from native handle 14d00019

找到了它.该文档已过时.您将需要一个带有两个参数的特殊字符,并且必须添加 [Application] 属性:

Found it. The documentation is outdated. You will need a special c'tor with two parameters and you will have to add the [Application] attribute:

[Application]
public class MyApplication : Application
{
    public MyApplication(IntPtr handle, JniHandleOwnership ownerShip) : base(handle, ownerShip)
    {
    }
}

编辑:此外,似乎还必须重写OnCreate().如果只有 构造函数,则不会调用它.

In addition it seems one has to override OnCreate(). If you have only the constructor, it will not be called.

public override void OnCreate()
{
  // If OnCreate is overridden, the overridden c'tor will also be called.
  base.OnCreate();
}

编辑2015年11月::这是Xamarin文档的链接,该文档解释了为什么存在此行为.

EDIT November 2015: here's a link to the Xamarin documentation which explains why this behavior exists.

... Xamarin.Android通过添加一个在运行期间,将mono.MonoRuntimeProvider ContentProvider转换为AndroidManifest.xml构建过程.mono.MonoRuntimeProvider.attachInfo()方法是负责将Mono运行时加载到流程中.任何在此之前尝试使用Mono的尝试将失败.(注意:这是为什么要键入哪个子类Android.App.Application需要提供一个(IntPtr,JniHandleOwnership)构造函数,作为Application实例是在可以初始化Mono之前创建的.)

...Xamarin.Android hooks into this by adding a mono.MonoRuntimeProvider ContentProvider to AndroidManifest.xml during the build process. The mono.MonoRuntimeProvider.attachInfo() method is responsible for loading the Mono runtime into the process. Any attempts to use Mono prior to this point will fail. ( Note: This is why types which subclass Android.App.Application need to provide an (IntPtr, JniHandleOwnership) constructor, as the Application instance is created before Mono can be initialized.)