Domanda

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!

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top