一.SharedPreferences工具类

一.需要在application注册

public class MyApplication extends Application {
    /** * 应用实例 **/
    private static MyApplication instance;
    private static Context context;
    private static Handler myHandler;
    private static int myTid;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        context = this;
        myHandler = new Handler();
    }
    public static int getMyTid() {
        return myTid;
    }
    public static Handler getMyHandler() {
        return myHandler;
    }
    public static Context getContext() {
        return context;
    }
}

二.写工具类

public class SharedPreferencesUtil {
    //声明Sharedpreferenced对象
    private static SharedPreferences msp;
    private SharedPreferencesUtil() {}
    private static final SharedPreferencesUtil single = new SharedPreferencesUtil();
    //静态工厂方法
    public static SharedPreferencesUtil getInstance() {
        return single;
    }
    /** * 初始化sp存储 */
    private static void initShared(){
        if(null == msp){
            msp = BleApplication.getContext().getSharedPreferences("MyShared", Context.MODE_PRIVATE);
        }
    }
    public static void runOnUiThread(Runnable runnable){
        if(Process.myTid() == BleApplication.getMyTid()){
            runnable.run();
        }else{
            BleApplication.getMyHandler().post(runnable);
        }
    }
    // 存储字符串
    public static void setSharedString(String key,String value){
        initShared();
        boolean commit = msp.edit().putString(key, value).commit();
    }
    // 存储boolean
    public static void setSharedBoolean(String key,boolean value){
        initShared();
        boolean commit = msp.edit().putBoolean(key, value).commit();
    }
    // 存储int
    public static void setSharedInt(String key,int value) {
        initShared();
        boolean commit = msp.edit().putInt(key, value).commit();
    }
    // 获取字符串
    public static String getStringValue(String key){
        initShared();
        return msp.getString(key,"isNull");
    }
    // 获取boolean
    public static boolean getBooleanValue(String key){
        initShared();
        return msp.getBoolean(key,false);
    }
    // 获取int
    public static int getIntValue(String key){
        initShared();
        return msp.getInt(key,-1);
    }
    public static void backLogin(){
        initShared();
        msp.edit().clear().commit();
    }
}
    原文作者:I_do_
    原文地址: https://blog.csdn.net/shitou0/article/details/81100299
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