【问题标题】:Start context.startService(intent) on Android Pie在 Android Pie 上启动 context.startService(intent)
【发布时间】:2018-09-18 09:59:17
【问题描述】:

我在我的 Activity 的 onResume 上启动了一项服务,它在 oreo 上运行良好,但最近我看到 Android P 的崩溃,上面写着“无法恢复 Activity...。不允许启动服务意图...应用程序是在后台......”。有没有人以前见过这个并且能够应用修复,任何输入将不胜感激。

@Override
public void onResume() {
    super.onResume();
    Timber.v("onResume");
    Intent intent = new Intent(context, Token.class);
    intent.setAction(ACTION_FETCH_TOKEN);
    context.startService(intent);
}

只是为了添加更多上下文,我自己无法重现崩溃。

【问题讨论】:

  • 包含您的代码。
  • 代码很简单
  • 受保护的无效 onResume() { super.onResume(); context.startService(intent); }
  • 编辑您的问题以包含代码。 intent 声明在哪里?
  • 看看这个问题和第一个答案:stackoverflow.com/questions/49961273/…

标签: android


【解决方案1】:

在 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);

【讨论】:

  • 这只会让应用程序崩溃。
  • 用更复杂的方式编辑,但它现在应该可以工作了。我认为通知不能为空。
  • 是的,但我不想显示通知,有趣的是我不明白为什么在 onResume 上,应用程序仍在后台,这没有任何意义。
  • @MohammedAbdulBari,奥利奥后。没有背景概念。但是你可以在前台运行它。你必须使用 context.startForegroundService(intent);正如军团所说。现在,如果您正在启动前台服务,那么您必须仅在 onCreate 方法中创建通知,并且在 onCreate 结束时您必须使用 startForeground(111, mBuilder.build());开始运行你的 onStartCommand。这些是没有任何借口的规则..!!如果您不想收到通知,这显然意味着您无法在 Oreo 后启动服务。就是这样。
  • @sandhyasasane 问题是我没有在后台启动服务,它是在 Activity 的 onResume 上启动的一次性服务,这意味着应用程序应该已经在前台,但由于某种原因它不是。此外,该应用程序不会在运行 Android 9 的像素上崩溃。
【解决方案2】:

我不想更改为 ForegroundService 的小型服务遇到了同样的问题。然后我发现谷歌为在 onResume 中启动服务提供了这个解决方法:

ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    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) {
            //start your service the same way you did before in here
            startService(serviceIntent);
        }
    }

该问题已在未来的 Android 版本中得到解决。

有一种解决方法可以避免应用程序崩溃。应用程序可以获得 通过调用 Activity.onResume() 中的进程状态 ActivityManager.getRunningAppProcesses() 并避免启动服务如果 重要性级别低于 ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND。如果 设备尚未完全唤醒,活动将立即暂停,并且 最终在完全清醒后再次恢复。

【讨论】:

  • 很高兴知道。能否分享一下源码。
猜你喜欢
  • 1970-01-01
  • 2012-02-27
  • 2020-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
  • 2016-08-20
相关资源
最近更新 更多