DEV Community

Cover image for Understand Various Contexts in HarmonyOS Next in One Article
kouwei qing
kouwei qing

Posted on

Understand Various Contexts in HarmonyOS Next in One Article

Background

Both Android and HarmonyOS Next involve the concept of Context. In many scenarios, such as obtaining file resources, reliance on this Context is necessary. There are various types of Context, and the ways to obtain and the functions of different Contexts are different. To carry out HarmonyOS development smoothly, it is quite essential to figure out various Contexts.

Context Concept

Context is the context of objects in an application. It provides some basic information of the application, such as resourceManager (resource management), applicationInfo (information of the current application), dir (application file path), area (file partition), etc., as well as some basic methods of the application, like createBundleContext(), getApplicationContext(), etc.

UIAbility components and various components derived from ExtensionAbility have their respective different Context classes, including the base class Context, ApplicationContext, AbilityStageContext, UIAbilityContext, ExtensionContext, ServiceExtensionContext, etc.

The inheritance relationships of various Contexts are as follows:

Image description

The holding relationships of various Contexts are as follows:

Image description

There are 9 types of Context mentioned here:

  1. BaseContext
  2. Context
  3. ApplicationContext
  4. AbilityStageContext
  5. UIAbilityContext
  6. ExtensionContext
  7. Other ExtensionContext
  8. FormExtensionContext
  9. ServiceExtensionContext

Abilities Provided by Various Contexts

Let's take a look at the abilities provided by various Contexts.

BaseContext

The BaseContext abstract class is used to indicate whether the inherited subclass Context is of the Stage model or the FA model. It is the parent class of all Context types. It mainly provides the stageMode property:

Name Type Readable Writable Description
stageMode boolean Yes Yes Indicates whether it is the Stage model.

True: Stage model

False: FA model.

Context

The Context module inherits from BaseContext and provides the ability of the context of an ability or an application, including accessing the resources of a specific application program. It provides the following properties:

