2

I am continuing to see a lot of crashes in the wild for this, despite the fact that I am in fact calling startForeground.

For reference, my code is below:

In my app's main activity onCreate, the very last thing I do is:

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

And then in 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);
    }
}

When I run this on my Android it runs fine, the service starts, etc. And for most of my users it runs fine. But I'm getting a lot of android.app.RemoteServiceException reports from users - a few dozen a day.

There's a maximum 5 second ANR gap between startForegroundService and startForeground, and I assume that's what's causing the issue (and why it's intermittent), but I can't figure out what all could be happening between onCreate in the app's activity and onCreate in the service. Is it possible that the creation of the notification is slow on some devices? Any techniques/suggestions for minimizing the time here? Should I be calling startForegroundService later than onCreate?

0 Answers0