Context.startForegroundService 没有再调用 Service.startForeground

Context.startForegroundService did not then call Service.startForeground

这是我的 BroadcastReciever class。 class 正在启动 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 奥利奥。我不知道那是什么错误。

根据Android 8.0的官方文档后台执行限制

Android 8.0 introduces the new method startForegroundService() to start a new service in the foreground. After the system has created the service, the app has five seconds to call the service's startForeground() method to show the new service's user-visible notification. If the app does not call startForeground() within the time limit, the system stops the service and declares the app to be ANR.

因此,请确保您已通过在服务的 onCreate() 方法中调用 startForeground (int id, Notification notification) 来启动持续通知。

注意: 面向 API Build.VERSION_CODES.P 或更高版本的应用必须请求权限 Manifest.permission.FOREGROUND_SERVICE 才能使用此 API .