android - Context.startForegroundService 然后没有调用 Service.startForeground
问题描述
这是我的 BroadcastReciever 类。处理启动电话状态的类。
代码 ;
public class BroadCastRecieverBoot extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent ıntent) {
if(Intent.ACTION_BOOT_COMPLETED.equals(ıntent.getAction()))
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, MyService.class));
context.startForegroundService(new Intent(context, GPSTracker.class));
} else {
context.startService(new Intent(context, MyService.class));
context.startService(new Intent(context, GPSTracker.class));
}
}
}
}
我收到此错误;
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1792)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857)
它现在不适用于 Android Oreo。我不知道那是什么错误。
解决方案
根据Android 8.0 Background Execution Limits 的官方文档
Android 8.0 引入了新方法 startForegroundService()在前台启动新服务。系统创建服务后,应用程序有五秒钟的时间调用服务的startForeground()方法以显示新服务的用户可见通知。如果应用程序在时限内没有调用startForeground(),系统将停止服务并声明应用程序为ANR。
因此,请确保您已通过在您的服务方法中调用startForeground (int id, Notification notification)来启动持续通知。onCreate()
注意:面向 APIBuild.VERSION_CODES.P
或更高版本的应用必须请求权限Manifest.permission.FOREGROUND_SERVICE
才能使用此 API。
推荐阅读
- vue.js - VueJS:如何将父母的标记传递给孩子的`
` 当孩子被直接访问(通过路由器)? - python - 在用户定义的函数中使用模块
- ngx-logger - 每个类的唯一记录器名称
- python - 如何循环一个函数以每 15 分钟执行一次任务(在 0/15/30/45 分钟标记上)?
- r - 如何将小标题列表拆分为各自的小标题
- linux - Kops 滚动更新失败,主节点出现“集群未通过验证”
- sql - Access SQL 查询在不同的计算机上失败
- java - 使用 Java 客户端库配置 PubSub 的消息保留时间
- if-statement - 如何根据另一列中的第一个空白行计算一列中空白单元格的数量
- java - Spring Boot 和 JUnit 5 之间的交互——必须使用整体工件而不是个人?