我在我的Android服务中使用了Context.startForegroundService()没有然后调用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
时发生... 但是startForeground
是在唯一一次调用 startForegroundService
之后立即调用的。
此外,在onStop
方法中,一个onPlaybackStateChange
将传输到我的“现在播放”活动,触发那个活动运行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。
onCreate
中触发它,但是否有函数来检查前台通知是否存在,以便在播放从暂停转换到播放时(当onCreate
不会被调用时)仍然可以在此函数中启动它? - transiti0nary