这是我的BroadcastReceiver类。该课程处理启动电话状态。
代码;
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()
来开始持续通知。
注意:针对API Build.VERSION_CODES.P
或更高版本的应用必须请求权限Manifest.permission.FOREGROUND_SERVICE
才能使用此API。