如何在 Xamarin.Android 中注册我自己的应用程序子类? [英] How to register my own Application subclass in Xamarin.Android?

查看:16
本文介绍了如何在 Xamarin.Android 中注册我自己的应用程序子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

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

推荐答案

找到了.文档已过时.你需要一个带有两个参数的特殊c'tor你必须添加[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.)

这篇关于如何在 Xamarin.Android 中注册我自己的应用程序子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