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

2024-01-11

我有Context.startForegroundService() did not then call Service.startForeground()在我的 Android 服务中,但我不明白为什么会发生这种情况。

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

这是唯一的方法startForegroundService, startForeground and 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));

This configureServiceState(long action)方法仅从我的调用MediaSession回调:onPlay, onPause and onStop...显然该操作是要执行的预期操作。

执行时不会出现该错误onStop从我的用户界面,或者打电话时onPause其次是onStop从 UI(镜像清除通知所需的操作),仅从通知。

我所能找到的关于此错误的全部信息是,当您致电时,它应该会发生startForegroundService但不要打电话startForeground5 秒内...然而startForeground在唯一一次之后立即调用startForegroundService被调用。

另外,一个onPlaybackStateChange即将转到我的“正在播放”活动onStop方法,触发该活动运行finish()这样服务就不会以这种方式重新启动。

我在这里缺少什么?

额外细节:

  • 该服务没有被我的“正在播放”活动部分重新启动,因为代码执行从未到达其任何方法。

  • 代码执行似乎也永远不会重新输入configureServiceState在错误产生之前

  • 如果我在最后一个可能的点添加断点(MediaButtonReceiver.handleIntent(mMediaSession, intent); in onStartCommand我的服务),在这里暂停执行并尝试调试会导致调试器在暂停后不久断开连接

  • 为前台尝试不同的通知渠道与常规通知也没有什么区别

  • 将暂停的通知从锁定屏幕上滑开不会导致错误,仅在手机解锁时才会发生;无论我的应用程序是否真正打开

完整异常:

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,项目 min API 是 21,目标 API 是 27。设备 API 是 26。


对于 Android O API 26 及更高版本,您需要使用NotificationChannel,否则您将收到所遇到的错误。请参阅 Android 文档中的以下声明 -创建和管理通知渠道 https://developer.android.com/training/notify-user/channels:

从 Android 8.0(API 级别 26)开始,所有通知都必须分配给一个通道。

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

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

    val description = mMetadata.description

    // https://stackoverflow.com/questions/45395669/notifications-fail-to-display-in-android-oreo-api-26
    @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())
}

In your 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)
}

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

startForegroundService() 没有调用 startForeground(),但它确实调用了 的相关文章

  • 如何识别图形线条

    我有以下格式的路径的 x y 数据 示例仅用于说明 seq p1 p2 0 20 2 3 1 20 2 4 2 20 4 4 3 22 5 5 4 22 5 6 5 23 6 2 6 23 6 3 7 23 6 4 每条路径都有多个点 它们
  • 将数组值导出到 csv 文件 java

    我只需要帮助将数组元素导出到 csv 文件 我不知道我的代码有什么问题 任何帮助将不胜感激 谢谢 for int index 0 index lt cols length index FileWriter fw new FileWriter
  • 如何强制下载图片?

    我的页面上有一个动态生成的图像 如下所示 img src 我不想告诉我的用户右键单击图像并点击保存 而是想公开一个下载链接 单击该链接将提示下载图像 如何实现这一目标 最初我在 js 中尝试这样做 var path my image att
  • 将 Hbase 与 PHP 集成 [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我已经安装了 Hbase 现在我正在寻找一些 PHP 库来将 hbase 与 PHP 集成 我尝试了 2 个库 第一个是我尝试与 th
  • SimpleXML 返回空数组

    我正在尝试使用 Google Maps API 和 PHP SimpleXML 获取城市的纬度和经度 我尝试这样做 xml simplexml load file http maps googleapis com maps api geoc
  • CUDA 添加矩阵的行

    我试图将 4800x9600 矩阵的行加在一起 得到一个 1x9600 的矩阵 我所做的是将 4800x9600 分成 9 600 个矩阵 每个矩阵长度为 4800 然后我对 4800 个元素进行缩减 问题是 这真的很慢 有人有什么建议吗
  • 声明 for 循环变量时 &mut 会做什么吗?

    考虑以下 愚蠢的 程序 fn main let mut array mut 1u8 2u8 3u8 for mut value in array 它编译并运行正常 尽管如预期的那样警告未使用的变量 不必要的可变性 但有什么作用 mut做在f
  • AWK 错误:尝试在标量上下文中使用数组

    我正在学习AWK 这是一个简单的代码片段 我尝试将字符串拆分为数组并迭代它 BEGIN split a b c a for i 1 i lt length a i print a i 运行此代码时 我收到以下错误 awk awk txt 4
  • 如何使用placement new重新初始化该字段?

    我的课程包含字段 private OrderUpdate curOrderUpdate 我一遍又一遍地使用它 经常需要重新初始化 for int i 0 i lt entries size i auto entry entries i ne
  • 突出显示单词并提取其附近文本的函数

    我有一个文本例如 Etiam porta semmalesuada magna mollis euismod 整数取数 ante venenatis dapibus posuere velit aliquet 埃蒂亚姆 门塔 塞姆 male
  • [GoF]-ConcreteSubject 可以覆盖通知方法吗?

    我正在模拟一种情况 其中存在 通知框 观察者 list1 list2 list3 这个科目 现在我会制作一张图表 其中使用观察者模式描述每个列表实现不同类型的notify 这一事实 例如 列表状态的某些变化只需要按照某些标准通知给某些观察者
  • 拉斐尔路径交叉点不起作用

    我对拉斐尔和 pathIntersection method JSFiddle 示例 http jsfiddle net t6gWt 2 您可以看到有两条线都与曲线相交 但当我使用 pathIntersection method 有一个未解
  • 缓存感知树的实现

    I have a tree where every node may have 0 to N children 用例是以下查询 给定指向两个节点的指针 这些节点是否位于树的同一分支内 Examples q 2 7 gt true q 5 4
  • 结构化绑定的用例有哪些?

    C 17 标准引入了新的结构化绑定 http en cppreference com w cpp language structured binding功能 最初是proposed http www open std org jtc1 sc
  • 在引导程序中以编程方式更改选项卡窗格选项卡

    我使用的选项卡窗格定义为 ul class nav nav tabs li a href personal Personal Information a li li class active a href contact Contact a
  • Jenkins 通过 ssh 发布显示错误“jenkins.plugins.publish_over.BapPublisherException:无法添加 SSH 密钥。”

    为了使用 ssh 连接 jenkins 与远程服务器 我在 jenkins 中安装了通过 SSH 发布的插件 但配置后 它显示错误为 jenkins plugins publish over BapPublisherException 无法
  • 小部件配置在 macOS 上不起作用

    我为我的 iOS 应用程序制作了一个小部件 效果很好 现在我正在将其移植到我的 macOS 应用程序中 但不知何故 小部件配置不起作用 这些项目已显示 但我无法以某种方式选择它们 查看屏幕截图 但请看一下我制作的视频 https youtu
  • 使用 numpy 加速 for 循环

    下一个 for 循环如何使用 numpy 获得加速 我想这里可以使用一些奇特的索引技巧 但我不知道是哪一个 这里可以使用 einsum 吗 a 0 for i in range len b a numpy mean C d e f b i
  • 使用未分配的局部变量

    我遇到了一个错误 尽管声明了变量 failturetext 和 userName 错误仍然出现 谁能帮帮我吗 Use of Unassigned local variable FailureText Use of Unassigned lo
  • 将 R 中的列中的单引号替换为双引号

    我在 R 中的数据框有一个 A 列 其中有带单引号的字符串数据 Column A Hello World Hi World Good morning world 我想做的是将单引号替换为双引号并实现如下所示的输出 Column A Hell

随机推荐