In my Android app, I record a lot of things like GPS, barometric pressure, Bluetooth sensors. There is a "super" service which is started in the foreground:

Intent intent = new Intent(context, DataCollectorService.class);
ContextCompat.startForegroundService(context, intent);

The service itself has to start numerous child services like GPS-recording, Bluetooth sensor recording and the like. And the service creates a notification:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // . . . 
    Notification notification = new NotificationCompat.Builder(this, channelId)
            // . . .
            .build();

    startForeground(NOTIFICATION_ID, notification);

    mHandler.postDelayed(this::startChildServices, 100);
    return START_STICKY;
}

private void startChildServices() {
    // . . .
    if (gpsEnabled) {
        Intent intent = new Intent(this, GpsTrackingService.class);
        bindService(intent, mGpsServiceConnection, Context.BIND_AUTO_CREATE);
        startService(intent);
    }
    if (isPressureEnabled) {
        Intent intent = new Intent(this, PressureService.class);
        bindService(intent, pressureConnection, Context.BIND_AUTO_CREATE);
        startService(intent);
    }
    // . . .
}

All works well, but a very small percentage of the users encounter crashes like this:

android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground()

Actually, I start the "super" service in the foreground, as you can see.

Do I have to start the child services in the foreground as well?

Obviously, I don't want to have 3-7 notification icons in the users status bar.

0 Answers