2

i have troubles with my STICKY Service. I call it in my MainActivity.class and bind it:

MainActivity:

Intent intent = new Intent(this, MyService.class);
ComponentName MyCompName= startService(intent);
bindService(intent, MyConnection, Context.BIND_AUTO_CREATE);

and...

MyService

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    return START_STICKY;
}

I want that this Service runs STICKY and never be closed or restarted. But when i close my Application, the onCreate()-Method of MyService is called and all variables are reseted, and i don´t know why.

BTW: I don´t call stopService!

1

1 Answer 1

4

The difference between STICKY and NON_STICKY services is that STICKY services are restarted after being killed. I don't think it's possible to guarantee that your service will never be restarted - if memory is low it might be restarted.

If you need to preserve the state, you can save variables in a database. To see if the service is being created for the first time or restarted, you can check if the intent in onStartCommand is null.

If you only need to preserve the initial state when the service was created, you can use START_REDELIVER_INTENT which will resend the Intent used to create the service in onStartCommand.

4
  • But when should i save the current state of the service in the database, because the onDestroy()-Method of MyService is never called? Commented Nov 19, 2013 at 14:41
  • If the state data doesn't change too often, you could save it whenever it changes.
    – slamnjam
    Commented Nov 19, 2013 at 15:52
  • Ok, but i have trobles by reloading the state from database. Because when i check in onStartCommand if the intent is null, and then i call LoadState() (which loads the data from db), the state could not be loaded because the database isn´t available at this time. The Binding of the database need more time Commented Nov 21, 2013 at 21:29
  • Ok, finally i do this when the db is connected and not in onStartCommand. Commented Nov 21, 2013 at 21:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.