致命异常:android.app.ForegroundServiceStartNotAllowedException 即使应用程序不在后台

发布于 2025-01-10 07:38:55 字数 991 浏览 0 评论 0原文

我在 MainActivity 上有这段代码,它在应用程序恢复时启动前台服务。


private final Handler handler = new Handler();

private final Runnable runnable = () -> {
    Intent intent = new Intent(this, MyService.class);
    ContextCompat.startForegroundService(this, intent);
    bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);
};

private class AppLifecycleListener implements DefaultLifecycleObserver {
    @Override
    public void onResume(LifecycleOwner owner) { // app moved to foreground
        handler.postDelayed(runnable, 1000);
    }
}

我尝试在 onResume 中没有 handler.postDelayed 和 runnable 的情况下解决此错误,只需在 onResume 内运行 Runnable 内的代码,但我什至得到了 更多 ForegroundServiceStartNotAllowedException 崩溃。

如果我们无法再在后台启动前台服务(自 Android API 32 起),我的方法有什么问题?换句话说,当用户打开应用程序后需要立即启动前台服务时,如何避免此异常? (如果没有 WorkManager 也可以)

使用的依赖项:

implementation 'androidx.lifecycle:lifecycle-process:2.4.1'

I have this piece of code on MainActivity that starts a foreground service when the app is resumed.


private final Handler handler = new Handler();

private final Runnable runnable = () -> {
    Intent intent = new Intent(this, MyService.class);
    ContextCompat.startForegroundService(this, intent);
    bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);
};

private class AppLifecycleListener implements DefaultLifecycleObserver {
    @Override
    public void onResume(LifecycleOwner owner) { // app moved to foreground
        handler.postDelayed(runnable, 1000);
    }
}

I have tried to solve this error without the handler.postDelayed and runnable in onResume, just by running the code inside Runnable inside onResume, but I've got even
more ForegroundServiceStartNotAllowedException crashes.

If we cannot start foreground services on background anymore (since Android API 32), what is the problem with my approach ? In other words, how to avoid this exception when it is needed to start a foreground service right after user opens the app ? (and if it's possible without WorkManager)

Dependency used:

implementation 'androidx.lifecycle:lifecycle-process:2.4.1'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文