2
\$\begingroup\$

I was wondering wether my implementation of the PreferenceService below is thread safe or could cause memory leaks.

Android Studio gives me the warning "Do not place Android context classes in static fields". But since this warning is known to show in some cases where it does not really apply I am not sure if this is actually one of those cases. Replacing this._context = context; with this._context = context.getApplicationContext(); removes the warning...

Is there anything else that should stop me from using this in my release build?

package my.package.service;

// Android
import android.content.Context;
import android.content.SharedPreferences;

// Android X
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;

// Internal dependencies
import my.package.R;


public class PreferenceService
{
    /* SINGLETON */

    private static PreferenceService instance;


    /* ATTRIBUTES */

    private Context _context;
    private SharedPreferences _preferences;


    /* LIFECYCLE */

    /**
     * TODO
     * @param context
     */
    private PreferenceService(@NonNull Context context)
    {
        this._context = context;
        this._preferences = PreferenceManager.getDefaultSharedPreferences(this._context);
    }

    /**
     * TODO
     * @return
     */
    @NonNull
    public static synchronized PreferenceService create(@NonNull Context context)
    {
        if(PreferenceService.instance == null)
        {
            PreferenceService.instance = new PreferenceService(context);
        }

        return PreferenceService.instance;
    }

    /**
     * TODO
     * @return
    */
    @NonNull
    public static PreferenceService use()
    {
        if(PreferenceService.instance != null)
        {
           return PreferenceService.instance;
        }
        else throw new IllegalStateException("PreferenceService must be created before usage.");
    }


    /* GETTER & SETTER */

    /**
     * TODO
     * @return
     */
    public boolean getNightModePreference()
    {
        return this._preferences.getBoolean(this._context.getString(R.string.preference_key_night_mode), false);
    }

    /**
     * TODO
     * @param newNightModePreferenceValue
     * @return
     */
    public void setNightModePreference(boolean newNightModePreferenceValue)
    {
        this._preferences.edit().putBoolean(this._context.getString(R.string.preference_key_night_mode), newNightModePreferenceValue).apply();
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.