Name Type Read-Only Optional Description
resourceManager resmgr.ResourceManager No No Resource management object.
applicationInfo ApplicationInfo No No Information of the current application program.
cacheDir string No No Cache directory.
tempDir string No No Temporary directory.
resourceDir string No No Resource directory.
filesDir string No No File directory.
databaseDir string No No Database directory.
preferencesDir string No No Preferences directory.
bundleCodeDir string No No Installation package directory. Do not concatenate paths to access resource files. Please use the resource management interface to access resources.
distributedFilesDir string No No Distributed file directory.
cloudFileDir12+ string No No Cloud file directory.
eventHub [EventHub No No Event center, providing subscription, unsubscription, and triggering event objects.
area contextConstant.AreaMode No No File partition information.

It can be seen that Context already has properties for obtaining resources and resource paths.

It provides the following methods:

  • getApplicationContext(): ApplicationContext: Obtain the application context of the current application.
  • getGroupDir(dataGroupID: string): Promise<string>: Obtain the corresponding shared directory by using the Group ID in the application, using Promise for asynchronous callback.
  • getGroupDir(dataGroupID: string, callback: AsyncCallback<string>): void: Obtain the corresponding shared directory by using the Group ID in the application, using callback for asynchronous callback.

ApplicationContext

The ApplicationContext module inherits from Context and provides the ability of the context at the developer application level, including providing interfaces for registering and unregistering the listening of the component life cycle within the application. It provides the following methods:

  • on(type: 'abilityLifecycle', callback: AbilityLifecycleCallback): number: Register to monitor the life cycle within the application. Use callback for asynchronous callback. Only supports being called in the main thread.
  • off(type: 'abilityLifecycle', callbackId: number, callback: AsyncCallback<void>): void: Cancel the monitoring of the life cycle within the application. Use callback for asynchronous callback. Only supports being called in the main thread.
  • on(type: 'environment', callback: EnvironmentCallback): number: Register to monitor the changes in the system environment. Use callback for asynchronous callback. Only supports being called in the main thread.
  • off(type: 'environment', callbackId: number, callback: AsyncCallback<void>): void: Cancel the monitoring of the changes in the system environment. Use callback for asynchronous callback. Only supports being called in the main thread.
  • on(type: 'applicationStateChange', callback: ApplicationStateChangeCallback): void: Register to monitor the changes of the current application between the foreground and the background. Use callback for asynchronous callback. Only supports being called in the main thread.
  • off(type: 'applicationStateChange', callback?: ApplicationStateChangeCallback): void: Cancel all the monitoring of the changes between the foreground and the background registered by the current application. Use callback for asynchronous callback. Only supports being called in the main thread.
  • getRunningProcessInformation(): Promise<Array<ProcessInformation>>: Obtain information about running processes. Use Promise for asynchronous callback.
  • getRunningProcessInformation(callback: AsyncCallback<Array<ProcessInformation>>): void: Obtain information about running processes. Use callback for asynchronous callback.
  • killAllProcesses(): Promise<void>: Terminate all processes of the application. When the processes exit, they will not go through the application life cycle normally. Use Promise for asynchronous callback. Only supports being called in the main thread.
  • setColorMode(colorMode: ConfigurationConstant.ColorMode): void: Set the color mode of the application. Only supports being called in the main thread.
  • setLanguage(language: string): void: Set the language of the application. Only supports being called in the main thread.
  • clearUpApplicationData(): Promise<void>: Clear the data of the application itself and revoke the permissions applied by the application to the user. Use Promise for asynchronous callback. Only supports being called in the main thread.
  • clearUpApplicationData(callback: AsyncCallback<void>): void: Clear the data of the application itself and revoke the permissions applied by the application to the user. Use callback for asynchronous callback. Only supports being called in the main thread.
  • restartApp(want: Want): void: Restart the application and pull up the specified UIAbility of itself. When restarting, the onDestroy callback will not be received. Only supports being called in the main thread, and the application to be restarted needs to be in the focused state.
  • getCurrentAppCloneIndex(): number: Obtain the clone index of the current application.
  • setFont(font: string): void: Set the font type of the application. Only supports being called in the main thread.
  • setSupportedProcessCache(isSupported : boolean): void: Set whether the application itself supports quick startup with caching. Only supports being called in the main thread.

AbilityStageContext

AbilityStageContext is the context environment of AbilityStage and inherits from Context.

AbilityStageContext provides the ability to access resources specific to abilityStage, including obtaining the ModuleInfo object and the environment change object corresponding to AbilityStage. It provides the following properties:

Name Type Readable Writable Description
currentHapModuleInfo HapModuleInfo Yes No The ModuleInfo object corresponding to AbilityStage.
config Configuration Yes No The environment change object.

UIAbilityContext

UIAbilityContext is the context corresponding to the UIAbility that needs to save the state. It inherits from Context and provides the relevant configuration information of UIAbility as well as methods for operating UIAbility and ServiceExtensionAbility, such as starting UIAbility, stopping the UIAbility to which the current UIAbilityContext belongs, starting, stopping, connecting, and disconnecting ServiceExtensionAbility, etc. It provides the following properties:

Name Type Readable Writable Description
abilityInfo AbilityInfo Yes No Information related to UIAbility.

Meta Service API: From API version 11, this interface supports use in meta services.
currentHapModuleInfo HapModuleInfo Yes No Information of the current HAP.

Meta Service API: From API version 11, this interface supports use in meta services.
config Configuration Yes No Configuration information related to UIAbility, such as language, color mode, etc.

Meta Service API: From API version 11, this interface supports use in meta services.
windowStage12+ window.WindowStage Yes No The current WindowStage object. Only supports being called in the main thread.

Meta Service API: From API version 12, this interface supports use in meta services.

It provides the following abilities:

  • Start Ability: startAbility, startAbilityForResult
  • Stop Ability itself: terminateSelf, terminateSelfWithResult
  • Connect the current Ability to a ServiceExtensionAbility: connectServiceExtensionAbility
  • Disconnect from a ServiceExtensionAbility. After disconnection, the remote object returned when the connection is successful needs to be set to null: disconnectServiceExtensionAbility
  • In a cross-device scenario, start the specified Ability to the foreground or background and obtain its Caller communication interface at the same time. The caller can use Caller to communicate with the started Ability: startAbilityByCall
  • Set the name displayed by UIAbility in the task: setMissionLabel
  • Set the流转状态 (I assume it's something like transfer state in Chinese, but you may correct it if it's a specific term) of the UIAbility task: setMissionContinueState
  • Restore the WindowStage data in UIAbility: restoreWindowStage
  • Query whether UIAbility is in the terminating state: isTerminating
  • Start a ServiceExtensionAbility that supports modal pop-up boxes. After the ServiceExtensionAbility is started, the application pops up a modal pop-up box, and the result can be returned to the caller by calling the setRequestResult interface: requestDialogService
  • When the page loading is completed (loadContent is successful), provide a checkpoint function for developers (in the form of callback): reportDrawnCompleted
  • Start UIExtensionAbility implicitly through type. Use callback for asynchronous callback: startAbilityByType
  • Display the current Ability: showAbility
  • Hide the current Ability: hideAbility
  • Move the Ability in the foreground to the background: moveAbilityToBackground
  • Start EmbeddableUIAbility in a jump-out manner and return the result: openAtomicService
  • Start UIAbility through AppLinking: openLink
  • When the target Ability is pulled up through startAbilityForResult or openLink and the result needs to be returned by the target side, the target side can return the result and pull up the caller through this interface. Different from terminateSelfWithResult, this interface will not destroy the current Ability when returning: backToCallerAbilityWithResult

ExtensionContext

ExtensionContext is the context environment of Extension and inherits from Context.

The ExtensionContext module provides the ability to access the resources specific to Extension. For extended Extensions, the ExtensionContext can be directly used as the context environment, or a type inherited from ExtensionContext can be defined as the context environment.

It provides the following properties:

Name Type Readable Writable Description
currentHapModuleInfo HapModuleInfo Yes No Information of the belonging Hap package.

(See api\bundle\hapModuleInfo.d.ts under the SDK directory)
config Configuration Yes No Configuration information of the belonging Module.

(See api\@ohos.app.ability.Configuration.d.ts under the SDK directory)
extensionAbilityInfo ExtensionAbilityInfo Yes No Information of the belonging Extension.

(See api\bundle\extensionAbilityInfo.d.ts under the SDK directory)

Common Usage Scenarios of Context

From the above analysis of various Contexts, it can be understood that Context can mainly be used in the following scenarios:

  • Obtaining the application file path
  • Obtaining and modifying the encrypted partition
  • Obtaining the Context of other Modules in the current application
  • Subscribing to the changes in the life cycle of UIAbility within the process

Taking the most typical example of obtaining string resources through resourceManager:

static getStringSync(context: common.Context | undefined, resource: Resource): string {  
  let rscManager = (context?? getContext() as common.UIAbilityContext).resourceManager;  
    return rscManager.getStringSync(resource.id)  
}
Enter fullscreen mode Exit fullscreen mode

Here, Context is needed. What is the Context obtained by getContext in a general class?
In the page, we can check the types of Context obtained through getContext and getUIContext, which are AbilityContext and UIContext respectively:

Image description

In the viewmodel, the Context obtained by getContext is also the same AbilityContext:

Image description

Summary

This article has detailed the direct relationships, provided properties, and methods of various Contexts in HarmonyOS Next.

References

Top comments (0)