合作咨询
我们的专家服务团队将竭诚为您提供专业的合作咨询服务
吕辉【问题现象】:不确定鸿蒙是否能在后台持续保持蓝牙连接
【版本信息】:不涉及
【复现代码】:不涉及
【尝试解决方案】:不涉及
云帆扬应用退至后台后,在后台需要长时间运行用户可感知的任务,如蓝牙相关业务等。为防止应用进程被挂起,导致对应功能异常,可以申请长时任务,使应用在后台长时间运行。
可参考以下:
"requestPermissions": [
{
"name": "ohos.permission.KEEP_BACKGROUND_RUNNING"
}
]
2. 声明蓝牙传输后台模式类型。在module.json5文件中为需要使用长时任务的UIAbility声明相应的长时任务类型,配置文件中填写长时任务类型的配置项。
"module": {
"abilities": [
{
"backgroundModes": [
// 配置长时任务类型为蓝牙传输
"bluetoothInteraction"
]
}
],
// ...
}
3. 导入长时任务相关模块。
import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { wantAgent, WantAgent } from '@kit.AbilityKit';
import { ble } from '@kit.ConnectivityKit';
4. 申请和取消长时任务。
import { bundleManager, wantAgent } from '@kit.AbilityKit'
import { ble } from '@kit.ConnectivityKit'
import { backgroundTaskManager } from '@kit.BackgroundTasksKit'
class BackgroundRunningManager {
// 申请长时任务
async startBackgroundRunning() {
// 获取bundle应用信息
const bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
// 通过wantAgent模块下getWantAgent方法获取WantAgent对象
const wantAgentObj = await wantAgent.getWantAgent({
// 添加需要被拉起应用的bundleName和abilityName
wants: [{ bundleName: bundleInfo.name, abilityName: "EntryAbility" }],
// 使用者自定义的一个私有值
requestCode: 0,
actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG],
// 车钥匙长时任务子类型。只有申请bluetoothInteraction类型的长时任务,车钥匙子类型才能生效。
// 确保extraInfo参数中的Key值为backgroundTaskManager.BackgroundModeType.SUB_MODE,否则子类型不生效。
extraInfo: { [backgroundTaskManager.BackgroundModeType.SUB_MODE] : backgroundTaskManager.BackgroundSubMode.CAR_KEY }
})
// 创建类型为BLUETOOTH_INTERACTION的后台任务
await backgroundTaskManager.startBackgroundRunning(context,backgroundTaskManager.BackgroundMode.BLUETOOTH_INTERACTION, wantAgentObj)
}
// 停止后台任务
async stopBackgroundRunning() {
backgroundTaskManager.stopBackgroundRunning(getContext())
}
}
5.
调用方式。
backgroundTaskManager.startBackgroundRunning(this.context, backgroundTaskManager.BackgroundMode.BLUETOOTH_INTERACTION, wantAgentObj).then((res: backgroundTaskManager.ContinuousTaskNotification) => {
console.info("Operation startBackgroundRunning succeeded")
// 此处执行具体的蓝牙业务逻辑。
}).catch((error: BusinessError) => {
console.error(`Failed to Operation startBackgroundRunning. code is ${error.code} message is ${error.message}`)
});
// 执行封装好的长时任务方法
this.startContinuousTask()
// 执行蓝牙相关业务逻辑
ble.startBLEScan()
开启蓝牙后台长时任务时,若蓝牙连接断开需在一分钟内重新连接成功,否则长时任务将自动结束
【背景知识】
我要提问题
HarmonyOS滑动手势离开Scroll后如何持续滚动?(API12+)
HarmonyOS 如何后台拉起悬浮窗 (API12+)
HarmonyOS ble蓝牙连接数据收发 (API12+)
HarmonyOS 连接WIFI对应的API以及示例 (API12+)
华为运动健康数据实时性问题
HarmonyOS 如何实现后台通知(API12+)
HarmonyOS 应用后台需要保持WIFI直连,传输数据,目前应用退出前台就会断连,是请问什么原因?(API12+)
HarmonyOS 应用切入后台之后,如何实时获取华为运动数据? (API12+)
合作咨询
我们的专家服务团队将竭诚为您提供专业的合作咨询服务
解决方案
精准高效的一站式服务支持,助力开发者商业成功