我在 Activity 的 onResume 上启动了一项服务,它在 oreo 上运行良好,但最近我看到 Android P 崩溃,显示“无法恢复 Activity...。不允许启动服务 Intent ...应用程序是在背景中……”。有没有人以前见过这个并且可以应用修复程序,我们将不胜感激。
@Override
public void onResume() {
super.onResume();
Timber.v("onResume");
Intent intent = new Intent(context, Token.class);
intent.setAction(ACTION_FETCH_TOKEN);
context.startService(intent);
}
只是为了添加更多上下文,我自己无法重现崩溃。
最佳答案
在 Oreo8+ 上,如果您的应用程序未“显示”,您将无法启动后台服务,为此您需要像下面这样编辑代码:
protected void onResume() {
super.onResume(); context.startForegroundService(intent);
}
在您的服务类的 onCreate() 方法中,您还需要添加:
*编辑* 2018-09-18 18:15
PendingIntent pIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("My App")
.setContentText("Doing some work...")
.setContentIntent(pIntent).build();
startForeground(1000, notification);
关于android - 在 Android Pie 上启动 context.startService(intent),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52383953/