一般情况下,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"]
}
场景介绍应用使用当前的数据网络打开一个 URL 链接。接口说明应用使用当前网络打开一个 URL 链接,所使用的接口说明如下。类名接...
场景介绍应用通常需要获取用户所在蜂窝网络下信号信息,以便获取当前驻网质量。开发者可以通过本业务,获取到用户指定 SIM 卡当...
RadioContainerjava.lang.Object |---ohos.agp.components.Component |---|---ohos.agp.components.ComponentContainer |---|---...
TransitionAlphajava.lang.Object |---ohos.agp.transition.Transition |---|---ohos.agp.transition.TransitionAlphapublic cla...
NotificationRequest.NotificationMediaContentjava.lang.Object |---ohos.event.notification.NotificationRequest.Notificatio...