Context.startForegroundService没有调用Service.startForeground

12

这是我的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上无法工作。我不知道出了什么错误。


https://dev59.com/AVcP5IYBdhLWcg3wa5bQ - Crammeur
最终我们的应用程序问题已经解决 https://dev59.com/AVcP5IYBdhLWcg3wa5bQ#72754189 - Kunal Kalwar
1个回答

18
根据Android 8.0的官方文档Background Execution Limits
Android 8.0引入了新方法startForegroundService()以在前台启动新服务。系统创建服务后,应用程序有五秒钟时间调用服务的startForeground()方法来显示新服务的用户可见通知。如果应用程序未在时限内调用startForeground(),则系统会停止服务并宣布应用程序为ANR。
因此,请确保通过在您服务的onCreate()方法中调用startForeground(int id, Notification notification)来启动持续的通知。
注意:针对API Build.VERSION_CODES.P或更高版本的应用程序必须请求权限Manifest.permission.FOREGROUND_SERVICE才能使用此API。

1
应用程序针对API 27进行了定位,但在Build.VERSION_CODES.P上出现崩溃。 - Sagar
是的,我已经使用startForeground(int id, Notification notification)开始了通知。 - Sagar
@Sagar,你能发布一个新的问题并附上你的崩溃日志吗?把链接发给我,如果我能帮到你,我肯定会的。 - Priyank Patel
@GowthamanM,您是否在添加该权限时遇到任何性能问题? - Limyandi Vico Trico
@LimyandiVicoTrico 由于权限问题,您不会遇到性能问题...您的服务存在问题,请检查您的服务类。 - Gowthaman M
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接