Context.startForegroundService() 然后没有调用 Service.startForeground

2023-12-11

我的应用程序将调用startForegroundService(intent) in the onCreate of the MainActivity。我把startForeground(ON_SERVICE_CONNECTION_NID, notification)在两个onCreatestartCommand of the Service。 但我仍然偶尔收到此错误。

Exception android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
android.app.ActivityThread$H.handleMessage (ActivityThread.java:1775)
android.os.Handler.dispatchMessage (Handler.java:105)
android.os.Looper.loop (Looper.java:164)
android.app.ActivityThread.main (ActivityThread.java:6541)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:240)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:767)

怎么会发生这种事? 是否有可能onCreate or startCommand5秒后没有接到电话? 如果是这样,我们应该如何调用startForegroundService没有错误吗?

更新于2017-12-09

我不知道为什么每个人都说这与这个问题相同:Context.startForegroundService() 然后没有调用 Service.startForeground()你甚至可以在那里找到我的评论。

其不同的原因是您可以在这个问题的第一行看到的内容。我已经把startForegroundService and startForeground在正确的位置,但它仍然随机显示此错误。

这是 Google 问题跟踪器:https://issuetracker.google.com/issues/67920140

在此之前停止服务将导致崩溃。

这是关于服务生命周期的另一个问题。 服务关闭后可能会错误地触发断言。


我面临同样的问题,在花了时间找到解决方案后,您可以尝试下面的代码。如果您使用Service然后把这段代码放入onCreate否则你使用Intent Service然后把这段代码放入onHandleIntent.

if (Build.VERSION.SDK_INT >= 26) {
    String CHANNEL_ID = "my_app";
    NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
            "MyApp", NotificationManager.IMPORTANCE_DEFAULT);
    ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("")
            .setContentText("").build();
    startForeground(1, notification);
}

并称之为

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(getSyncIntent(context));
    } else {
        context.startService(getSyncIntent(context));
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Context.startForegroundService() 然后没有调用 Service.startForeground 的相关文章

随机推荐