0

I have an app with a service. This service should be started if the smartphone is rebooted. Anyway if the app was started during the switch off or not. And the app should be restarted (or still running) if the app is swiped away (killed). This work on my Smartphone with Android 4.2, but doesn't work on a Smartphone with Android 5.1.

I start my service in a class, derived from BroadcastReceiver:

@Override
public void onReceive(Context oContext, Intent oIntent)
{
  if (oIntent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
    Intent oNewIntent = new Intent(oContext, CarFinderService.class);
    // class can be anything which you want to start on bootup...
    oNewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    oContext.startService(oNewIntent);
  }
}

This works on Android 4.2., but not on Android 5.1. I thins this code is OK. Or not?

What can I do that a service is started on reboot or if the app is swiped away?

I tried different things, found via searching the web. But I found a solution who works on Android 5.1.

Any hints?

Thanks Hans

Nisarg
  • 1,358
  • 14
  • 30
Hans
  • 43
  • 3

1 Answers1

0

Add this to you manifest for 5.1 :

<action android:name="android.intent.action.QUICKBOOT_POWERON" />

To bring service back to live put this inside your service :

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

The money is in the START_STICKY.

Nir Duan
  • 6,164
  • 4
  • 24
  • 38
  • Hi I use START_STICKY. But this doesn't work. I Also use QUICKBOOT_POWERON, no success. – Hans Jul 26 '16 at 14:54
  • What I need: i use a service who runs in the background. Even if the app is swiped away or the samrtphone is rebooted. Acutally if I swipe away the app, the service is killed and will not be restarted. Also with START_STICKY. It works great on Android 4.2. The same with the case described above. It works with Android 4.2, not with Android 5.1. I am looking for a solution the whole day, but nothing works like expected. I tried thins with onTaskRemoved and so on, no success. – Hans Jul 26 '16 at 14:57
  • Did you consider startForeground()? – Nir Duan Jul 26 '16 at 15:52
  • Until now not, no. – Hans Jul 27 '16 at 12:31