Context.startForegroundService 然后没有调用 Service.startForeground
Posted
技术标签:
【中文标题】Context.startForegroundService 然后没有调用 Service.startForeground【英文标题】:Context.startForegroundService did not then call Service.startForeground 【发布时间】:2019-01-09 06:56:54 【问题描述】:这是我的 BroadcastReciever 类。处理 Boot phone 状态的类。
代码;
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。我不知道这是什么错误。
【问题讨论】:
***.com/questions/44425584/… Context.startForegroundService() did not then call Service.startForeground()的可能重复 看看这里! Context.startForegroundService() did not then call Service.startForeground() 【参考方案1】:根据Android 8.0官方文档Background Execution Limits
Android 8.0 引入新方法 startForegroundService() 在前台启动新服务。 系统创建服务后,应用有 5 秒 调用服务的 startForeground() 方法来显示新服务的 用户可见的通知。 如果应用没有调用 startForeground() 时限内,系统停止服务并声明 应用成为 ANR。
因此,请确保您已通过在服务的 onCreate()
方法中调用 startForeground (int id, Notification notification) 开始持续通知。
注意:以 API Build.VERSION_CODES.P
或更高版本为目标的应用程序必须请求权限 Manifest.permission.FOREGROUND_SERVICE
才能使用此 API。
【讨论】:
应用程序以API 27
为目标,但在 Build.VERSION_CODES.P
上崩溃
@Sagar 您是否在服务类中使用startForeground(int id, Notification notification)
方法开始通知?
是的,我已经使用startForeground(int id, Notification notification)
开始通知
@Sagar 你能用你的崩溃日志发布一个新问题吗?把那个链接发给我,如果可以的话我一定会帮助你的。
我添加了这个android.permission.FOREGROUND_SERVICE
它正在工作以上是关于Context.startForegroundService 然后没有调用 Service.startForeground的主要内容,如果未能解决你的问题,请参考以下文章