harmony 鸿蒙@ohos.resourceschedule.backgroundTaskManager (Background Task Management)

2022-12-05 浏览 (766)

@ohos.resourceschedule.backgroundTaskManager (Background Task Management)

The backgroundTaskManager module provides APIs to request background tasks. You can use the APIs to request transient tasks, continuous tasks, or efficiency resources to prevent the application process from being terminated or suspended when your application is switched to the background.

NOTE

The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';  

backgroundTaskManager.requestSuspendDelay

requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo

Requests a transient task.

NOTE

The maximum duration of a transient task is 3 minutes in normal cases. In the case of a low battery, the maximum duration is decreased to 1 minute.

System capability: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask

Parameters

NameTypeMandatoryDescription
reasonstringYesReason for requesting the transient task.
callbackCallback<void>YesCallback used to notify the application that the transient task is about to time out. Generally, the callback is invoked 6 seconds before the timeout.

Return value

TypeDescription
DelaySuspendInfoInformation about the transient task.

Error codes

For details about the error codes, see backgroundTaskManager Error Codes.

IDError Message
9800001Memory operation failed.
9800002Parcel operation failed.
9800003Inner transact failed.
9800004System service operation failed.
9900001Caller information verification failed.
9900002Background task verification failed.

Example

import { BusinessError } from '@ohos.base';

