android - 在 Android Pie 上启动 context.startService(intent)

标签 android

我在 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/

相关文章:

Android - 从另一个 Activity 将对象添加到 ListView

安卓网络服务认证

android - 如何同时拖动两个 View

android - 当应用程序未运行时如何通知用户收到的 GTalk 聊天记录

javascript - Android Chrome 自定义选项卡 - 在新选项卡中打开链接 + Postmessage

android - 解析 XML XmlPullParser android

java - Android Studio 无法创建新项目

android - 模拟器不在按钮上显示图像单击android

android - 使用兼容性库时 setRetainInstance 不适用于 ListFragment

Android Studio 缺少初始分区文件 :