gpt4 book ai didi

android - onCreate() 中的 startForeground() 与 onStartCommand()

转载 作者:行者123 更新时间:2023-12-02 11:21:07 35 4
gpt4 key购买 nike

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

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

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

每个代码都没有问题。

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

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

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

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

最佳答案

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

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());
}
}
您应该了解的更多信息服务 onCreate()如果你 startService()/startForegroundService() 只打过一次电话很多次,但 onStartCommand()将与您调用的时间一样运行,所以我认为您应该为您的服务添加一个检查,如果此服务还活着,所以不要调用 startForeground()也许可以解决这个问题。
相同问题请查看 this .

关于android - onCreate() 中的 startForeground() 与 onStartCommand(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54704686/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com