This article aims to deeply explore the technical details of Huawei's HarmonyOS Next system (as of API 12 currently) and is summarized based on actual development practices. It is mainly used as a carrier for technical sharing and exchange. Inevitable errors and omissions may exist. Colleagues are welcome to put forward valuable opinions and questions for common progress. This article is original content. Any form of reprint must indicate the source and original author.
With the rapid development of the mobile Internet, users' functional requirements for applications are increasingly rich, and the need for applications to run in the background is becoming more and more common. However, the management of background tasks faces many challenges, such as device energy consumption and user experience. As a distributed operating system independently developed by Huawei, HarmonyOS Next provides a complete Background Tasks Kit background task development framework to help us developers efficiently manage and schedule background tasks and realize the continuous operation of application functions.
The role and application scenarios of Background Tasks Kit
The Background Tasks Kit is a background task development framework provided by HarmonyOS Next. Its main roles are as follows:
- Reduce device energy consumption: By standardizing the use of background tasks, avoid excessive consumption of device resources by applications in the background and extend the battery life of the device.
- Optimize user experience: Ensure the normal operation of background tasks and avoid applications being killed by the system in the background to ensure the continuity of user experience.
- Provide multiple background task types: Support multiple background task types such as short-term tasks, long-term tasks, deferred tasks, and agent-powered reminders to meet the development needs of different scenarios.
Types and characteristics of background tasks
The Background Tasks Kit provides four types of background tasks, and each type has its unique characteristics and application scenarios:
Task type | Characteristics | Application scenarios |
---|---|---|
Short-term task (Transient Task) | High real-time requirements and short duration | Saving status, sending messages, making network requests, etc. |
Long-term task (Continuous Task) | Long-term background operation | Music playback, navigation, device connection, location tracking, etc. |
Deferred task (Deferred Task) | Allows condition-triggered tasks | Actively obtaining emails irregularly when there is a network, synchronizing data regularly, etc. |
Agent-powered reminder | A reminder task executed by the system on behalf of the application in the background | Countdown, alarm clock, calendar, meeting reminder, etc. |
Short-term task
Short-term tasks are suitable for tasks with high real-time requirements and short duration in the background, such as saving status, sending messages, and making network requests. Developers can apply for short-term tasks through the requestSuspendDelay
interface and set up a callback function to handle the situation where the task times out.
Code example:
import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
function requestSuspendDelay() {
let myReason = 'test requestSuspendDelay'; // Reason for application
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
// Callback function. When the application's short-term task is about to time out, the application is called back through this function to perform some cleanup and annotation work and cancel the short-term task.
console.info('suspend delay task will timeout');
backgroundTaskManager.cancelSuspendDelay(delayInfo.requestId);
});
}
Long-term task
Long-term tasks are suitable for tasks that run in the background for a long time, such as music playback, navigation, device connection, and location tracking. Developers need to create a ContinuousTaskExtensionAbility
to carry long-term tasks and implement the onContinuousTaskStart
and onContinuousTaskStop
callback functions to handle the logic of task start and end respectively.
Code example:
import { ContinuousTaskExtensionAbility, backgroundTaskManager } from '@kit.BackgroundTasksKit';
export default class MyContinuousTaskExtensionAbility extends ContinuousTaskExtensionAbility {
onContinuousTaskStart(workInfo: backgroundTaskManager.WorkInfo) {
console.info(`onContinuousTaskStart, workInfo = ${JSON.stringify(workInfo)}`);
// Start executing long-term task logic
}
onContinuousTaskStop(workInfo: backgroundTaskManager.WorkInfo) {
console.info(`onContinuousTaskStop, workInfo is ${JSON.stringify(workInfo)}`);
// Stop executing long-term task logic
}
}
Deferred task
Deferred tasks allow tasks triggered by conditions (such as network or charging conditions), such as actively obtaining emails irregularly when there is a network and synchronizing data regularly. Developers can apply for deferred tasks through the startWork
interface and set information such as trigger conditions, cycle intervals, and cycle times.
Code example:
import { workScheduler } from '@kit.BackgroundTasksKit';
const workInfo: workScheduler.WorkInfo = {
workId: 1,
networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI,
bundleName: 'com.example.application',
abilityName: 'MyWorkSchedulerExtensionAbility',
repeatCycleTime: 2 * 60 * 60 * 1000, // Execute once every 2 hours
repeatCount: 10 // Repeat execution 10 times
};
try {
workScheduler.startWork(workInfo);
console.info(`startWork success`);
} catch (error) {
console.error(`startWork failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
}
Agent-powered reminder
Agent-powered reminders are reminder tasks executed by the system on behalf of the application in the background, such as countdown, alarm clock, calendar, and meeting reminder. Developers can publish reminder tasks through the publishReminder
interface and set information such as reminder type, trigger time, reminder content, and notification channel.
Code example:
import { reminderAgentManager } from '@kit.BackgroundTasksKit';
import { notificationManager } from '@kit.NotificationKit';
let targetReminderAgent: reminderAgentManager.ReminderRequestTimer = {
reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, // Reminder type is countdown type
triggerTimeInSeconds: 10,
actionButton: [{ title: 'close', type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE }],
wantAgent: { pkgName: 'com.example.myapplication', abilityName: 'EntryAbility' },
maxScreenWantAgent: { pkgName: 'com.example.myapplication', abilityName: 'EntryAbility' },
title: 'this is title',
content: 'this is content',
expiredContent: 'this reminder has expired',
notificationId: 100,
slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION
};
reminderAgentManager.publishReminder(targetReminderAgent).then((res: number) => {
console.info('Succeeded in publishing reminder. ');
let reminderId: number = res; // Published reminder ID
}).catch((err: BusinessError) => {
console.error(`Failed to publish reminder. Code: ${err.code}, message: ${err.message}`);
});
Conclusion
The Background Tasks Kit of HarmonyOS Next provides us developers with rich background task management functions, helping us efficiently manage and schedule background tasks and realize the continuous operation of application functions. We can choose the appropriate background task type according to actual needs and apply it in application development combined with specific development scenarios.
Top comments (0)