6

我从以下异常输出Device Monitor

//FATAL EXCEPTION: main
//Process: com.xxx.yyy, PID: 11584
//android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
//    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1881)
//    at android.os.Handler.dispatchMessage(Handler.java:105)
//    at android.os.Looper.loop(Looper.java:164)
//    at android.app.ActivityThread.main(ActivityThread.java:6944)
//    at java.lang.reflect.Method.invoke(Native Method)
//    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
//    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

我的应用程序中有 4 项服务,它们基本上看起来像这样:

public class MyService extends Service {

    private static final int forgroundId = 55544433; //Unique for each Service
    private Notification notification;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        initNotification(); //Creates a notification

        startForeground(forgroundId, notification); //Start foreground, very first thing..

        //Do Stuff

        return START_STICKY;
    }
}

要启动服务,我使用以下内容:

Intent i = new Intent(context, MyService.class);
i.SetAction("myaction..");
i.PutExtra(...);
android.support.v4.content.ContextCompat.startForegroundService(context, i);

我还有一些其他库也可能在我的项目中开始包含服务:

  • Fabric.io
  • Firebase 消息传递/分析/等。
  • 谷歌播放服务分析/GCM/任务/等。
  • 来自Evernote的 Android-Job

问题是,我无法准确找出导致此错误的服务。如果该类包含在异常中,我就不会在这里...

无论如何[捕捉/抛出/我不知道]关于异常来自哪里的任何提示?

我已经阅读了以下所有帖子,但完全没有运气:

这只在打开应用程序时有时会发生,所以对我来说我的代码是正确的吗?

我只想知道如何弄清楚这是来自哪个服务。

4

1 回答 1

6

如果调用startForegroundService(),则需要让服务启动。否则,您将得到“Context.startForegroundService() 没有调用 Service.startForeground()”异常。

在您的情况下,有时您会在调用之后停止服务,startForegroundService()但在调用onStartCommand()服务之前。而且,显然,这意味着服务最终永远不会开始。这可以说是一个框架错误,但我们不太可能改变它,所以我们需要处理它。

一种方法是不使用您自己的服务。对于像这样的“一劳永逸”的工作,使用WorkManager, 或可能JobIntentService,您不再需要担心前景。

但是,如果您想坚持使用前台服务,请让该服务启动。一种方法是让服务自行停止。例如,服务可以有自己的onLowMemory()方法,它可以在其中停止自己。该服务知道该服务是否已调用startForeground(),并且可以比外部方更优雅地处理它。

于 2019-06-06T15:56:47.170 回答