后台任务管理
本模块提供后台任务管理能力。
当应用或业务模块处于后台(无可见界面)时,如果有需要继续执行或者后续执行的业务,可基于业务类型,申请短时任务延迟挂起(Suspend)或者长时任务避免进入挂起状态。
应用有不可中断且短时间能完成的任务时(如,用户在文件管理器上点击垃圾文件清理,若清理未完成时退到后台,文件管理器需要申请短时任务完成清理),可以使用短时任务机制。
应用中存在用户能够直观感受到的且需要一直在后台运行的业务时(如,后台播放音乐),可以使用长时任务机制。
对于系统特权应用,提供独立的能效资源申请接口。系统特权应用如果需要使用特定的系统资源,例如在被挂起期间仍然能够收到系统公共事件,可以使用能效资源申请接口。
- 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
backgroundTaskManager.requestSuspendDelay
requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo
后台应用申请延迟挂起。
延迟挂起时间一般情况下默认值为3分钟,低电量(依据系统低电量广播)时默认值为1分钟。
系统能力: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
参数:
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
reason | string | 是 | 延迟挂起申请的原因。 |
callback | Callback<void> | 是 | 延迟即将超时的回调函数,一般在超时前6秒通过此回调通知应用。 |
返回值:
类型 | 说明 |
---|---|
返回延迟挂起信息。 |
错误码:
以下错误码的详细介绍请参见@ohos.resourceschedule.backgroundTaskManager (后台任务管理)错误码。
错误码ID | 错误信息 |
---|---|
9800001 | Memory operation failed. |
9800002 | Parcel operation failed. |
9800003 | Inner transact failed. |
9800004 | System service operation failed. |
9900001 | Caller information verification failed. |
9900002 | Background task verification failed. |
示例:
- import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
- let myReason = 'test requestSuspendDelay';
- try {
- let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
- console.info("Request suspension delay will time out.");
- })
- var id = delayInfo.requestId;
- var time = delayInfo.actualDelayTime;
- console.info("The requestId is: " + id);
- console.info("The actualDelayTime is: " + time);
- } catch (error) {
- console.error(`requestSuspendDelay failed. code is ${error.code} message is ${error.message}`);
- }
backgroundTaskManager.getRemainingDelayTime
getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void
获取应用程序进入挂起状态前的剩余时间,使用callback形式返回。
系统能力: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
参数:
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
requestId | number | 是 | 延迟挂起的请求ID。 |
callback | AsyncCallback<number> | 是 | 指定的callback回调方法。用于返回应用程序进入挂起状态之前的剩余时间,以毫秒为单位。 |
错误码:
以下错误码的详细介绍请参见@ohos.resourceschedule.backgroundTaskManager (后台任务管理)错误码。
错误码ID | 错误信息 |
---|---|
9800001 | Memory operation failed. |
9800002 | Parcel operation failed. |
9800003 | Inner transact failed. |
9800004 | System service operation failed. |
9900001 | Caller information verification failed. |
9900002 | Background task verification failed. |
示例:
- import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
- let id = 1;
- try {
- backgroundTaskManager.getRemainingDelayTime(id, (error, res) => {
- if(error) {
- console.error(`callback => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`);
- } else {
- console.log('callback => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
- }
- })
- } catch (error) {
- console.error(`callback => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`);
- }
backgroundTaskManager.getRemainingDelayTime
getRemainingDelayTime(requestId: number): Promise<number>
获取应用程序进入挂起状态前的剩余时间,使用Promise形式返回。
系统能力: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
参数:
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
requestId | number | 是 | 延迟挂起的请求ID。 |
返回值:
类型 | 说明 |
---|---|
Promise<number> | 指定的Promise回调方法。返回应用程序进入挂起状态之前的剩余时间,以毫秒为单位。 |
错误码:
以下错误码的详细介绍请参见@ohos.resourceschedule.backgroundTaskManager (后台任务管理)错误码。
错误码ID | 错误信息 |
---|---|
9800001 | Memory operation failed. |
9800002 | Parcel operation failed. |
9800003 | Inner transact failed. |
9800004 | System service operation failed. |
9900001 | Caller information verification failed. |
9900002 | Background task verification failed. |
示例:
- import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
- let id = 1;
- try {
- backgroundTaskManager.getRemainingDelayTime(id).then( res => {
- console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
- }).catch( error => {
- console.error(`promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`);
- })
- } catch (error) {
- console.error(`promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`);
- }
backgroundTaskManager.cancelSuspendDelay
cancelSuspendDelay(requestId: number): void
取消延迟挂起。
系统能力: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
参数:
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
requestId | number | 是 | 延迟挂起的请求ID。 |
错误码:
以下错误码的详细介绍请参见@ohos.resourceschedule.backgroundTaskManager (后台任务管理)错误码。
错误码ID | 错误信息 |
---|---|
9800001 | Memory operation failed. |
9800002 | Parcel operation failed. |
9800003 | Inner transact failed. |
9800004 | System service operation failed. |
9900001 | Caller information verification failed. |
9900002 | Background task verification failed. |
示例:
- import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
- let id = 1;
- try {
- backgroundTaskManager.cancelSuspendDelay(id);
- } catch (error) {
- console.error(`cancelSuspendDelay failed. code is ${error.code} message is ${error.message}`);
- }
backgroundTaskManager.startBackgroundRunning
startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void
向系统申请长时任务,使用callback形式返回结果。
需要权限: ohos.permission.KEEP_BACKGROUND_RUNNING
系统能力: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
参数:
错误码:
以下错误码的详细介绍请参见@ohos.resourceschedule.backgroundTaskManager (后台任务管理)错误码。
错误码ID | 错误信息 |
---|---|
9800001 | Memory operation failed. |
9800002 | Parcel operation failed. |
9800003 | Inner transact failed. |
9800004 | System service operation failed. |
9800005 | Background task verification failed. |
9800006 | Notification verification failed. |
9800007 | Task storage failed. |
示例:
- import UIAbility from '@ohos.app.ability.UIAbility';
- import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
- import wantAgent from '@ohos.app.ability.wantAgent';
- function callback(error, data) {
- if (error) {
- console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
- } else {
- console.info("Operation startBackgroundRunning succeeded");
- }
- }
- export default class EntryAbility extends UIAbility {
- onCreate(want, launchParam) {
- let wantAgentInfo = {
- wants: [
- {
- bundleName: "com.example.myapplication",
- abilityName: "EntryAbility"
- }
- ],
- operationType: wantAgent.OperationType.START_ABILITY,
- requestCode: 0,
- wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
- };
- try {
- wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
- try {
- backgroundTaskManager.startBackgroundRunning(this.context,
- backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback)
- } catch (error) {
- console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
- }
- });
- } catch (error) {
- console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`);
- }
- }
- };
backgroundTaskManager.startBackgroundRunning
startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void>
向系统申请长时任务,使用promise形式返回结果。
需要权限: ohos.permission.KEEP_BACKGROUND_RUNNING
系统能力: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
参数:
返回值:
类型 | 说明 |
---|---|
Promise<void> | 使用Promise形式返回结果。 |
错误码:
以下错误码的详细介绍请参见@ohos.resourceschedule.backgroundTaskManager (后台任务管理)错误码。
错误码ID | 错误信息 |
---|---|
9800001 | Memory operation failed. |
9800002 | Parcel operation failed. |
9800003 | Inner transact failed. |
9800004 | System service operation failed. |
9800005 | Background task verification failed. |
9800006 | Notification verification failed. |
9800007 | Task storage failed. |
示例:
- import UIAbility from '@ohos.app.ability.UIAbility';
- import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
- import wantAgent from '@ohos.app.ability.wantAgent';
- export default class EntryAbility extends UIAbility {
- onCreate(want, launchParam) {
- let wantAgentInfo = {
- wants: [
- {
- bundleName: "com.example.myapplication",
- abilityName: "EntryAbility"
- }
- ],
- operationType: wantAgent.OperationType.START_ABILITY,
- requestCode: 0,
- wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
- };
- try {
- wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
- try {
- backgroundTaskManager.startBackgroundRunning(this.context,
- backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => {
- console.info("Operation startBackgroundRunning succeeded");
- }).catch((error) => {
- console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
- });
- } catch (error) {
- console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
- }
- });
- } catch (error) {
- console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`);
- }
- }
- };
backgroundTaskManager.stopBackgroundRunning
stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void
向系统申请取消长时任务,使用callback形式返回结果。
系统能力: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
参数:
错误码:
以下错误码的详细介绍请参见@ohos.resourceschedule.backgroundTaskManager (后台任务管理)错误码。
错误码ID | 错误信息 |
---|---|
9800001 | Memory operation failed. |
9800002 | Parcel operation failed. |
9800003 | Inner transact failed. |
9800004 | System service operation failed. |
9800005 | Background task verification failed. |
9800006 | Notification verification failed. |
9800007 | Task storage failed. |
示例:
- import UIAbility from '@ohos.app.ability.UIAbility';
- import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
- function callback(error, data) {
- if (error) {
- console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
- } else {
- console.info("Operation stopBackgroundRunning succeeded");
- }
- }
- export default class EntryAbility extends UIAbility {
- onCreate(want, launchParam) {
- try {
- backgroundTaskManager.stopBackgroundRunning(this.context, callback);
- } catch (error) {
- console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
- }
- }
- };
backgroundTaskManager.stopBackgroundRunning
stopBackgroundRunning(context: Context): Promise<void>
向系统申请取消长时任务,使用promise形式返回结果。
系统能力: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
参数:
返回值:
类型 | 说明 |
---|---|
Promise<void> | 使用Promise形式返回结果。 |
错误码:
以下错误码的详细介绍请参见@ohos.resourceschedule.backgroundTaskManager (后台任务管理)错误码。
错误码ID | 错误信息 |
---|---|
9800001 | Memory operation failed. |
9800002 | Parcel operation failed. |
9800003 | Inner transact failed. |
9800004 | System service operation failed. |
9800005 | Background task verification failed. |
9800006 | Notification verification failed. |
9800007 | Task storage failed. |
示例:
- import UIAbility from '@ohos.app.ability.UIAbility';
- import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
- export default class EntryAbility extends UIAbility {
- onCreate(want, launchParam) {
- try {
- backgroundTaskManager.stopBackgroundRunning(this.context).then(() => {
- console.info("Operation stopBackgroundRunning succeeded");
- }).catch((error) => {
- console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
- });
- } catch (error) {
- console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
- }
- }
- };
更多建议: