如何在Android 13模拟器复现ForegroundServiceStartNotAllowedException?
Android 12+模拟器复现ForegroundServiceStartNotAllowedException问题
根据Google Play Console的「崩溃与ANR」页面显示,我的音乐播放器应用在Android 12+设备上频繁出现ForegroundServiceStartNotAllowedException崩溃,这源于Android 12+引入的「后台应用无法启动前台服务」限制。
我没有Android 12+实体设备,因此搭建了运行Android 13的模拟器尝试复现,但未能成功。我怀疑这是模拟器的原因,请问是否有方法配置模拟器以确保该崩溃复现?
示例堆栈跟踪
以下是Google Play Console上报的示例堆栈跟踪:
Exception java.lang.RuntimeException: at android.app.ActivityThread.handleServiceArgs (ActivityThread.java:5261) at android.app.ActivityThread.-$$Nest$mhandleServiceArgs at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2447) at android.os.Handler.dispatchMessage (Handler.java:106) at android.os.Looper.loopOnce (Looper.java:226) at android.os.Looper.loop (Looper.java:313) at android.app.ActivityThread.main (ActivityThread.java:8757) at java.lang.reflect.Method.invoke at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:571) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1067) Caused by android.app.ForegroundServiceStartNotAllowedException: at android.app.ForegroundServiceStartNotAllowedException$1.createFromParcel (ForegroundServiceStartNotAllowedException.java:54) at android.app.ForegroundServiceStartNotAllowedException$1.createFromParcel (ForegroundServiceStartNotAllowedException.java:50) at android.os.Parcel.readParcelableInternal (Parcel.java:4787) at android.os.Parcel.readParcelable (Parcel.java:4755) at android.os.Parcel.createExceptionOrNull (Parcel.java:3018) at android.os.Parcel.createException (Parcel.java:3007) at android.os.Parcel.readException (Parcel.java:2990) at android.os.Parcel.readException (Parcel.java:2932) at android.app.IActivityManager$Stub$Proxy.setServiceForeground (IActivityManager.java:6978) at android.app.Service.startForeground (Service.java:743) at github.daneren2005.dsub.util.Notifications.startForeground (Notifications.java:462) at github.daneren2005.dsub.util.Notifications.shutGoogleUpNotification (Notifications.java:384) at github.daneren2005.dsub.service.DownloadService.onStartCommand (DownloadService.java:317) at android.app.ActivityThread.handleServiceArgs (ActivityThread.java:5243)
当前复现步骤
- 在应用中启动音乐播放
- 点击Home键将应用置于后台
- 在模拟器上点击「CALL DEVICE」(此时音乐暂停)
- 挂断电话(短暂暂停后音乐恢复播放,我预期此时会崩溃)
我认为此时应该触发崩溃,因为我在启动前台服务的代码中添加了日志:
... Log.d(TAG, "Notifications, current state: " + ProcessLifecycleOwner.get().getLifecycle().getCurrentState()); downloadService.startForeground(notificationId, notification); ...
此时生命周期状态为CREATED,意味着应用处于后台,但崩溃并未发生,应用仍正常运行。
已尝试的操作
- 确保应用已开启电池优化,尝试了「优化」和「限制」模式
- 修改模拟器的电池设置
- 启用ActivityManager日志记录受限前台启动,在logcat中看到了日志:
ActivityManager: Service.startForeground() not allowed due to bg restriction: service ga.asti.android/github.daneren2005.dsub.service.DownloadService,请问这是否是同一问题?为何未触发崩溃?
我了解有很多关于修复该问题的指南,但我希望先复现问题,以验证修复方案是否有效。
内容的提问来源于stack exchange,提问作者Dan Gravell
相关产品推荐
相关产品推荐

