Application
The Application class provides abstraction over the platform-specific application implementations. It lets you manage things such as handling lifecycle events of your application (cross-platform and/or native), sending Broadcasts on Android or adding a Notification observer on IOS.
Android
For android, you can access the main activity for the application, currently active activity, a method to register a broadcast receiver and other Android-specific properties and methods, as you will see below.
Android Properties
android
The property gives you the Nativescript wrapper, the AndroidApplication object, around the native android native application instance.
nativeApp
This is a native application reference.
Basically, it is the android.app.Application instance keeping track of the global application state.
From this object you can get methods such as getFilesDir()
, onLowMemory()
,etc.
Type: |
|
foregroundActivity
The reference to the currently active (loaded) android Activity. This property is automatically updated upon Activity events.
Type: |
|
startActivity
The main (start) Activity for the application.
Type: |
|
AndroidApplication Methods
registerBroadcastReceiver(intentFilter, onReceiveCallback)
Registers a BroadcastReceiver to be run in the main activity thread. The receiver will be called with any broadcast Intent that matches the intent filter, in the main application thread. For more information, please visit.
Parameter(s) | Definition |
---|---|
|
A string containing the intent filter. |
|
A callback function that will be called each time the receiver receives a broadcast. |
Since this code is Android specific, first check if isAndroid
is true.
Use the same for any Android-specific code to avoid code for Android to run on iOS and results in the app crashing.
import { isAndroid } from '@nativescript/core'
if (isAndroid) {
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
viewModel.set('batteryLife', percent.toString())
}
androidApp.registerBroadcastReceiver(
android.content.Intent.ACTION_BATTERY_CHANGED,
receiverCallback
)
}
import { isAndroid } from '@nativescript/core'
if (isAndroid) {
const receiverCallback = (
androidContext: globalAndroid.content.Context,
intent: globalAndroid.content.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
viewModel.set('batteryLife', percent.toString())
}
androidApp.registerBroadcastReceiver(
android.content.Intent.ACTION_BATTERY_CHANGED,
receiverCallback
)
}
getRegisteredBroadcastReceiver(intentFilter)
Gets a registered BroadcastReceiver for the specified intent filter.
Parameters | Definition |
---|---|
|
A string containing the intent filter for which the BroadcastReceiver. |
Android Activity lifecycles events
applicationModule.AndroidApplication.on('activityResumed', args => {
//handle the event here
})
Application.AndroidApplication.on('activityResumed', args => {
//handle the event here
})
Other Android Activity lifecycles events are:
-
activityCreated
-
activityDestroyed
-
activityStarted
-
activityPaused
-
activityStopped
-
saveActivityState
-
activityResult
-
activityBackPressed
-
activityNewIntent
-
activityRequestPermissions
iOS Properties
ios
The property gives you the Nativescript wrapper, the iOSApplication object, around the native iOS application instance.
Type: |
|
window
This property gives the key window, the container for your app views, and one of its roles is to deliver touch events to the views. Views are the user interface items such as button, label or scrollview.
Type: |
|
delegate
This returns the class you set (the best place to set it is in the app.js
or app.ts
, before Application.run()
) as a delegate or undefined if you didn’t set any.
The iOS system monitors the different states of your application and emits an event at each state.
To handle these lifecycle events, you have to write a class that extends UIResponder and implements UIApplicationDelegate classes and set the delegate
property to that class.
You then overwrite the methods from UIApplicationDelegate to handle the events.
Type: |
|
const MyDelegate = (function (_super) {
__extends(MyDelegate, _super)
function MyDelegate() {
_super.apply(this, arguments)
}
MyDelegate.prototype.applicationDidFinishLaunchingWithOptions = function (
application,
launchOptions
) {
console.log('applicationWillFinishLaunchingWithOptions: ' + launchOptions)
return true
}
MyDelegate.prototype.applicationDidBecomeActive = function (application) {
console.log('applicationDidBecomeActive: ' + application)
}
MyDelegate.ObjCProtocols = [UIApplicationDelegate]
return MyDelegate
})(UIResponder)
Application.ios.delegate = MyDelegate
@NativeClass()
class MyDelegate extends UIResponder implements UIApplicationDelegate {
public static ObjCProtocols = [UIApplicationDelegate]
applicationDidFinishLaunchingWithOptions(
application: UIApplication,
launchOptions: NSDictionary<string, any>
): boolean {
console.log('applicationWillFinishLaunchingWithOptions: ' + launchOptions)
return true
}
applicationDidBecomeActive(application: UIApplication): void {
console.log('applicationDidBecomeActive: ' + application)
}
}
Application.ios.delegate = MyDelegate
For a complete list of the iOS lifecycle events, visit UIApplicationDelegate.
iOSApplication Methods
addNotificationObserver(notificationName, onReceiveCallback: (notification))
Adds an observer to the default notification center for the specified notification. For more information, please visit.
Parameter(s) | Definition |
---|---|
|
A string containing the name of the notification. Find the possible values here |
|
A callback function that will be called each time the observer receives a notification for which it was registered. |
const observer = iOSApp.addNotificationObserver(
'myNotification',
(notification: NSNotification) => {}
)
const observer: any = iOSApp.addNotificationObserver(
UIDeviceOrientationDidChangeNotification, // For example
(notification: NSNotification) => {
//Handle the notification
}
)
removeNotificationObserver(observer, notificationName)
Removes the observer for the specified notification from the default notification center.
Parameters | Definition |
---|---|
|
The observer that was returned from the addNotificationObserver method. |
|
A string containing the name of the notification. |
|
A callback function that will be called each time the observer receives a notification. |
Cross-platform application events
These are Nativescript events for both platforms.
applicationModule.on('orientationChanged', args => {
console.log(args.eventName) // orientationChanged
})
Application.on('orientationChanged', (args: ApplicationEventData) => {
console.log(args.eventName) // orientationChanged
})
Other cross-platform events:
-
livesync
-
cssChanged
-
launch
-
displayed
-
suspend
-
resume
-
exit
-
lowMemory
-
uncaughtError
-
discardedError
-
orientationChanged
-
systemAppearanceChanged
-
fontScaleChanged