我如何避免android.app.RemoteServiceException-Context.startForegroundService()然后没有调用Service.startForeground()

时间:2019-09-27 16:16:28

标签: java android oncreate android-gps

尽管事实上我实际上在打电话给startForeground,但我仍然继续在野外看到很多崩溃。

作为参考,我的代码如下:

在我应用的主要活动onCreate上,我要做的最后一件事是:

Intent i = new Intent(c, myGpsService.class);
if (Build.VERSION.SDK_INT >= 26)
    c.startForegroundService(i);
else
    c.startService(i);

然后在myGpsService中:

@Override
public void onCreate() {
    super.onCreate();
    startInForeground();
}

private void startInForeground() {
    if (Build.VERSION.SDK_INT >= 26) {
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel nc = new NotificationChannel(...);
        nc.enableLights(false);
        nc.enableVibration(false);
        if (nm != null)
            nm.createNotificationChannel(nc);
        Notification n = new Notification.Builder(this, nc.getId())
                .setContentText(...)
                .setContentTitle(...))
                .setSmallIcon(...)
                .build();
        this.startForeground(NOTIFICATION_ID, n);
    }
}

当我在Android上运行该程序时,它运行正常,该服务启动,依此类推。对于大多数用户而言,它运行良好。但是我从用户那里收到了很多android.app.RemoteServiceException报告-每天几十个。

startForegroundService和startForeground之间最多有5秒的ANR间隔,我认为这就是问题的根源(以及原因是间歇性的),但我无法弄清应用程序活动中的onCreate和onCreate之间可能发生的一切在服务中。在某些设备上,通知的创建是否可能很慢?有什么技巧/建议可以缩短此处的时间?我应该在onCreate之后调用startForegroundService吗?

0 个答案:

没有答案