【问题标题】:startForeground() in onCreate() vs onStartCommand()onCreate() 中的 startForeground() 与 onStartCommand()
【发布时间】:2019-02-15 07:46:49
【问题描述】:

我遇到了从 Playstore 报告的大量异常。 来自 Android P 的 RemoteServiceException。

我正在创建 android 前台服务,然后调用 startForegound(with channel)。

但 99.9% 只有 9.0(android P) 用户报告 RemoteServiceException。 我检查了我是否为该服务制作通知渠道。 我还检查了我是否在 OREO 之后为 os 调用 startForegroundService。

每个代码都没有问题。

但我发现我多次调用startForegroundService(),但Service的onCreate()在第一次创建时只调用了一次。 所以 onCreate() 内部的 startForeground() 只被调用一次。

但是,如果我将 startForeground() 放在 onStartCommand() 中,那么它也会像我调用 startForegroundService() 一样多次调用。 因为每当您调用 startService/startForegroundService 时也会调用它(即使 Service 的实例已经创建)。

你认为这是异常的原因吗?

还有mboy对https://stackoverflow.com/a/51251741/5343的评论 也说了类似的话。

【问题讨论】:

    标签: android android-9.0-pie foreground-service remoteserviceexception


    【解决方案1】:

    您可以在onStartCommand() 中调用startForeground() 之前尝试此代码块

    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NotifyManagerUtils.getNotificationDefaultChannelId());
            builder.setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.drawable.app_icon);
            startForeground(YOUR_ID, builder.build());
        }
    } catch (Exception e) {
        if (DEBUG) {
            Log.e(TAG, e.getMessage());
        }
    }
    

    如果您startService()/startForegroundService() 多次调用,您应该在服务onCreate() 中了解更多信息,但onStartCommand() 将与您调用的次数一样运行,所以我认为如果此服务,您应该为您的服务添加检查活着所以不要打电话startForeground()也许可以解决这个问题。

    同样的问题请查看this

    【讨论】:

      【解决方案2】:

      同样的问题。 就我而言,当我更改 id 时,似乎可以解决这个问题。

      之前

      startForeground(1, notification);
      

      之后

      startForeground(100001, notification);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-22
        • 2012-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多