NativeScript Core

Application

The Application module provides abstraction over the platform-specific Application implementations. The module lets you manage the lifecycle of your NativeScript applications from starting the application to handling application events and creating platform-specific logic.

The pre-required application module is used throughout the following code snippets.

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

Android Broadcast Receiver

Application Module Android Specific Properties

The application module provides a number of Android specific properties to access the Android app, context and activities.

// 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

Registering a Broadcast Receiver (Android)

Registering a broadcast receiver (Android) to check the device's battery life. The example also demonstrates how to access the native Android API using tns-platform-declarations plugin.

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
    );
}

Unregistering a Broadcast Receiver (Android)

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

Improve this document

Demo Source


Application Events

The application module provides cross-platform application events to handle different application states. With the provided application events the user can handle launch, resume, suspend and exit states or provide logic related to the screen orientation, uncaught errors and low memory events.

Use the application method on to add event listeners.

Launch Event

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 Event

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 Event

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 Event

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 Event

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 Event

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 Event

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);

Uncaught Error Event

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);

Unsubscribing Event Listener

Use the application method off to remove the registered event listeners.

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);

Improve this document

Demo Source


Check Platform

Use the following code in case you need to check somewhere in your code the platform you are running against:

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");
}

Improve this document

Demo Source


iOS Notification Observer

Application Module iOS Specific Properties

The application module provides a number of iOS specific properties to access the iOS app, delegate and root view controller, etc..

// 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

Adding a Notification Observer (iOS)

Use addNotificationObserver to add iOS notifications observer

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)
            );
        }
    );
}

Removing a Notification Observer (iOS)

When no longer needed, remove the notification observer

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

Improve this document

Demo Source