フレームワークモジュール / アプリケーション

アプリケーション

アプリケーション・モジュールは、プラットフォーム固有のアプリケーションの実装上の抽象化を提供します。 このモジュールを使用すると、アプリケーションの起動からアプリケーションイベントの処理、プラットフォーム固有のロジックの作成まで、NativeScriptアプリケーションのライフサイクルを管理できます。

必要なapplicationモジュールは、以下のコードスニペット全体で使用されます。

const applicationModule = require("tns-core-modules/application");
import * as applicationModule from "tns-core-modules/application";

Androidブロードキャストレシーバー

アプリケーションモジュールのAndroid固有プロパティ

アプリケーションモジュールは、Androidのアプリ(app)、コンテキスト(context)、アクティビティ(avtivity)にアクセスするためのAndroid固有のプロパティをいくつか提供します。

// import { android as androidApp } from "tns-core-modules/application";
let isPaused = androidApp.paused; // e.g. false
let packageName = androidApp.packageName; // The package ID e.g. org.nativescript.nativescriptsdkexamplesng
let nativeApp = androidApp.nativeApp; // The native APplication reference
let foregroundActivity = androidApp.foregroundActivity; // The current Activity reference
let context = androidApp.context; // The current Android context

ブロードキャストレシーバーの登録(Android)

ブロードキャストレシーバー(Android)を登録して、デバイスのバッテリー寿命を確認します。 この例は、tns-platform-declarationsプラグインを使用して、ネイティブAndroid APIにアクセスする方法も示しています。

if (platformModule.isAndroid) {
    // use tns-platform-dclarations to acces native APIs (e.g. ndroid.content.Intent)
    const receiverCallback = (androidContext, intent) => {
        const level = intent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1);
        const scale = intent.getIntExtra(android.os.BatteryManager.EXTRA_SCALE, -1);
        const percent = (level / scale) * 100.0;
        vm.set("batteryLife", percent.toString());
    };

    applicationModule.android.registerBroadcastReceiver(
        android.content.Intent.ACTION_BATTERY_CHANGED,
        receiverCallback
    );
}
if (isAndroid) {
    // use tns-platform-dclarations to access native APIs (e.g. android.content.Intent)
    let receiverCallback = (androidContext, intent) => {
        const level = intent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1);
        const scale = intent.getIntExtra(android.os.BatteryManager.EXTRA_SCALE, -1);
        const percent = (level / scale) * 100.0;
        vm.set("batteryLife", percent.toString());
    };

    applicationModule.android.registerBroadcastReceiver(
        android.content.Intent.ACTION_BATTERY_CHANGED,
        receiverCallback
    );
}

ブロードキャストレシーバーの登録解除(Android)

applicationModule.android.unregisterBroadcastReceiver(android.content.Intent.ACTION_BATTERY_CHANGED);
applicationModule.android.unregisterBroadcastReceiver(android.content.Intent.ACTION_BATTERY_CHANGED);

デモソース


アプリケーションイベント

アプリケーションモジュールは、さまざまなアプリケーションの状態を処理するためのクロスプラットフォームアプリケーションイベントを提供します。 ユーザーは、提供されたアプリケーションイベントを使用して、起動、再開、一時停止、および終了状態を処理したり、画面の向き、不明なエラー、低メモリイベントに関連するロジックを提供したりできます。

アプリケーションメソッドonを使用して、イベントリスナーを追加します。

Launchイベント

launchListener = (args) => {
    // The root view for this Window on iOS or Activity for Android.
    // If not set a new Frame will be created as a root view in order to maintain backwards compatibility.
    console.log("Root View: ", args.root);
    console.log("The appication was launched!");
    vm.set("resumeEvent", "The appication was launched!");
};
applicationModule.on(applicationModule.launchEvent, launchListener);
launchListener = (args) => {
    // The root view for this Window on iOS or Activity for Android.
    // If not set a new Frame will be created as a root view in order to maintain backwards compatibility.
    console.log("Root View: ", args.root);
    console.log("The appication was launched!");
    vm.set("resumeEvent", "The appication was launched!");
};
applicationModule.on(applicationModule.launchEvent, launchListener);

