-2

Foreground service stopping in some mobiles when app destroyed, want to run foreground service even app destoryed.

Manifest :

<service android:name=".services.LocationService" />

Here is how i am starting and stopping service :

private void startLocationUpdates() {
    if (!isMyServiceRunning(LocationService.class)) {

        Intent locationServiceIntent = new Intent(this, LocationService.class);
        locationServiceIntent.putExtra(StringConstants.LOCATION_UPDATES, true);

        startService(locationServiceIntent);
    }
}

private void stopLocationUpdates() {
    Intent locationServiceIntent = new Intent(this, LocationService.class);
    locationServiceIntent.putExtra(StringConstants.LOCATION_UPDATES, false);

    startService(locationServiceIntent);
}

Service :

public class LocationService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(TAG, "Service started");
    if (intent != null) {
      if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForeground(1, notification);

      } else {

        startService(new Intent(getApplicationContext(), MyForeGroundService.class));

    }
    }
    return START_STICKY;

} }

private NotificationCompat.Builder getNotificationBuilder(){
    return new NotificationCompat.Builder(this)
            .setContentIntent(MyApp.pendingIntent)
            .setContentText("setContentText")
            .setContentTitle(getString(R.string.app_name))
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_arrow_back_black_24px))
            .setSmallIcon(R.drawable.ic_arrow_back_black_24px);
}

1 Answers1

0

for devices having OS Oreo and above there is a limitation in running service , you have to show a notification for devices having Oreo and above ,you have to do one more thing instead of startService() try using startForegroundService() for more info please go through the official doc https://developer.android.com/about/versions/oreo/background

Sujeet Kumar
  • 256
  • 1
  • 11