Android: service restart after changing settings

I have a service and a preference function that allows the user to edit some settings. I would like to restart the service as soon as the user is created using the PreferenceActivity function.

I understand that I can register onChange listeners for individual preference changes, but I do not want to restart the Service as each preference changes. I would like to do this when the user edits all the settings. Without the Apply Now button in the PreferenceActivity, I don’t see a direct way to do this.

Did I miss something fundamental here?

Thank!

+3
source share
2 answers

In Activitywhich launches PreferenceActivity, use startActivityForResultand onActivityResultto track when the user has completed PreferenceActivityand restarted the service there.

eg.

Wherever you start PreferenceActivity:

Intent prefIntent = new Intent(this, MyPreferenceActivity.class);
startActivityForResult(prefIntent, PREFS_UPDATED);

later in the same Activity:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (resultCode) {
        case PREFS_UPDATED:
            // restart service
            break;
        ...
    }
}
+3
source

Another alternative is to override onStart () in your PreferenceActivity to write "before" values ​​and override it onStop () to check for any deltas so that they can be processed right away, for example.

@Override
protected void onStart() {
    super.onStart();
    // save current state into data member(s) for comparison later
    mShouldNotify = getApp().getSettings().getBoolean(PrefsActivity.PREF_SHOW_NOTIFICATIONS, true);           
}

@Override
protected void onStop() {
    super.onStop();

    if (mShouldNotify != getApp().getSettings().getBoolean(PrefsActivity.PREF_SHOW_NOTIFICATIONS, true)) {
        // we changed notifcation status.  Tell google.
        getApp().updateGooglePushRegistration();
    } 
}
+1
source

Source: https://habr.com/ru/post/1767695/


All Articles