如何在 Nativescript 中正确获取 Android Application Context

How to properly get Android Application Context in Nativescript

我正在 Android 上创建一个具有一些特定本机处理的 Nativescript 应用程序。由于需要在 Android 的 onCreate() 方法上初始化插件,我通过以下方式扩展了 Nativescript 的主应用程序: https://docs.nativescript.org/core-concepts/android-runtime/advanced-topics/extend-application-activity

我还可以确认我的自定义 class 已正确设置并在放置日志并使用 onCreate() 方法后正常工作:

应用所需初始化之前的代码:

import { isAndroid } from "tns-core-modules/ui/page/page";
import * as application from "tns-core-modules/application";

declare var co;
declare var android;
declare var applicationContext;

// const context = android.content.Context;
const BleManager = co.igloohome.ble.lock.BleManager;
var utilsModule = require("tns-core-modules/utils/utils");

@JavaProxy("org.myApp.Application")
class Application extends android.app.Application {
    onCreate(): void {
        super.onCreate();

        console.log("OnCreate() called");

    }

    attachBaseContext(baseContext: any) { // android.content.Context
        super.attachBaseContext(baseContext);
    }
}

使用此代码,我能够在日志中看到 "OnCreate() called",这意味着我的扩展正在运行。

现在,我正在尝试初始化一个 SDK,所以我是根据这样的文档来完成的:

import { isAndroid } from "tns-core-modules/ui/page/page";
import * as application from "tns-core-modules/application";

declare var co;
declare var android;
declare var applicationContext;

// const context = android.content.Context;
const BleManager = co.igloohome.ble.lock.BleManager;
var utilsModule = require("tns-core-modules/utils/utils");

@JavaProxy("org.myApp.Application")
class Application extends android.app.Application {
    onCreate(): void {
        super.onCreate();

        console.log("OnCreate() called");

        //Setup Ble SDK
        BleManager(utilsModule.ad.getApplicationContext()).setDebug(true)

        console.log("OnCreate() end");
    }

    attachBaseContext(baseContext: any) { // android.content.Context
        super.attachBaseContext(baseContext);
    }
}

不幸的是它吐出一个错误:

JS: OnCreate() called
System.err: java.lang.RuntimeException: Unable to create application org.myApp.Application: com.tns.NativeScriptException:
System.err: Calling js method onCreate failed
System.err:
System.err: Error: Trying to link invalid 'this' to a Java object

我也可以确认 "BleManager" 对象不是未定义的。仅此而已,我认为这可能是由于我传递了错误的应用程序上下文。 (该方法需要应用程序上下文来初始化)。

如何在 Nativescript 中获取 Android 的主应用程序上下文?

我相信你可以这样做:

import * as application from '@nativescript/core/application';


const ctx = application.android.context;

或(如果您没有使用作用域包):

import * as application from 'tns-core-modules/application';


const ctx = application.android.context;