你是否想过这么愉快的使用SharedPrefrence

来一个属于程序猿的打招呼方式:
public class ConfigManager {
    private int mPwdLength;
    private boolean mIsAutoLogin;
    private boolean mIsFinishGuide;
    private Context mContext;

    private ConfigManager() {
        mContext = BaseApplication.getContext();
        mIsAutoLogin = getBoolean(IS_AUTO_LOGIN);
        mIsFinishGuide = getBoolean(IS_FINISH_GUIDE);
        mPwdLength = SpfUtils.getInt(mContext, LENGTH, 0);
    }
   
    private static ConfigManager singleInstance = new ConfigManager();

    public static ConfigManager getInstance() {
        return singleInstance;
    }

    private boolean getBoolean(String key) {
        return SpfUtils.getBoolean(mContext, key,false);
    }

    private boolean getBoolean(String key, boolean defaultValue) {
        return SpfUtils.getBoolean(mContext, key, defaultValue);
    }

    public int getPwdLength() {
        return mPwdLength;
    }

    public void setPwdLength(int pwdLength) {
        mPwdLength = pwdLength;
        SpfUtils.putInt(mContext, LENGTH, pwdLength);
    }

    public boolean isAutoLogin() {
        return mIsAutoLogin;
    }

    public void setAutoLogin(boolean autoLogin) {
        mIsAutoLogin = autoLogin;
        SpfUtils.putBoolean(mContext, IS_AUTO_LOGIN, autoLogin);
    }

     public boolean isFinishGuide() {
        return mIsFinishGuide;
    }

     public void setFinishGuide(boolean finishGuide) {
        mIsFinishGuide = finishGuide;
        SpfUtils.putBoolean(mContext, IS_FINISH_GUIDE, finishGuide);
    }
}

看到这么密集的代码,估计有人想报警了(看个博客都不能安生,就不能让我愉快的阅读,远离代码几分钟?心理暗暗的骂道。)
大兄弟,不要急!贴代码就是为了证明我不是在吹B,你再忍一忍!
牛B的你肯定已经看出来了,这里只是对日常我们操作SP的一个封装。经常使用SP的童鞋肯定有写错key的经历,别环顾左右了,说的就是你。
还有另外的一个好处是,只管调方法取你想要的值,完全不用关心是不是有哪个冒失鬼修改了里面的值。
对,就是这么任性。
这里写的都是一些设置里的配置参数,没有考虑并发的情况

吹完了优点总得出来溜一溜吧:

来一段熟悉的代码

    if (ConfigManager.getInstance().isFinishGuide()) {
            startActivity(new Intent(this, MainActivity.class));
            finish();
     }

设置?

ConfigManager.getInstance().setAutoLogin(isChecked);

AndroidStudio那么强大的代码提示功能怎么能闲着
这个没有什么酷炫到爆的功能,但是能让工作更便利,你觉得呢?

    原文作者:Gersy
    原文地址: https://www.jianshu.com/p/c9fa8ed06665
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