Suspendイベント

suspendListener = (args) => {
    console.log("The appication was suspended!");
    vm.set("suspendEvent", "The appication was suspended!");
};
applicationModule.on(applicationModule.suspendEvent, suspendListener);
suspendListener = (args) => {
    console.log("The appication was suspended!");
    vm.set("suspendEvent", "The appication was suspended!");
};
applicationModule.on(applicationModule.suspendEvent, suspendListener);

Resumeイベント

resumeListener = (args) => {
    console.log("The appication was resumed!");
    vm.set("resumeEvent", "The appication was resumed!");
};
applicationModule.on(applicationModule.resumeEvent, resumeListener);
resumeListener = (args) => {
    console.log("The appication was resumed!");
    vm.set("resumeEvent", "The appication was resumed!");
};
applicationModule.on(applicationModule.resumeEvent, resumeListener);

Exitイベント

exitListener = (args) => {
    console.log("The appication was closed!");
};
applicationModule.on(applicationModule.exitEvent, exitListener);
exitListener = (args) => {
    console.log("The appication was closed!");
};
applicationModule.on(applicationModule.exitEvent, exitListener);

Displayedイベント

displayedListener = (args) => {
    console.log("NativeScript displayedEvent!");
    vm.set("displayedEvent", "The appication is displayed!");
};
applicationModule.on(applicationModule.displayedEvent, displayedListener);
displayedListener = (args) => {
    console.log("NativeScript displayedEvent!");
    vm.set("displayedEvent", "The appication is displayed!");
};
applicationModule.on(applicationModule.displayedEvent, displayedListener);

Low Memoryイベント

lowMemoryListener = (args) => {
    // the instance that has raidsed the event
    console.log("Instance: ", args.object);
};
applicationModule.on(applicationModule.lowMemoryEvent, lowMemoryListener);
lowMemoryListener = (args) => {
    // the instance that has raidsed the event
    console.log("Instance: ", args.object);
};
applicationModule.on(applicationModule.lowMemoryEvent, lowMemoryListener);

Orientation Changedイベント

orientationChangedListener = (args) => {
    // orientationChangedEventData.newValue: "portrait" | "landscape" | "unknown"
    console.log("Orientation: ", args.newValue);
    vm.set("orientation", args.newValue);
};
applicationModule.on(applicationModule.orientationChangedEvent, orientationChangedListener);
orientationChangedListener = (args) => {
    // orientationChangedEventData.newValue: "portrait" | "landscape" | "unknown"
    console.log("Orientation: ", args.newValue);
    vm.set("orientation", args.newValue);
};
applicationModule.on(applicationModule.orientationChangedEvent, orientationChangedListener);

キャッチされないエラーイベント

uncaughtErrorListener = (args) => {
    // UnhandledErrorEventData.error: NativeScriptError
    console.log("NativeScript Error: ", args.error);
};
applicationModule.on(applicationModule.uncaughtErrorEvent, uncaughtErrorListener);
uncaughtErrorListener = (args) => {
    // UnhandledErrorEventData.error: NativeScriptError
    console.log("NativeScript Error: ", args.error);
};
applicationModule.on(applicationModule.uncaughtErrorEvent, uncaughtErrorListener);

イベントリスナーの解除

アプリケーションメソッドoffを使用して、登録済みのイベントリスナーを削除します。

