Read the original article:HarmonyOS Next: Understanding Context (Stage Model)
Introduction
Context helps parts of the app talk to each other and access information about the environment. Context makes it possible to manage app resources, check settings, and watch system events. In this article, we will explain the different types of Context in HarmonyOS Next, how to get them, and where they are commonly used.
What is Context?
The Context object typically provides access to foundational elements such as:
· resourceManager: Manages application resources like strings, images, and layouts.
· applicationInfo: Offers metadata about the application, including its name, version, and configuration details.
· dir: Points to file paths where the app stores its data.
· area: Defines the encryption level for secure data access.
These elements create a standardized way for different parts of an app to retrieve shared information without hardcoding dependencies.
Comparison of Context Types
1-) ApplicationContext (App-Level Context)
This context is shared by all parts of the app. It includes settings, resources, and services.
· Gives access to app-wide resources
· Can be used by all parts
· Stays the same while the app is running
2-) AbilityStageContext (Module-Level Context)
This context is connected to the AbilityStage class. It gives module info and configuration.
· Offers module-level details
· Special for AbilityStage parts
3-) UIAbilityContext (UIAbility Context)
This is the context of the UIAbility class. It includes UI settings and other app info.
· Manages UIAbility life cycle events
· Has methods for user interface actions
4-) ExtensionAbilityContext (Component-Level Context)
This context is used for screen or widget-like components. For example, FormExtensionContext for form screens.
· Gives special info for custom components
· Designed for advanced widget tasks
Where Context Is Used
- Obtaining ApplicationContext Context helps you find basic app details like name, version, and settings.
- Getting App File Paths Context lets you find the file path to save app data.
- Obtaining and Modifying Encryption encrypting application files, you improve data safety and block unauthorized access. Various files within an app may need different levels of encryption depending on their importance.
- Watching App Foreground/Background Changes Context helps you track if the app is open or running in the background.
- Watching UIAbility Lifecycle Changes Context is used to listen to when UIAbility is created or destroyed.
Development Example
Accessing File Paths with Context
Context lets you find the file path to save app data.
Example Create File Code:
import { common } from '@kit.AbilityKit';
import { buffer } from '@kit.ArkTS';
import { fileIo, ReadOptions } from '@kit.CoreFileKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
const TAG: string = '[Page_Context]';
const DOMAIN_NUMBER: number = 0xFF00;
@Entry
@Component
struct Index {
@State message: string = 'Obtaining Application File Paths';
private context = this.getUIContext().getHostContext() as common.UIAbilityContext;
build() {
Row() {
Column() {
Text(this.message)
Button() {
Text('Create File')
.onClick(() => {
let applicationContext = this.context.getApplicationContext();
let filesDir = applicationContext.filesDir;
hilog.info(DOMAIN_NUMBER, TAG, `filePath: ${filesDir}`);
let file = fileIo.openSync(filesDir + '/test.txt', fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
let writeLen = fileIo.writeSync(file.fd, "Try to write str.");
hilog.info(DOMAIN_NUMBER, TAG, `The length of str is: ${writeLen}`);
let arrayBuffer = new ArrayBuffer(1024);
let readOptions: ReadOptions = {
offset: 0,
length: arrayBuffer.byteLength
};
let readLen = fileIo.readSync(file.fd, arrayBuffer, readOptions);
let buf = buffer.from(arrayBuffer, 0, readLen);
hilog.info(DOMAIN_NUMBER, TAG, `the content of file: ${buf.toString()}`);
fileIo.closeSync(file);
})
}
}
}
}
}
Obtaining and Modifying Encryption Levels
Encrypting application files, you improve data safety and block unauthorized access. Various files within an app may need different levels of encryption depending on their importance.
Here's a quick overview of the common levels:
EL1: Use this for private files (like alarms or wallpapers). Files here are encrypted at the device level, meaning they require the device to be unlocked (user password/biometrics) before access is granted.
EL2: Opt for sensitive files containing personal privacy. This level uses user-level encryption, requiring user authentication for access.
EL3: Necessary for files involved in operations that need to run even when the screen is locked (e.g., step counters, background downloads, music playback). These files are stored with permissions allowing read/write/execute while locked.
EL4: Suitable for files related to user security that should NOT be accessed or modified when the screen is locked. This level provides protection against unauthorized actions during idle states.
EL5: Reserved for highly sensitive files whose access might be needed briefly on a locked screen (though by default, such files can’t be modified on a lock screen). If required, you need to explicitly request Access or handle file creation/writing after the screen unlocks.
Code Example:
// EntryAbility.ets
import { AbilityConstant, contextConstant, UIAbility, Want } from '@kit.AbilityKit';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
// Before storing common information, switch the encryption level to EL1.
this.context.area = contextConstant.AreaMode.EL1; // Change the encryption level.
// Store common information.
// Before storing sensitive information, switch the encryption level to EL2.
this.context.area = contextConstant.AreaMode.EL2; // Change the encryption level.
// Before storing sensitive information, switch the encryption level to EL3.
this.context.area = contextConstant.AreaMode.EL3; // Change the encryption level.
// Store sensitive information.
// Before storing sensitive information, switch the encryption level to EL4.
this.context.area = contextConstant.AreaMode.EL4; // Change the encryption level.
// Store sensitive information.
// Before storing sensitive information, switch the encryption level to EL5.
this.context.area = contextConstant.AreaMode.EL5; // Change the encryption level.
// Store sensitive information.
}
}
// Index.ets
import { common, contextConstant } from '@kit.AbilityKit';
@Entry
@Component
struct Page_Context {
private context = this.getUIContext().getHostContext() as common.UIAbilityContext;
build() {
Column() {
//...
List({ initialIndex: 0 }) {
//...
ListItem() {
Row() {
//...
}
.onClick(() => {
// Before storing common information, switch the encryption level to EL1.
if (this.context.area === contextConstant.AreaMode.EL2) { // Obtain the encryption level.
this.context.area = contextConstant.AreaMode.EL1; // Change the encryption level.
this.getUIContext().getPromptAction().showToast({
message: 'SwitchToEL1'
});
}
// Store common information.
})
}
//...
ListItem() {
Row() {
//...
}
.onClick(() => {
// Before storing sensitive information, switch the encryption level to EL2.
if (this.context.area === contextConstant.AreaMode.EL1) { // Obtain the encryption level.
this.context.area = contextConstant.AreaMode.EL2; // Change the encryption level.
this.getUIContext().getPromptAction().showToast({
message: 'SwitchToEL2'
});
}
// Store sensitive information.
})
}
//...
}
//...
}
//...
}
}
Conclusion
Context is an important tool in HarmonyOS. It helps different app parts talk to each other and manage the environment. In this article, we saw how to get different types of Context and where they are used. We hope this helps you when making HarmonyOS Next apps.
Referances
https://developer.huawei.com/consumer/en/doc/harmonyos-guides/application-context-stage

Top comments (0)