【发布时间】:2018-10-25 02:30:23
【问题描述】:
我的 Android 服务中有 Context.startForegroundService() did not then call Service.startForeground(),但我不知道为什么会这样。
我的应用程序用于媒体流,只有当您从前台通知暂停(将其变为常规通知),然后将通知滑开时才会出现此错误,这旨在停止我的服务。
这是调用startForegroundService、startForeground 和stopForeground 方法的唯一方法:
private void configureServiceState(long action) {
if (action == PlaybackStateCompat.ACTION_PLAY) {
if (!mServiceInStartedState) {
ContextCompat.startForegroundService(
StreamingService.this,
new Intent(
StreamingService.this,
StreamingService.class));
mServiceInStartedState = true;
} startForeground(NOTIFICATION_ID,
buildNotification(PlaybackStateCompat.ACTION_PAUSE));
} else if (action == PlaybackStateCompat.ACTION_PAUSE) {
stopForeground(false);
NotificationManager mNotificationManager
= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert mNotificationManager != null;
mNotificationManager
.notify(NOTIFICATION_ID,
buildNotification(PlaybackStateCompat.ACTION_PLAY));
} else if (action == PlaybackStateCompat.ACTION_STOP) {
mServiceInStartedState = false;
stopForeground(true);
stopSelf();
}
}
这里是设置我的通知的删除意图的地方:
.setDeleteIntent(
MediaButtonReceiver.buildMediaButtonPendingIntent(
this, PlaybackStateCompat.ACTION_STOP));
这个configureServiceState(long action) 方法只能从我的MediaSession 回调中调用:onPlay、onPause 和onStop... 显然该操作是要执行的预期操作。
从我的 UI 执行 onStop 或从 UI 调用 onPause 后跟 onStop(镜像清除通知所需的操作)时,仅从通知中不会发生错误。
我能找到的关于此错误的所有信息是,它可能发生在您调用 startForegroundService 但未在 5 秒内调用 startForeground 时......但是在唯一一次 startForegroundService 之后立即调用 startForeground被调用。
此外,onPlaybackStateChange 将在onStop 方法中进入我的“正在播放”活动,这会触发该活动运行finish(),这样服务就不会以这种方式重新启动。
我在这里错过了什么?
其他细节:
我的“正在播放”活动未部分重新启动该服务,因为代码执行从未到达其任何方法。
在产生错误之前,代码执行似乎也永远不会重新输入
configureServiceState-
如果我在最后一个可能的点(我的服务的
李>onStartCommand中的MediaButtonReceiver.handleIntent(mMediaSession, intent);)添加断点,在此处暂停执行并尝试调试会导致调试器在暂停后不久断开连接 为前台和常规通知尝试不同的通知渠道也没有什么不同
将暂停的通知从锁定屏幕上滑开不会导致错误,只有在手机解锁时才会出现;无论我的应用是否真正打开
完全例外:
android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1870)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6809)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
我的测试设备运行的是 Android 8.0,项目的最小 API 是 21,目标 API 是 27。设备 API 是 26。
【问题讨论】:
-
我最近在创建媒体服务时遇到了这个确切的问题(尽管这可能并不完全相关)。请将您的 Android 版本和 API 级别添加到您的问题中,我会看看是否可以提供帮助。
-
谢谢。我已经添加了这一点以及我在调试过程中发现的另一件事。
-
@transiti0nary if (action == PlaybackStateCompat.ACTION_PLAY) 如果条件在 5 秒内执行,这是吗?我的意思是这个条件
true和 ACTION_PLAY 在 5 秒内触发? -
服务启动后 5 秒内?我不知道。为了安全起见,我也可以在
onCreate内触发它,但是是否有检查前台通知是否存在的功能,所以当播放从暂停移动到播放时,我仍然可以在此功能内启动它(当onCreate获胜时不叫?
标签: java android android-notifications foreground-service remoteserviceexception