Search code examples
androidsharedpreferencesandroid-intentservice

Android - Access SharedPreferences once application is stopped/destroyed


I implementing notifications together with a periodical alarm and on IntentService i need to validate some values on SharedPreferences to decide if I will show a notifications or not.

When the application is on pause i have context, and everything goes ok, the problem comes when i destroy(remove from "recent apps" list) my application. In this case, the alarm is still running (which is ok), but when it tries to load my shared preferences gives me NullPointerException.

IntentService:

public class MyIntentService extends IntentService {

    private final PreferencesManager prefs;

    public SchedulingService() {
        super("MyIntentService");
        prefs = PreferencesManager.getInstance(this); //Error here
    }

    @Override
    protected void onHandleIntent(Intent intent) {
       // Do some checking with prefs variable ...
    }
}

SharedPreferences

public class PreferencesManager {

    public static final String SHARED_PREFERENCES_NAME = "PREFERENCES_PROJECT";
    private static PreferencesManager preferencesManager = null;
    private SharedPreferences sharedPreferences;

    private PreferencesManager(Context context) {
        sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    }

    public static PreferencesManager getInstance(Context context) {
        if (preferencesManager == null) {
            preferencesManager = new PreferencesManager(context);
        }
        return preferencesManager;
    }

    //....
}

How can retrieve the values from my PreferencesManager when the application is not running?


Solution

  • Move your prefs = PreferencesManager.getInstance(this) line to onHandleIntent(), or into an onCreate() method after the super.onCreate() call.

    why dont i have context on constructor?

    You do have a Context. It is not fully initialized yet. Never attempt to use a Context before the inherited onCreate() of the relevant component has completed. In this case, the component is a Service, so once super.onCreate() is over, then it is safe to use the Service to retrieve a SharedPreferences object.