【发布时间】:2019-10-22 01:40:30
【问题描述】:
我从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 消息传递/分析/等。
- Google Play 服务分析/GCM/Tasks/等。
- Android-Job 来自Evernote
问题是,我无法准确找出导致此错误的服务。如果该类包含在异常中,我就不会在这里...
无论如何 [catch/throw/我不知道] 是否有任何关于异常来自何处的提示?
我已经阅读了以下所有帖子,但完全没有运气:
只有在打开应用程序时才会出现这种情况,所以对我来说我的代码是正确的吗?
我只想知道如何确定这是来自哪个服务。
【问题讨论】:
-
你能重现这个吗(即使只是偶尔)?如果是这样,您应该能够返回 Logcat 并找出最近启动的服务。但是,如果您只是从生产用户那里获得此信息,那么这种方法将行不通。
-
@CommonsWare 感谢您的回答,通过弄清楚您的意思是为启动的服务添加日志行,然后查看它可能是哪一个?它确实经常发生,但不能直接重现。
-
“你的意思是为启动的服务添加日志行,然后看看它可能是哪一个?” -- 不,我认为有报告服务启动的系统日志消息。当然有活动开始。
-
可能。您可能会考虑摆脱所有这些,并在工作完成后让服务自行停止。或者,您可以考虑切换到
WorkManager(或 Android-Job,因为您似乎已经在使用它),而不是为此推出自己的服务。 -
@CommonsWare Removing
onDestroy和onLowMemory停止服务为我解决了这个问题
标签: android service android-notifications foregroundnotification