致命异常:android.app.ForegroundServiceStartNotAllowedException 即使应用程序不在后台
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论