Altaiir
Altaiir

Reputation: 487

Restarting android service the good way

I implemented a foreground service which is working fine for now, the service is loading shared preferences to work with. Now when user changes these parameters and apply them, i have to restart the service so it can load the new changes from preferences.

My service is started/stopped from a switch , to restart it i am using :

@Override
public void onSettingsInteraction() {
    if(pService.isRunning()){
        pServiceSwitch.performClick();
        pServiceSwitch.performClick();
    }
}

The callback is listening for settings fragment interaction; now my question is ; should i set a small delay between the two calls or leave them as they are ? i'm afraid the two calls happen too fast and the service stops without starting again.

Upvotes: 0

Views: 40

Answers (1)

David Wasser
David Wasser

Reputation: 95568

Alternative: Instead of stopping and starting your Service, why don't you just call startService() with an Intent containing an "extra" that indicates the Service should reload the parameters. The Service gets the Intent in onStartCommand() and it can then reinitialize itself.

Upvotes: 1

Related Questions