虽然这里似乎有一些关于Android 12服务限制的问题,但我还没有看到一个特定于这个用例的问题。
背景:我正在启动前台服务,以处理非常长时间运行的后台媒体播放器(Exoplayer)。由于应用程序的设置,我不能使用外星内置通知管理器。然而,我看到了一种奇怪的行为从破折主义。我得到的ForegroundServiceStartNotAllowedException
,而应用程序无疑是在前景。根据日志,很容易看到用户在startForeground
调用后的一秒内导航应用程序。
我也在听
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event)
以确保应用程序处于前台状态。
关于造成这种情况的原因,我已经没有任何想法了。从时间戳可以看出,不到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>
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()
)
}
}
编辑:@Arlind建议的设备状态选项卡
发布于 2022-09-30 12:59:21
有一件事情看起来很有希望(在我获得更多的数据之前,我不会将任何答案标记出来),就是将这一点添加到通知生成器中:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
foregroundServiceBehavior = Notification.FOREGROUND_SERVICE_IMMEDIATE
}
然后,为了防止崩溃,但仍然收到一个问题的通知,我在一个尝试/捕捉中封装了startForeground
,并将其发布到crashlytics,这样我就知道存在一个问题:
if (!audioFocusTakenBackground && Application.instance.isAppInForeground && !isForegroundActive) {
isForegroundActive = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
try {
startForeground(ONGOING_NOTIFICATION_ID, builder.build(), ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK)
true
} catch (e: Exception) {
Timber.e("Unable to start foreground: ${e.message}")
FirebaseCrashlytics.getInstance().recordException(e)
false
}
} else {
try {
startForeground(ONGOING_NOTIFICATION_ID, builder.build())
true
} catch (e: Exception) {
Timber.e("Unable to start foreground: ${e.message}")
FirebaseCrashlytics.getInstance().recordException(e)
false
}
}
}
注意,在Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
区域中,它添加了通知是FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
。根据这里的google:https://developer.android.com/guide/components/foreground-services#notification-immediate,这应该足以初步显示通知。我很好奇某些实现是否不使用或不听。
当我得到更多的数据时,我会更新它,但是现在我的崩溃已经平息了,而且我没有看到任何来自crashlytics中的捕捉块的日志记录。希望其他人能用这个来验证我的发现。
编辑:
几天后,这个错误导致的崩溃减少到0,没有观察到捕捉到的明显日志。最后把这封信
发布于 2022-03-23 15:56:35
Application.instance.isAppInForeground
这个变量有正确的值吗?也许这个变量得到了错误的值。你能检查一下吗?
发布于 2022-03-22 15:42:20
不要尝试使用您自己的服务播放音频。始终使用MediaSession API,如下所述:https://developer.android.com/guide/topics/media-apps/audio-app/building-an-audio-app
https://stackoverflow.com/questions/70711950
复制相似问题