您的位置:58编程 > 鸿蒙系统服务怎么打开 鸿蒙OS 前台Service

鸿蒙系统服务怎么打开 鸿蒙OS 前台Service

2023-04-16 07:34 鸿蒙OS开发文档

鸿蒙系统服务怎么打开 鸿蒙OS 前台Service

鸿蒙系统服务怎么打开 鸿蒙OS 前台Service

鸿蒙系统服务怎么打开

一般情况下,Service 都是在后台运行的,后台 Service 的优先级都是比较低的,当资源不足时,系统有可能回收正在运行的后台 Service。

在一些场景下(如播放音乐),用户希望应用能够一直保持运行,此时就需要使用前台 Service。前台 Service 会始终保持正在运行的图标在系统状态栏显示。

使用前台 Service 并不复杂,开发者只需在 Service 创建的方法里,调用 keepBackgroundRunning()将 Service 与通知绑定。调用 keepBackgroundRunning() 方法前需要在配置文件中声明 ohos.permission.KEEP_BACKGROUND_RUNNING 权限,该权限是 normal 级别,同时还需要在配置文件中添加对应的 backgroundModes 参数。在 onStop() 方法中调用 cancelBackgroundRunning() 方法可停止前台 Service。

使用前台 Service 的 onStart() 代码示例如下:

// 创建通知,其中1005为notificationId
NotificationRequest 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为创建通知时传入的notificationId
keepBackgroundRunning(1005, request);

在配置文件中配置如下:

{    
    "name": ".ServiceAbility",
    "type": "service",
    "visible": true,
    "backgroundModes": ["dataTransfer","location"]
}
阅读全文
以上是58编程为你收集整理的鸿蒙系统服务怎么打开 鸿蒙OS 前台Service全部内容。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
相关文章
© 2024 58编程 58biancheng.com 版权所有 联系我们
桂ICP备12005667号-32 Powered by CMS