小编bre*_*ite的帖子

Android 12 ForegroundServiceStartNotAllowedException 在前台时出现?

虽然这里似乎存在一些有关 Android 12 服务限制的问题,但我还没有看到专门针对此用例的问题。

背景:我正在启动一个前台服务来处理一个长时间运行的后台媒体播放器(Exoplayer)。由于应用程序的设置,我无法使用 exoplayer 的内置通知管理器。然而,我发现 Crashlytics 存在奇怪的行为。我得到ForegroundServiceStartNotAllowedException虽然该应用程序无疑位于前台。根据日志,很容易看到用户在通话后一秒内就在应用程序中导航startForeground

我也在听

override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event)
Run Code Online (Sandbox Code Playgroud)

确保应用程序处于前台状态。

日志

碰撞

我开始不知道什么会导致这种情况。从时间戳可以看出,过去了不到 1 秒。该应用程序不存在服务可能意外从后台启动的用例。

谢谢

编辑:

我还声明我的服务类型:

        <service
            android:name=".service.SoundPlayerService"
            android:enabled="true"
            android:exported="false"
            android:foregroundServiceType="mediaPlayback"
            android:stopWithTask="false">
            <intent-filter>
                <action android:name="android.media.browse.MediaBrowserService" />
            </intent-filter>
        </service>
Run Code Online (Sandbox Code Playgroud)
        if (!audioFocusTakenBackground && Application.instance.isAppInForeground) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                startForeground(
                    ONGOING_NOTIFICATION_ID,
                    builder.build(),
                    ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
                )
            } else {
                startForeground(
                    ONGOING_NOTIFICATION_ID,
                    builder.build()
                )
            }
        }
Run Code Online (Sandbox Code Playgroud)

编辑:@Arlind 建议的设备状态选项卡

设备状态

android kotlin

23
推荐指数
1
解决办法
8834
查看次数

Android 12 - 媒体通知消失

我在 Android 12 上遇到了一些奇怪的行为。特别是对于MediaBrowserService. 该应用程序将在后台长时间播放声音。我在 Android 12 上遇到了两种不同但不受欢迎的行为。

在 Pixel 5a 上 - 通知会出现,但会在一小时左右后在后台消失。音乐仍然可以正常播放,如果打开应用程序可以暂停。

在 Samsung s21 上 - 播放声音时会出现通知。但如果它被停止,并且另一个启动,通知将不会在启动服务时再次出现,直到手机本身重新启动。

在运行 Android 10 的 s9 和运行 Android 11 的 OnePlus 8 上,没有任何问题。

创建通知似乎非常简单:


companion object {
    const val ACTION_STOP = "action_stop"
    const val CHANNEL_ID = "app_notification_channel"
    const val NOTIFICATION_CHANNEL_TAG = "Playing Controls"
    const val ONGOING_NOTIFICATION_ID = 2222
}

private fun refreshNotification(stopCalled: Boolean = false) {
        val sounds = playingSounds

        if (sounds.isEmpty() || stopCalled) {
            // if we lost …
Run Code Online (Sandbox Code Playgroud)

android kotlin exoplayer

6
推荐指数
0
解决办法
801
查看次数

标签 统计

android ×2

kotlin ×2

exoplayer ×1