22、鸿蒙OS 前台Service
- 作者: ___娇娇___
- 来源: 51数据库
- 2022-10-14
一般情况下,Service 都是在后台运行的,后台 Service 的优先级都是比较低的,当资源不足时,系统有可能回收正在运行的后台 Service。
在一些场景下(如播放音乐),用户希望应用能够一直保持运行,此时就需要使用前台 Service。前台 Service 会始终保持正在运行的图标在系统状态栏显示。
使用前台 Service 并不复杂,开发者只需在 Service 创建的方法里,调用 keepBackgroundRunning()将 Service 与通知绑定。调用 keepBackgroundRunning() 方法前需要在配置文件中声明 ohos.permission.KEEP_BACKGROUND_RUNNING 权限,该权限是 normal 级别,同时还需要在配置文件中添加对应的 backgroundModes 参数。在 onStop() 方法中调用 cancelBackgroundRunning() 方法可停止前台 Service。
使用前台 Service 的 onStart() 代码示例如下:
// 创建通知,其中1005为notificationIdNotificationRequest request = new NotificationRequest(1005);NotificationRequest.NotificationNormalContent content = new NotificationRequest.NotificationNormalContent();content.setTitle("title").setText("text");NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);request.setContent(notificationContent); // 绑定通知,1005为创建通知时传入的notificationIdkeepBackgroundRunning(1005, request);
在配置文件中配置如下:
{ "name": ".ServiceAbility", "type": "service", "visible": true, "backgroundModes": ["dataTransfer","location"]}
推荐阅读