gpt4 book ai didi

安卓 9.0 : Not allowed to start service: app is in background. 。在 onResume() 之后

转载 作者:IT王子 更新时间:2023-10-28 23:39:28 24 4
gpt4 key购买 nike

我有一个音乐播放器,它试图在 ActivityonResume() 中启动 Service。为了清楚起见,我删除了几行,但代码是有效的:

@Override
protected void onResume() {
super.onResume();

startService(new Intent(this, MusicService.class));
}

根据崩溃日志,这会在一些运行 Android P 的设备上引发异常:

Caused by java.lang.IllegalStateException: Not allowed to start service Intent { cmp=another.music.player/com.simplecity.amp_library.playback.MusicService }: app is in background uid UidRecord{6a4a9c6 u0a143 TPSL bg:+3m25s199ms idle change:cached procs:1 seq(1283,1283,1283)}
at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1577)
at android.app.ContextImpl.startService(ContextImpl.java:1532)
at android.content.ContextWrapper.startService(ContextWrapper.java:664)
at android.content.ContextWrapper.startService(ContextWrapper.java:664)
at com.simplecity.amp_library.utils.MusicServiceConnectionUtils.bindToService(SourceFile:36)
at com.simplecity.amp_library.ui.activities.BaseActivity.bindService(SourceFile:129)
at com.simplecity.amp_library.ui.activities.BaseActivity.onResume(SourceFile:96)

我的应用怎么可能在调用 onResume()(和 super.onResume())之后立即在后台运行?

这对我来说没有任何意义。这可能是平台错误吗?受此崩溃影响的所有 3500 多名用户均使用 Android P。

最佳答案

Google 提供了一种解决方法:

The issue has been addressed in future Android release.

There is a workaround to avoid application crash. Applications can get the process state in Activity.onResume() by calling ActivityManager.getRunningAppProcesses() and avoid starting Service if the importance level is lower than ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND. If the device hasn’t fully awake, activities would be paused immediately and eventually be resumed again after its fully awake.

所以我认为应该是这样的:

// hack for https://issuetracker.google.com/issues/113122354
List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
if (runningAppProcesses != null) {
int importance = runningAppProcesses.get(0).importance;
// higher importance has lower number (?)
if (importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)
URLPlayerService.startActionBroadcastServiceData(PlayerActivity.this);
}

我使用处理程序作为解决方法,它工作得很好,但不是 100%:

// hack for https://issuetracker.google.com/issues/113122354
handler.postDelayed(() -> URLPlayerService.startService(PlayerActivity.this),200);

关于安卓 9.0 : Not allowed to start service: app is in background. 。在 onResume() 之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52013545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com