startForegroundService() 没有调用 startForeground(),但它调用了

startForegroundService() did not call startForeground(), but it did

我的 Android 服务中有 Context.startForegroundService() did not then call Service.startForeground(),但我不知道为什么会这样。

我的应用是媒体流,只有当你从前台通知暂停(将其变成常规通知),然后将通知滑开时才会出现此错误,这是为了停止我的服务。

这是唯一调用 startForegroundServicestartForegroundstopForeground 方法的方法:

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 回调中调用:onPlayonPauseonStop... 显然操作是要执行的预期操作。

从我的 UI 执行 onStop 或从 UI 调用 onPause 后跟 onStop 时(镜像清除通知所需的操作),仅来自通知。

我能找到的关于这个错误的所有信息是,当您调用 startForegroundService 但没有在 5 秒内调用 startForeground 时,它应该会发生...但是调用了 startForeground在唯一一次 startForegroundService 被调用后立即。

此外,onPlaybackStateChange 将转到 onStop 方法中的 'Now Playing' activity,这会触发 activity 到 运行 finish() 这样服务就不会以这种方式重新启动。

我在这里错过了什么?

其他详细信息:

完全异常:

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)

我的测试设备是运行ning Android 8.0,项目最小API是21,目标API是27。设备API是26 .

只是在这上面浪费了太多时间。我不确定这是您遇到的情况,但就我而言,我一直收到此异常,因为我的 NOTIFICATION_ID0 ...使用任何其他值似乎可以解决此问题。-_-

您需要为 Android O API 26 及更高版本使用 NotificationChannel,否则您将遇到您遇到的错误。请参阅 Android 文档中的以下声明 - Create and Manage Notification Channels:

Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel.

这是我用于构建媒体通知的方法的摘录(从中获取您需要的内容)。你可以看到有一个检查 Android O 设备用特定的方法来处理这种情况:

private fun compileNotification(context: Context, action: NotificationCompat.Action, mediaSession: MediaSessionCompat, controller: MediaControllerCompat, mMetadata: MediaMetadataCompat, art: Bitmap?, mPlaybackState: PlaybackStateCompat) {

    val description = mMetadata.description

    // 
    @TargetApi(26)
    if(Utils.hasO()) {
        val channelA = mNotificationManager?.getNotificationChannel(NotificationChannelID.MEDIA_SERVICE.name)

        if(channelA == null) {
            val channelB = NotificationChannel(NotificationChannelID.MEDIA_SERVICE.name,
                    "MediaService",
                    NotificationManager.IMPORTANCE_DEFAULT)
            channelB.setSound(null, null)

            mNotificationManager?.createNotificationChannel(channelB)
        }
    }

    val notificationBuilder = if(Utils.hasLollipop()) {
        NotificationCompat.Builder(context, NotificationChannelID.MEDIA_SERVICE.name)
    } else {
        NotificationCompat.Builder(context)
    }

    notificationBuilder
            .setStyle(android.support.v4.media.app.NotificationCompat.MediaStyle()
                    // Show actions 0,2,4 in compact view
                    .setShowActionsInCompactView(0,2,4)
                    .setMediaSession(mediaSession.sessionToken))
            .setSmallIcon(R.drawable.logo_icon)
            .setShowWhen(false)
            .setContentIntent(controller.sessionActivity)
            .setContentTitle(description.title)
            .setContentText(description.description)
            .setLargeIcon(art)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setOngoing(mPlaybackState.state == PlaybackStateCompat.STATE_PLAYING)
            .setOnlyAlertOnce(true)

            if(!Utils.hasLollipop()) {
                notificationBuilder
                        .setStyle(android.support.v4.media.app.NotificationCompat.MediaStyle()
                                // Show actions 0,2,4 in compact view
                                .setShowActionsInCompactView(0,2,4)
                                .setMediaSession(mediaSession.sessionToken)
                                .setShowCancelButton(true)
                                .setCancelButtonIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(context,
                                        PlaybackStateCompat.ACTION_STOP)))
                        // Stop the service when the notification is swiped away
                        .setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(context,
                                PlaybackStateCompat.ACTION_STOP))
            }

    notificationBuilder.addAction(NotificationCompat.Action(
            R.drawable.exo_controls_previous,
            "Previous",
            MediaButtonReceiver.buildMediaButtonPendingIntent(context,
                    PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)))
    notificationBuilder.addAction(NotificationCompat.Action(
            R.drawable.ic_replay_10_white_24dp,
            "Rewind",
            MediaButtonReceiver.buildMediaButtonPendingIntent(context,
                    PlaybackStateCompat.ACTION_REWIND)))

    notificationBuilder.addAction(action)

    notificationBuilder.addAction(NotificationCompat.Action(
            R.drawable.ic_forward_10_white_24dp,
            "Fast Foward",
            MediaButtonReceiver.buildMediaButtonPendingIntent(context,
                    PlaybackStateCompat.ACTION_FAST_FORWARD)))
    notificationBuilder.addAction(NotificationCompat.Action(
            R.drawable.exo_controls_next,
            "Next",
            MediaButtonReceiver.buildMediaButtonPendingIntent(context,
                    PlaybackStateCompat.ACTION_SKIP_TO_NEXT)))

    (context as MediaService).startForeground(NOTIFICATION_ID, notificationBuilder.build())
}

在您的 onStop() 回调中,您需要在服务中调用 stopSelf()。然后,当您的服务 onDestroy() 方法被调用时,您需要清理一些东西(适用于您的情况),如下所示:

override fun onDestroy() {
    super.onDestroy()

    abandonAudioFocus()
    unregisterReceiver(mNoisyReceiver)

    //Deactivate session
    mSession.isActive = false
    mSession.release()

    NotificationManagerCompat.from(this).cancelAll()

    if(mWiFiLock?.isHeld == true) mWiFiLock?.release()

    stopForeground(true)
}

我没有包含上面某些方法的详细信息,但方法名称应该是自我注释 - 如果我可以包含更多详细信息,请告诉我。其中一些可能有些矫枉过正,但在您的情况下可能会解决问题。

我很确定这会解决您的问题。如果没有,我还有一些想法。

我遇到了同样的问题。问题是在通知项目上使用 PendingIntent.getForegroundService() 单击以更新媒体服务。仅使用 PendingIntent.getService 就解决了我的问题。