| title | Application |
|---|---|
| description | 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.
To register a broadcast receiver, you follow these 3 steps:
-
Import the
Applicationclass from@nativescript/core.import { Application, isAndroid } from '@nativescript/core'
-
Get the wrapper object for android.app.Application instance. Use the
androidproperty to get the wrapper around android.app.Application.const androidApp: AndroidApplication = Application.android
-
Call the registerBroadcastReceiver method. Call the
registerBroadcastReceivermethod onandroidApp.androidApp.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.
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,
)
}To add an iOS notification observer, follow the steps below:
-
Import the
Applicationclass from@nativescript/core.import { Application, isIOS } from '@nativescript/core'
-
Get the wrapper object for UIApplication instance.
const iOSApp: iOSApplication = Application.ios
-
Call the
addNotificationObservermethod. Call theaddNotificationObserverpassing 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.const observer: any = iOSApp.addNotificationObserver( UIDeviceOrientationDidChangeNotification, (notification: NSNotification) => { //Handle the notification }, )
Find the complete example here
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,
)This class allows you to listen to the following lifecycle events on both platforms.
Application.on('orientationChanged', (args: ApplicationEventData) => {
// handle the event
}):::details More events
livesynccssChangedinitRootViewlaunchdisplayedsuspendresumeexitlowMemoryuncaughtErrordiscardedErrororientationChangedsystemAppearanceChangedfontScaleChanged
:::
resources: any = Application.getResources()Gets application-level static resources.
Application.setResources(resources)Sets application-level static resources.
Application.setCssFileName(filePath)Sets css file name for the application.
cssFileName: string = Application.getCssFileName()Gets css file name for the application.
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.
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.
androidApp: AndroidApplication = Application.androidThe property gives you the AndroidApplication object, a Nativescript wrapper, around the native android application instance.
nativeApp: android.app.Application = androidApp.nativeApp
// or
nativeApp: UIApplication = iOSApp.nativeAppThis 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 = androidApp.foregroundActivityGets the currently visible(topmost) android Activity.
startActivity = androidApp.startActivityGets the main (start) Activity for the application.
isSuspended: boolean = androidApp.pausedReturns true if the main application activity is not running (suspended), otherwise false is returned.
isInBackground: boolean = androidApp.backgroundedReturns true if the main application activity is in background
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.
androidApp.getRegisteredBroadcastReceiver(intentFilter)Gets a registered BroadcastReceiver for the specified intent filter.
androidApp.unregisterBroadcastReceiver(intentFilter)Unregisters a previously registered BroadcastReceiver for the specified intent filter.
To handle the application lifecycle events for Android, use on method of the
androidApp.on('activityResumed', (args) => {
//handle the event here
}):::details More Android Activity lifecycles events
activityCreatedactivityDestroyedactivityStartedactivityPausedactivityStoppedsaveActivityStateactivityResultactivityBackPressedactivityNewIntentactivityRequestPermissions
:::
iOSApp = Application.iosThe property gives you the iOSApplication object, Nativescript wrapper, the around the native iOS application instance.
rootController: UIViewController = iOSApp.rootControllerThe root view controller for the iOS application.
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.
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 = MyDelegateThe 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 = androidApp.orientation
// or
orientation = iOSApp.orientationGets or sets the orientation of the application.
Possible values: portrait| landscape| unknown
systemAppearance = androidApp.systemAppearance
// or
systemAppearance = iOSApp.systemAppearanceReturns whether the system appearance is dark, light or null(for iOS <= 11).
:::details References
| Name | Type |
|---|---|
| @nativescript/core/application | Module |
| Android | iOS |
|---|---|
| android.app.Application | UIApplication |
:::