applicationModule.off(applicationModule.launchEvent, launchListener);
applicationModule.off(applicationModule.resumeEvent, resumeListener);
applicationModule.off(applicationModule.suspendEvent, suspendListener);
applicationModule.off(applicationModule.exitEvent, exitListener);
applicationModule.off(applicationModule.displayedEvent, displayedListener);
applicationModule.off(applicationModule.lowMemoryEvent, lowMemoryListener);
applicationModule.off(applicationModule.orientationChangedEvent, orientationChangedListener);
applicationModule.off(applicationModule.uncaughtErrorEvent, uncaughtErrorListener)
applicationModule.off(applicationModule.launchEvent, launchListener);
applicationModule.off(applicationModule.resumeEvent, resumeListener);
applicationModule.off(applicationModule.suspendEvent, suspendListener);
applicationModule.off(applicationModule.exitEvent, exitListener);
applicationModule.off(applicationModule.displayedEvent, displayedListener);
applicationModule.off(applicationModule.lowMemoryEvent, lowMemoryListener);
applicationModule.off(applicationModule.orientationChangedEvent, orientationChangedListener);
applicationModule.off(applicationModule.uncaughtErrorEvent, uncaughtErrorListener);

デモソース


プラットフォームの確認

コードがどのプラットフォームで実行されているかを確認する必要がある場合は、次のコードを使用します。

if (application.android) {
    console.log("We are running on Android device!");
} else if (application.ios) {
    console.log("We are running on iOS device");
}
if (application.android) {
    console.log("We are running on Android device!");
} else if (application.ios) {
    console.log("We are running on iOS device");
}

デモソース


iOS通知オブザーバー

アプリケーションモジュールのiOS固有プロパティ

アプリケーションモジュールは、iOSアプリ、デリゲート、ルートビューコントローラーなどにアクセスするための多数のiOS固有のプロパティを提供します。

// import { ios as iosApp } from "tns-core-modules/application";

// https://developer.apple.com/documentation/uikit/uiapplicationdelegate?language=objc
let delegate = iosApp.delegate; // the iOS application delegate

let nativeApp = iosApp.nativeApp; // The native iOS app

// https://developer.apple.com/documentation/uikit/uiwindow/1621581-rootviewcontroller?language=objc
let rootController = iosApp.rootController; // the iOS rootViewController

let window = iosApp.window; // UIWindow

通知オブザーバーの追加(iOS)

iOSの通知オブザーバーを追加するにはaddNotificationObserverを使用します。

if (application.ios) {
    utilsModule.ios.getter(UIDevice, UIDevice.currentDevice).batteryMonitoringEnabled = true;
    vm.set("batteryLife", +(utilsModule.ios.getter(UIDevice, UIDevice.currentDevice).batteryLevel * 100).toFixed(1));
    observer = application.ios.addNotificationObserver(UIDeviceBatteryLevelDidChangeNotification, (notification) => {
        // tslint:disable:max-line-length
        vm.set("batteryLife", +(utilsModule.ios.getter(UIDevice, UIDevice.currentDevice).batteryLevel * 100).toFixed(1));
    });
}
if (isIOS) {
    UIDevice.currentDevice.batteryMonitoringEnabled = true;
    vm.set(
        "batteryLife",
        +(UIDevice.currentDevice.batteryLevel * 100).toFixed(1)
    );
    observer = iosApp.addNotificationObserver(
        UIDeviceBatteryLevelDidChangeNotification,
        notification => {
            vm.set(
                "batteryLife",
                +(UIDevice.currentDevice.batteryLevel * 100).toFixed(1)
            );
        }
    );
}

通知オブザーバーの削除(iOS)

不要になったら、通知オブザーバーを削除します。

application.ios.removeNotificationObserver(observer, UIDeviceBatteryLevelDidChangeNotification);
iosApp.removeNotificationObserver(observer, UIDeviceBatteryLevelDidChangeNotification);

デモソース

入門

コアコンセプト

ユーザーインターフェース

ツール

ハードウェアアクセス

プラグインの開発

リリース

アプリテンプレート

パフォーマンスの最適化

フレームワークモジュール

ガイド

サポートを受ける

トラブルシューティング

Siedkick