我从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);
我还有其他一些库,它们的项目中可能还包含一些开始的服务:
问题是,我无法确切找出是哪个服务导致此错误。如果该类包含在异常中,那么我就不会在这里...
反正有[catch / throw / 我不知道]关于异常来自何处的任何提示吗?
我阅读了以下所有帖子,完全没有运气:
仅在打开应用程序时才会发生这种情况,所以对我来说我的代码正确吗?
我只想知道如何确定它来自哪个服务。
答案 0 :(得分:2)
如果您致电startForegroundService()
,则需要让该服务启动。否则,您将获得“ Context.startForegroundService()并未调用Service.startForeground()”异常。
在您的情况下,似乎有时您会在调用startForegroundService()
之后但在调用onStartCommand()
之前停止该服务。而且,显然,这意味着该服务永远都不会启动。可以说这是一个框架错误,但是我们不太可能进行更改,因此我们需要对其进行处理。
一种方法是不使用您自己的服务。对于像这样的“忘了做”的工作,请使用WorkManager
或可能的JobIntentService
,而您不再需要担心前景。
但是,如果您想使用前台服务,请让该服务启动。一种方法是让服务自行停止。例如,服务可以具有自己的onLowMemory()
方法,可以在其中停止自身。该服务知道该服务是否已调用startForeground()
,并且比外部参与者可以更优雅地处理该问题。