let myReason = 'test requestSuspendDelay';
try {
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
    console.info("Request suspension delay will time out.");
})
let id = delayInfo.requestId;
let time = delayInfo.actualDelayTime;
console.info("The requestId is: " + id);
console.info("The actualDelayTime is: " + time);
} catch (error) {
console.error(`requestSuspendDelay failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
}

backgroundTaskManager.getRemainingDelayTime

getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void

Obtains the remaining time of a transient task. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask

Parameters

NameTypeMandatoryDescription
requestIdnumberYesRequest ID of the transient task.
callbackAsyncCallback<number>YesCallback used to return the remaining time, in milliseconds.

Error codes

For details about the error codes, see backgroundTaskManager Error Codes.

IDError Message
9800001Memory operation failed.
9800002Parcel operation failed.
9800003Inner transact failed.
9800004System service operation failed.
9900001Caller information verification failed.
9900002Background task verification failed.

Example

import { BusinessError } from '@ohos.base';

let id = 1;
backgroundTaskManager.getRemainingDelayTime(id, (error: BusinessError, res: number) => {
    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));
    }
})

backgroundTaskManager.getRemainingDelayTime

getRemainingDelayTime(requestId: number): Promise<number>

Obtains the remaining time of a transient task. This API uses a promise to return the result.

System capability: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask

Parameters

NameTypeMandatoryDescription
requestIdnumberYesRequest ID of the transient task.

Return value

TypeDescription
Promise<number>Promise used to return the remaining time, in milliseconds.

Error codes

For details about the error codes, see backgroundTaskManager Error Codes.

IDError Message
9800001Memory operation failed.
9800002Parcel operation failed.
9800003Inner transact failed.
9800004System service operation failed.
9900001Caller information verification failed.
9900002Background task verification failed.

Example

import { BusinessError } from '@ohos.base';

let id = 1;
backgroundTaskManager.getRemainingDelayTime(id).then((res: number) => {
    console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
}).catch((error: BusinessError) => {
    console.error(`promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`);
})

backgroundTaskManager.cancelSuspendDelay

cancelSuspendDelay(requestId: number): void

Cancels a transient task.

System capability: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask

Parameters

NameTypeMandatoryDescription
requestIdnumberYesRequest ID of the transient task.

Error codes

For details about the error codes, see backgroundTaskManager Error Codes.

IDError Message
9800001Memory operation failed.
9800002Parcel operation failed.
9800003Inner transact failed.
9800004System service operation failed.
9900001Caller information verification failed.
9900002Background task verification failed.

Example

import { BusinessError } from '@ohos.base';

let id = 1;
try {
  backgroundTaskManager.cancelSuspendDelay(id);
} catch (error) {
  console.error(`cancelSuspendDelay failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
}

backgroundTaskManager.startBackgroundRunning

startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void

Requests a continuous task. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.KEEP_BACKGROUND_RUNNING

System capability: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
bgModeBackgroundModeYesContinuous task mode.
wantAgentWantAgentYesNotification parameters, which are used to specify the target page that is redirected to when a continuous task notification is clicked.
callbackAsyncCallback<void>YesCallback used to return the result. If the continuous task is requested, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see backgroundTaskManager Error Codes.

IDError Message
9800001Memory operation failed.
9800002Parcel operation failed.
9800003Inner transact failed.
9800004System service operation failed.
9800005Background task verification failed.
9800006Notification verification failed.
9800007Task storage failed.

Example

import UIAbility from '@ohos.app.ability.UIAbility';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';  
import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent';
import Want from '@ohos.app.ability.Want';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import { BusinessError } from '@ohos.base';

function callback(error: BusinessError, data: void) {
    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: Want, launchParam: AbilityConstant.LaunchParam) {
        let wantAgentInfo: wantAgent.WantAgentInfo = {
            // List of operations to be executed after the notification is clicked.
            wants: [
                {
                    bundleName: "com.example.myapplication",
                    abilityName: "EntryAbility"
                }
            ],
            // Type of the operation to perform after the notification is clicked.
            operationType: wantAgent.OperationType.START_ABILITY,
            // Custom request code.
            requestCode: 0,
            // Execution attribute of the operation to perform after the notification is clicked.
            wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
        };

        try {
            // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
            wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => {
                try {
                    backgroundTaskManager.startBackgroundRunning(this.context,
                        backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback)
                } catch (error) {
                    console.error(`Operation startBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
                }
            });
        } catch (error) {
            console.error(`Operation getWantAgent failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
        }
    }
};

backgroundTaskManager.startBackgroundRunning

startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void>

Requests a continuous task. This API uses a promise to return the result.

Required permissions: ohos.permission.KEEP_BACKGROUND_RUNNING

System capability: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
bgModeBackgroundModeYesContinuous task mode.
wantAgentWantAgentYesNotification parameters, which are used to specify the target page that is redirected to when a continuous task notification is clicked.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see backgroundTaskManager Error Codes.

IDError Message
9800001Memory operation failed.
9800002Parcel operation failed.
9800003Inner transact failed.
9800004System service operation failed.
9800005Background task verification failed.
9800006Notification verification failed.
9800007Task storage failed.

Example

import UIAbility from '@ohos.app.ability.UIAbility';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; 
import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent';
import Want from '@ohos.app.ability.Want';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import { BusinessError } from '@ohos.base';

export default class EntryAbility extends UIAbility {
    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
        let wantAgentInfo: wantAgent.WantAgentInfo = {
            // List of operations to be executed after the notification is clicked.
            wants: [
                {
                    bundleName: "com.example.myapplication",
                    abilityName: "EntryAbility"
                }
            ],
            // Type of the operation to perform after the notification is clicked.
            operationType: wantAgent.OperationType.START_ABILITY,
            // Custom request code.
            requestCode: 0,
            // Execution attribute of the operation to perform after the notification is clicked.
            wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
        };

        try {
            // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
            wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => {
                try {
                    backgroundTaskManager.startBackgroundRunning(this.context,
                        backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => {
                        console.info("Operation startBackgroundRunning succeeded");
                    }).catch((error: BusinessError) => {
                        console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
                    });
                } catch (error) {
                    console.error(`Operation startBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
                }
            });
        } catch (error) {
            console.error(`Operation getWantAgent failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
        }
    }
};

backgroundTaskManager.stopBackgroundRunning

stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void

Cancels a continuous task. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.
callbackAsyncCallback<void>YesCallback used to return the result. If the continuous task is canceled, err is undefined. Otherwise, err is an error object.

Error codes

For details about the error codes, see backgroundTaskManager Error Codes.

IDError Message
9800001Memory operation failed.
9800002Parcel operation failed.
9800003Inner transact failed.
9800004System service operation failed.
9800005Background task verification failed.
9800006Notification verification failed.
9800007Task storage failed.

Example

import UIAbility from '@ohos.app.ability.UIAbility';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';  
import Want from '@ohos.app.ability.Want';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import { BusinessError } from '@ohos.base';

function callback(error: BusinessError, data: void) {
    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: Want, launchParam: AbilityConstant.LaunchParam) {
        try {
            backgroundTaskManager.stopBackgroundRunning(this.context, callback);
        } catch (error) {
            console.error(`Operation stopBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
        }
    }
};

backgroundTaskManager.stopBackgroundRunning

stopBackgroundRunning(context: Context): Promise<void>

Cancels a continuous task. This API uses a promise to return the result.

System capability: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context.
For details about the application context of the FA model, see Context.
For details about the application context of the stage model, see Context.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see backgroundTaskManager Error Codes.

IDError Message
9800001Memory operation failed.
9800002Parcel operation failed.
9800003Inner transact failed.
9800004System service operation failed.
9800005Background task verification failed.
9800006Notification verification failed.
9800007Task storage failed.

Example

import UIAbility from '@ohos.app.ability.UIAbility';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';  
import Want from '@ohos.app.ability.Want';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import { BusinessError } from '@ohos.base';

export default class EntryAbility extends UIAbility {
    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
        try {
            backgroundTaskManager.stopBackgroundRunning(this.context).then(() => {
                console.info("Operation stopBackgroundRunning succeeded");
            }).catch((error: BusinessError) => {
                console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
            });
        } catch (error) {
            console.error(`Operation stopBackgroundRunning failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
        }
    }
};

backgroundTaskManager.applyEfficiencyResources

applyEfficiencyResources(request: EfficiencyResourcesRequest): void

Requests efficiency resources.

System capability: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply

System API: This is a system API.

Parameters

NameTypeMandatoryDescription
requestEfficiencyResourcesRequestYesNecessary information carried in the request, including the resource type and timeout interval.

Error codes

For details about the error codes, see backgroundTaskManager Error Codes.

IDError Message
9800001Memory operation failed.
9800002Parcel operation failed.
9800003Inner transact failed.
9800004System service operation failed.
18700001Caller information verification failed.

Example

import { BusinessError } from '@ohos.base';

let request: backgroundTaskManager.EfficiencyResourcesRequest = {
    resourceTypes: backgroundTaskManager.ResourceType.CPU,
    isApply: true,
    timeOut: 0,
    reason: "apply",
    isPersist: true,
    isProcess: false,
};
try {
    backgroundTaskManager.applyEfficiencyResources(request);
    console.info("applyEfficiencyResources success. ");
} catch (error) {
    console.error(`applyEfficiencyResources failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
}

backgroundTaskManager.resetAllEfficiencyResources

resetAllEfficiencyResources(): void

Releases all efficiency resources.

System capability: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply

System API: This is a system API.

Error codes

For details about the error codes, see backgroundTaskManager Error Codes.

IDError Message
9800001Memory operation failed.
9800002Parcel operation failed.
9800003Inner transact failed.
9800004System service operation failed.
18700001Caller information verification failed.

Example

import { BusinessError } from '@ohos.base';

try {
    backgroundTaskManager.resetAllEfficiencyResources();
} catch (error) {
    console.error(`resetAllEfficiencyResources failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
}

DelaySuspendInfo

Defines the information about the transient task.

System capability: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask

NameTypeMandatoryDescription
requestIdnumberYesRequest ID of the transient task.
actualDelayTimenumberYesActual duration of the transient task that the application requests, in milliseconds.
The maximum duration of a transient task is 3 minutes in normal cases. In the case of a low battery, the maximum duration is decreased to 1 minute.

BackgroundMode

Enumerates the continuous task modes.

System capability: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask

NameValueDescription
DATA_TRANSFER1Data transfer.
AUDIO_PLAYBACK2Audio playback.
AUDIO_RECORDING3Audio recording.
LOCATION4Positioning and navigation.
BLUETOOTH_INTERACTION5Bluetooth-related task.
MULTI_DEVICE_CONNECTION6Multi-device connection.
WIFI_INTERACTION7WLAN-related.
System API: This is a system API.
VOIP8Audio and video calls.
System API: This is a system API.
TASK_KEEPING9Computing task (for specific devices only).

EfficiencyResourcesRequest

Describes the parameters for requesting efficiency resources.

System capability: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply

System API: This is a system API.

NameTypeMandatoryDescription
resourceTypesnumberYesType of the resource to request.
isApplybooleanYesWhether the request is used to apply for resources.
The value true means that the request is used to apply for resources, and false means that the request is used to release resources.
timeOutnumberYesDuration for which the resource will be used, in milliseconds.
isPersistbooleanNoWhether the resource is permanently held. The default value is false.
The value true means that the resource is permanently held, and false means the resource is held within a given period of time.
isProcessbooleanNoWhether the request is initiated by a process. The default value is false.
The value true means that the request is initiated by a process, and false means that the request is initiated by an application.
reasonstringYesReason for requesting the resource.

ResourceType

Enumerates the efficiency resource types.

System capability: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply

System API: This is a system API.

NameValueDescription
CPU1CPU resource. Such type of resource prevents an application from being suspended.
COMMON_EVENT2Common event resource. Such type of resource ensures that an application in the suspended state can receive common events.
TIMER4Timer resource. Such type of resource ensures that an application in the suspended state can be woken up by system timers.
WORK_SCHEDULER8Deferred task resource. Such type of resource provides a loose control policy for an application.
BLUETOOTH16Bluetooth resource. Such type of resource ensures that an application in the suspended state can be woken up by Bluetooth-related events.
GPS32GPS resource. Such type of resource ensures that an application in the suspended state can be woken up by GPS-related events.
AUDIO64Audio resource. Such type of resource prevents an application from being suspended when the application has an audio being played.
RUNNING_LOCK10+128RUNNING_LOCK resources are not proxied when the application is suspended.
SENSOR10+256Sensor callbacks are not intercepted.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙APIs

harmony 鸿蒙System Common Events (To Be Deprecated Soon)

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

harmony 鸿蒙Enterprise Device Management Overview (for System Applications Only)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager)

harmony 鸿蒙@ohos.distributedBundle (Distributed Bundle Management)

harmony 鸿蒙@ohos.bundle (Bundle)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/541230df0f444a87a7f85c366057eb9a