Fundamental Concepts
Application
Handling application global state
The Application class provides the wrapper around android.app.Application for Android and UIApplication for iOS. With this class you handle the app's lifecycle events, send Broadcasts on Android or add a Notification observer on IOS, etc.
Use Application class
Register a broadcast receiver
To register a broadcast receiver, you follow these 3 steps:
Import the
Application
class from@nativescript/core
.tsimport { Application, isAndroid } from '@nativescript/core'
Get the wrapper object for android.app.Application instance. Use the
android
property to get the wrapper around android.app.Application.tsconst androidApp: AndroidApplication = Application.android
Call the registerBroadcastReceiver method. Call the
registerBroadcastReceiver
method onandroidApp
.tsandroidApp.registerBroadcastReceiver()
For a complete example that shows how to register a broadcast receiver with a custom intent filter, visit the following link:
For system intent filters, see Standard Broadcast Actions.
Unregister a broadcast receiver
To unregister a broadcast receiver, call the unregisterBroadcastReceiver on the wrapper around an android.app.Application passing it the intent filter for which to unregister the broacast receiver. The example below unregisters a broadcast receiver for the android.content.Intent.ACTION_BATTERY_CHANGED
intent filter.
import { Application, isAndroid } from '@nativescript/core'
if (isAndroid) {
const androidApp: AndroidApplication = Application.android
androidApp.unregisterBroadcastReceiver(
android.content.Intent.ACTION_BATTERY_CHANGED
)
}
Add a notification observer
To add an iOS notification observer, follow the steps below:
Import the
Application
class from@nativescript/core
.tsimport { Application, isIOS } from '@nativescript/core'
Get the wrapper object for UIApplication instance.
tsconst iOSApp: iOSApplication = Application.ios
Call the
addNotificationObserver
method. Call theaddNotificationObserver
passing it the name of the notification(NSNotificationName) you would like to observe as the first parameter and as a second parameter, a callback function to be called when that notification occurs.tsconst observer: any = iOSApp.addNotificationObserver( UIDeviceOrientationDidChangeNotification, (notification: NSNotification) => { //Handle the notification } )
Find the complete example here
Remove a notification observer
To remove a notification observer, use the removeNotificationObserver
method on a Application.ios
reference the observer id, returned by the addNotificationObserver
as the first argument and the name of the notification to stop observing.
iOSApp.removeNotificationObserver(
observer,
UIDeviceBatteryStateDidChangeNotification
)
Cross platform application events
This class allows you to listen to the following lifecycle events on both platforms.
Application.on('orientationChanged', (args: ApplicationEventData) => {
// handle the event
})
More events
livesync
cssChanged
initRootView
launch
displayed
suspend
resume
exit
lowMemory
uncaughtError
discardedError
orientationChanged
systemAppearanceChanged
fontScaleChanged
getResources()
resources: any = Application.getResources()
Gets application-level static resources.
setResources()
Application.setResources(resources)
Sets application-level static resources.
setCssFileName()
Application.setCssFileName(filePath)
Sets css file name for the application.
getCssFileName()
cssFileName: string = Application.getCssFileName()
Gets css file name for the application.
loadAppCss()
loadedCss: any = Applicatioin.loadAppCss()
Loads immediately the app.css. By default the app.css file is loaded shortly after "loaded". For the Android snapshot the CSS can be parsed during the snapshot generation, as the CSS does not depend on runtime APIs, and loadAppCss will be called explicitly.
addCss()
Application.addCss(cssText, attributeScoped)
Adds new values to the application styles.
cssText
- A valid CSS styles to be add to the current application styles.- Optional:
attributeScoped
- sets whether the styles are attribute scoped. Adding attribute scoped styles does not perform a full application styling refresh.
Android Reference
android
androidApp: AndroidApplication = Application.android
The property gives you the AndroidApplication
object, a Nativescript wrapper, around the native android application instance.
nativeApp
nativeApp: android.app.Application = androidApp.nativeApp
// or
nativeApp: UIApplication = iOSApp.nativeApp
This is a native application reference.
For Android, 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.
For iOS, it returns the reference to a UIApplication instance for the application.
foregroundActivity
foregroundActivity = androidApp.foregroundActivity
Gets the currently visible(topmost) android Activity.
startActivity
startActivity = androidApp.startActivity
Gets the main (start) Activity for the application.
paused
isSuspended: boolean = androidApp.paused
Returns true
if the main application activity is not running (suspended), otherwise false is returned.
backgrounded
isInBackground: boolean = androidApp.backgrounded
Returns true
if the main application activity is in background
registerBroadcastReceiver
receiver = androidApp.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.
onReceiveCallback
: a callback function that will be called each time a broadcast is received.
getRegisteredBroadcastReceiver
androidApp.getRegisteredBroadcastReceiver(intentFilter)
Gets a registered BroadcastReceiver for the specified intent filter.
unregisterBroadcastReceiver
androidApp.unregisterBroadcastReceiver(intentFilter)
Unregisters a previously registered BroadcastReceiver for the specified intent filter.
Android Activity lifecycles events
To handle the application lifecycle events for Android, use on
method of the
androidApp.on('activityResumed', (args) => {
//handle the event here
})
More Android Activity lifecycles events
activityCreated
activityDestroyed
activityStarted
activityPaused
activityStopped
saveActivityState
activityResult
activityBackPressed
activityNewIntent
activityRequestPermissions
iOS Reference
ios
iOSApp = Application.ios
The property gives you the iOSApplication
object, Nativescript wrapper, the around the native iOS application instance.
rootController
rootController: UIViewController = iOSApp.rootController
The root view controller for the iOS application.
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.
delegate(iOS lifecycles events)
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
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.
For a complete list of the iOS lifecycle events, visit UIApplicationDelegate.
orientation
orientation = androidApp.orientation
// or
orientation = iOSApp.orientation
Gets or sets the orientation of the application.
Possible values: portrait
| landscape
| unknown
systemAppearance
systemAppearance = androidApp.systemAppearance
// or
systemAppearance = iOSApp.systemAppearance
Returns whether the system appearance is dark
, light
or null
(for iOS <= 11).
References
API References
Name | Type |
---|---|
@nativescript/core/application | Module |
Native Component
Android | iOS |
---|---|
android.app.Application | UIApplication |
- Previous
- @nativescript/core
- Next
- ApplicationSettings