diff --git a/zh-cn/application-dev/background-task-management/background-task-dev-guide.md b/zh-cn/application-dev/background-task-management/background-task-dev-guide.md index c23b3f917dfa750846432232963eac050d88f963..2047780916748df3d73dabb48f13df84c9960e32 100644 --- a/zh-cn/application-dev/background-task-management/background-task-dev-guide.md +++ b/zh-cn/application-dev/background-task-management/background-task-dev-guide.md @@ -7,10 +7,12 @@ ## 接口说明 -``` +```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; ``` +## 短时任务 + **表1** backgroundTaskManager主要接口 | 接口名 | 描述 | @@ -29,51 +31,221 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager'; ## 开发步骤 + 1. 申请延迟挂起 - ``` - import backgroundTaskManager from '@ohos.backgroundTaskManager'; - let myReason = 'test requestSuspendDelay'; - let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { - console.info("Request suspension delay will time out."); - }); - var id = delayInfo.requestId;console.info("requestId is: " + id); - ``` + + ```js + import backgroundTaskManager from '@ohos.backgroundTaskManager'; + + let myReason = 'test requestSuspendDelay'; + let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { + console.info("Request suspension delay will time out."); + }); + + var id = delayInfo.requestId;console.info("requestId is: " + id); + ``` + 2. 获取进入挂起前的剩余时间 - ``` - backgroundTaskManager.getRemainingDelayTime(id).then( res => { - console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res)); - }).catch( err => { - console.log('promise => Operation failed. Cause: ' + err.data); - }); - ``` + + ```js + backgroundTaskManager.getRemainingDelayTime(id).then( res => { + console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res)); + }).catch( err => { + console.log('promise => Operation failed. Cause: ' + err.data); + }); + ``` + 3. 取消延迟挂起 - ``` - backgroundTaskManager.cancelSuspendDelay(id); - ``` + + ```js + backgroundTaskManager.cancelSuspendDelay(id); + ``` ## 开发实例 -``` +```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; let myReason = 'test requestSuspendDelay'; + // 申请延迟挂起 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); + // 获取应用程序进入挂起状态前的剩余时间 backgroundTaskManager.getRemainingDelayTime(id).then( res => { console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res)); }).catch( err => { console.log('promise => Operation failed. Cause: ' + err.data); }); + // 取消延迟挂起 backgroundTaskManager.cancelSuspendDelay(id); ``` + +## 长时任务 + +### 权限 + +ohos.permission.KEEP_BACKGROUND_RUNNING + +**表3** 长时任务主要接口 + +| 接口名 | 描述 | +| -------- | -------- | +| function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void;
function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void>; | 服务启动后,向系统申请长时任务,使服务一直保持后台运行 | +| function stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void;
function stopBackgroundRunning(context: Context): Promise<void>; | 停止后台长时任务的运行 | + + +其中,wantAgent的信息详见([WantAgent](#zh-cn/application-dev/reference/apis/js-apis-notification.md#WantAgent接口)) + + +**表4** 后台模式类型 +| 参数名 | id值 | 描述 | +| -------- | -------- | -------- | +| DATA_TRANSFER | 1 | 数据传输 | +| AUDIO_PLAYBACK | 2 | 音频播放 | +| AUDIO_RECORDING | 3 | 录音 | +| LOCATION | 4 | 定位导航 | +| BLUETOOTH_INTERACTION | 5 | 蓝牙相关 | +| MULTI_DEVICE_CONNECTION | 6 | 多设备互联 | +| WIFI_INTERACTION | 7 | WLAN相关(系统保留) | +| VOIP | 8 | 音视频通话(系统保留) | +| TASK_KEEPING | 9 | 计算任务(仅供PC使用) | + + +## 开发步骤 + +1. 在config.json文件中配置长时任务权限 + + ```json + "module": { + "package": "com.example.myapplication", + ..., + "reqPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" + } + ] + } + ``` + +2. 申请长时任务 + + ```js + import backgroundTaskManager from '@ohos.backgroundTaskManager'; + import featureAbility from '@ohos.ability.featureAbility'; + import wantAgent from '@ohos.wantAgent'; + + let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG] + }; + + // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation succeeded"); + }).catch((err) => { + console.error("Operation failed Cause: " + err); + }); + }); + ``` + +3. 停止长时任务 + + ```js + import backgroundTaskManager from '@ohos.backgroundTaskManager'; + import featureAbility from '@ohos.ability.featureAbility'; + + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { + console.info("Operation succeeded"); + }).catch((err) => { + console.error("Operation failed Cause: " + err); + }); + + ``` + +## 开发实例 + +当服务启动后,在serviceAbility的onStart回调方法中,调用长时任务的申请接口,声明此服务需要在后台长时运行。在onStop回调方法里,调用长时任务取消接口,声明取消长时任务。 +在service.js文件中: + +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import featureAbility from '@ohos.ability.featureAbility'; +import wantAgent from '@ohos.wantAgent'; + +function startBackgroundRunning() { + let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG] + }; + + // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation succeeded"); + }).catch((err) => { + console.error("Operation failed Cause: " + err); + }); + }); +} + +function stopBackgroundRunning() { + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { + console.info("Operation succeeded"); + }).catch((err) => { + console.error("Operation failed Cause: " + err); + }); +} + +export default { + onStart(want) { + console.info('ServiceAbility onStart'); + startBackgroundRunning(); + }, + onStop() { + console.info('ServiceAbility onStop'); + stopBackgroundRunning(); + }, + onConnect(want) { + console.info('ServiceAbility onConnect'); + return {}; + }, + onReconnect(want) { + console.info('ServiceAbility onReconnect'); + }, + onDisconnect() { + console.info('ServiceAbility onDisconnect'); + }, + onCommand(want, restart, startId) { + console.info('ServiceAbility onCommand'); + } +}; +``` \ No newline at end of file diff --git a/zh-cn/application-dev/background-task-management/background-task-overview.md b/zh-cn/application-dev/background-task-management/background-task-overview.md index f3cec92c4187b4a63b4ca35f787b37e37c0a71d5..5486df94b96cf6d9ff82f55012e1fce2b98f6427 100644 --- a/zh-cn/application-dev/background-task-management/background-task-overview.md +++ b/zh-cn/application-dev/background-task-management/background-task-overview.md @@ -33,3 +33,30 @@ - **取消时机**:任务完成后申请方应用主动取消延时申请,不要等到超时后被系统取消,否则会影响该应用的后台允许运行时长配额。 - **配额机制**:为了防止应用滥用保活,或者申请后不取消,每个应用每天都会有一定配额(会根据用户的使用习惯动态调整),配额消耗完就不再允许申请短时任务,所以应用完成短时任务后立刻取消延时申请,避免消耗配额。(注,这个配额指的是申请的时长,系统默认应用在后台运行的时间不计算在内)。 + +## 长时任务 +长时任务给用户能够直观感受到的且需要一直在后台运行的业务提供后台运行生命周期的保障。比如:业务需要在后台播放声音、需要在后台持续导航定位等。此类用户可以直观感知到的后台业务行为,可以通过使用长时任务对应的后台模式保障业务在后台的运行,支撑应用完成在后台的业务。 + +### 后台模式分类 +OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业务使用,具体的后台模式类型如下: + +**表1** 长时任务种类 + +| BackgroundMode | 说明 | 通知栏显示提示 | 备注 | +| -------- | -------- | -------- | -------- | +| dataTransfer | 通过网络/对端设备进行数据下载、备份、分享、传输等 | 正在运行数据传输任务 | | +| audioPlayback | 音频输出 | 正在运行音频播放任务 | | +| audioRecording | 音频输入 | 正在运行录音任务 | | +| location | 定位、导航 | 正在运行定位任务 | | +| bluetoothInteraction | 蓝牙传输 | 正在运行蓝牙相关任务 | | +| multiDeviceConnection | 分布式互联任务 | 正在运行分布式任务 | | +| wifiInteraction | WLAN传输 | 正在运行WLAN相关任务 | SystemApi,仅对System权限应用开放 | +| voip | 音视频电话、VOIP | 正在运行通话相关任务 | SystemApi,仅对System权限应用开放 | +| taskKeeping | 计算任务 | 正在运行计算任务 | PC特有,仅在PC申请生效 | + +### 长时任务使用约束 +- 如果用户选择可感知业务(如播音、导航、上传下载等),触发对应后台模式,在任务启动时,系统会强制弹出通知提醒用户。 +- 如果任务结束,应用应主动退出后台模式。若在后台运行期间,系统检测到应用并未使用对应后台模式的资源,则会被挂起(Suspend)。 +- 避免不合理地申请后台长时任务,长时任务类型要与应用的业务类型匹配。如表1所示。如果执行的任务和申请的类型不匹配,也会被系统检测到并被挂起(Suspend)。 +- 长时任务是为了真正在后台长时间执行某个任务,如果一个应用申请了长时任务,但在实际运行过程中,并未真正运行或执行此类任务时,也会被系统检测到并被挂起(Suspend)。 +- 每个Ability同一时刻只能申请运行一个长时任务。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md index 774b6c05d8efe64a01395bdf5e7018778e1e3750..fb4a41f4bbd0ba63a5088ad0a75c2c6677a1ee81 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -10,10 +10,15 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager'; ``` +## 系统能力 +SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask +SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask -## 权限 +## 权限列表 -无 +长时任务需要申请如下权限: + +ohos.permission.KEEP_BACKGROUND_RUNNING ## backgroundTaskManager.requestSuspendDelay @@ -122,3 +127,168 @@ cancelSuspendDelay(requestId: number): void | requestId | number | 是 | 延迟挂起的请求ID。 | | actualDelayTime | number | 是 | 应用的实际挂起延迟时间,以毫秒为单位。
一般情况下默认值为180000,低电量(依据系统低电量广播)时默认值为60000。 | +## backgroundTaskManager.startBackgroundRunning + +[8] startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void; + +向系统申请长时任务,使用callback形式返回结果。 + +- **参数**: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | context | Context | 是 | 应用运行的上下文 | + | bgMode | BackgroundMode | 是 | 向系统申请的后台模式 | + | wantAgent | WantAgent | 是 | 通知参数,用于指定长时任务通知点击跳转的界面。使用方式参考:[8] | + | callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果 | + +- **示例**: +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import featureAbility from '@ohos.ability.featureAbility'; +import wantAgent from '@ohos.wantAgent'; + +function callback(err, data) { + if (err) { + console.error("Operation failed Cause: " + err); + } else { + console.info("Operation succeeded"); + } +} + +let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG] +}; + +wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj, callback) +}); + +``` + +## backgroundTaskManager.startBackgroundRunning + +[8] startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> + +向系统申请长时任务,使用promise形式返回结果。 + +- **参数**: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | context | Context | 是 | 应用运行的上下文 | + | bgMode | BackgroundMode | 是 | 向系统申请的后台模式 | + | wantAgent | WantAgent | 是 | 通知参数,用于指定长时任务通知点击跳转的界面 | + +- **返回值** + | 类型 | 说明 | + | -------------- | ------------------------- | + | Promise\ | 使用Promise形式返回结果。 | + +- **示例**: +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import featureAbility from '@ohos.ability.featureAbility'; +import wantAgent from '@ohos.wantAgent'; + +let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG] +}; + +wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation succeeded"); + }).catch((err) => { + console.error("Operation failed Cause: " + err); + }); +}); + +``` + +## backgroundTaskManager.stopBackgroundRunning + +[8] stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void; + +向系统申请取消长时任务,使用callback形式返回结果。 + +- **参数**: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | context | Context | 是 | 应用运行的上下文 | + | callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果 | + +- **示例**: +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import featureAbility from '@ohos.ability.featureAbility'; + +function callback(err, data) { + if (err) { + console.error("Operation failed Cause: " + err); + } else { + console.info("Operation succeeded"); + } +} + +backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), callback); + +``` + +## backgroundTaskManager.stopBackgroundRunning + +[8] stopBackgroundRunning(context: Context): Promise<void>; + +向系统申请取消长时任务,使用promise形式返回结果。 + +- **参数**: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | context | Context | 是 | 应用运行的上下文 | + +- **返回值** + | 类型 | 说明 | + | -------------- | ------------------------- | + | Promise\ | 使用Promise形式返回结果。 | + +- **示例**: +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import featureAbility from '@ohos.ability.featureAbility'; + +backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { + console.info("Operation succeeded"); +}).catch((err) => { + console.error("Operation failed Cause: " + err); +}); + +``` + +## [8] BackgroundMode + +| 参数名 | 参数 | 描述 | +| ----------------------- | -------- | -------- | +| DATA_TRANSFER | 1 | 数据传输 | +| AUDIO_PLAYBACK | 2 | 音频播放 | +| AUDIO_RECORDING | 3 | 录音 | +| LOCATION | 4 | 定位导航 | +| BLUETOOTH_INTERACTION | 5 | 蓝牙相关 | +| MULTI_DEVICE_CONNECTION | 6 | 多设备互联 | +| WIFI_INTERACTION | 7 | WLAN相关(系统保留) | +| VOIP | 8 | 音视频通话(系统保留) | +| TASK_KEEPING | 9 | 计算任务(仅供PC使用) | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-particleAbility.md b/zh-cn/application-dev/reference/apis/js-apis-particleAbility.md index 0e2cad1377516dab8e71878eea75c8938aaea29b..0730011d84859cb178d328a94fdbef118a6ac0a5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-particleAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @@ -370,4 +370,171 @@ abilityStartSetting属性是一个定义为[key: string]: any的对象,key对 | WINDOW_MODE_FULLSCREEN | 1 | 全屏。 | | WINDOW_MODE_SPLIT_PRIMARY | 100 | 分屏主屏。 | | WINDOW_MODE_SPLIT_SECONDARY | 101 | 分屏次屏。 | -| WINDOW_MODE_FLOATING | 102 | 悬浮窗。 | \ No newline at end of file +| WINDOW_MODE_FLOATING | 102 | 悬浮窗。 | + + +## particleAbility.startBackgroundRunning + +startBackgroundRunning(id: number, request: NotificationRequest, callback: AsyncCallback<void>): void; + +向系统申请长时任务,使用callback形式返回结果。(此接口为api7接口,后续会被废弃,请使用新的api8接口) + +- **参数**: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | id | number | 是 | 长时任务通知id号 | + | request | NotificationRequest | 是 | 通知参数,用于显示通知栏的信息 | + | callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果 | + +- **示例**: +```js +import notification from '@ohos.notification'; +import particleAbility from '@ohos.ability.particleAbility'; +import wantAgent from '@ohos.wantAgent'; + +function callback(err, data) { + if (err) { + console.error("Operation failed Cause: " + err); + } else { + console.info("Operation succeeded"); + } +} + +let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG] +}; + +wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + let basicContent = { + title: "title", + text: "text" + }; + let notificationContent = { + contentType: notification.ContentType.NOTIFICATION_CONTENT_TEXT, + normal: basicContent + }; + let request = { + content: notificatonContent, + wantAgent: wantAgentObj + }; + let id = 1; + particleAbility.startBackgroundRunning(id, request, callback); +}); + +``` + +## particleAbility.startBackgroundRunning + +startBackgroundRunning(id: number, request: NotificationRequest): Promise<void> + +向系统申请长时任务,使用promise形式返回结果。(此接口为api7接口,后续会被废弃,请使用新的api8接口) + +**参数**: +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| id | number | 是 | 长时任务通知id号 | +| request | NotificationRequest | 是 | 通知参数,用于显示通知栏的信息 | + +**返回值** +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | 使用Promise形式返回结果。 | + +- **示例**: +```js +import notification from '@ohos.notification'; +import particleAbility from '@ohos.ability.particleAbility'; +import wantAgent from '@ohos.wantAgent'; + +let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG] +}; + +wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + let basicContent = { + title: "title", + text: "text" + }; + let notificationContent = { + contentType: notification.ContentType.NOTIFICATION_CONTENT_TEXT, + normal: basicContent + }; + let request = { + content: notificatonContent, + wantAgent: wantAgentObj + }; + let id = 1; + particleAbility.startBackgroundRunning(id, request).then(() => { + console.info("Operation succeeded"); + }).catch((err) => { + console.error("Operation failed Cause: " + err); + }); +}); + +``` + +## particleAbility.cancelBackgroundRunning + +cancelBackgroundRunning(callback: AsyncCallback<void>): void; + +向系统申请取消长时任务,使用callback形式返回结果。(此接口为api7接口,后续会被废弃,请使用新的api8接口) + +- **参数**: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果 | + +- **示例**: +```js +import particleAbility from '@ohos.ability.particleAbility'; + +function callback(err, data) { + if (err) { + console.error("Operation failed Cause: " + err); + } else { + console.info("Operation succeeded"); + } +} + +particleAbility.cancelBackgroundRunning(callback); + +``` + +## particleAbility.cancelBackgroundRunning + +cancelBackgroundRunning(): Promise<void>; + +向系统申请取消长时任务,使用promise形式返回结果。(此接口为api7接口,后续会被废弃,请使用新的api8接口) + +**返回值** +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | 使用Promise形式返回结果。 | + +- **示例**: +```js +import particleAbility from '@ohos.ability.particleAbility'; + +particleAbility.cancelBackgroundRunning().then(() => { + console.info("Operation succeeded"); +}).catch((err) => { + console.error("Operation failed Cause: " + err); +}); + +``` \ No newline at end of file