Android社交App開發之SharedPreferences工具類

package com.hongx.framework.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.hongx.framework.BuildConfig;

/**
 * FileName: SpUtils
 * SharedPreferences工具類
 */
public class SpUtils {

    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    /**
     * key - values 存儲方式
     * 它的存儲路徑:data/data/packageName/shared_prefs/sp_name.xml
     * <p>
     * File存儲:/sdcard/ 讀寫方式不一樣
     * 數據庫:LitePal
     * get/post:數據的讀寫
     */

    private volatile static SpUtils mInstance = null;

    private SpUtils() {

    }

    public static SpUtils getInstance() {
        if (mInstance == null) {
            synchronized (SpUtils.class) {
                if (mInstance == null) {
                    mInstance = new SpUtils();
                }
            }
        }
        return mInstance;
    }

    public void initSp(Context mContext) {
        /**
         * MODE_PRIVATE:只限於本應用讀寫
         * MODE_WORLD_READABLE:支持其他應用讀,但是不能寫
         * MODE_WORLD_WRITEABLE:其他應用可以寫
         */
        sp = mContext.getSharedPreferences(BuildConfig.SP_NAME, Context.MODE_PRIVATE);
        editor = sp.edit();
    }

    public void putInt(String key, int values) {
        editor.putInt(key, values);
        editor.commit();
    }

    public int getInt(String key, int defValues) {
        return sp.getInt(key, defValues);
    }

    public void putString(String key, String values) {
        editor.putString(key, values);
        editor.commit();
    }

    public String getString(String key, String defValues) {
        return sp.getString(key, defValues);
    }

    public void putBoolean(String key, boolean values) {
        editor.putBoolean(key, values);
        editor.commit();
    }

    public boolean getBoolean(String key, boolean defValues) {
        return sp.getBoolean(key, defValues);
    }

    public void deleteKey(String key) {
        editor.remove(key);
        editor.commit();
    }

}

應用啓動頁中使用:

//1.判斷App是否第一次啓動 install - first run
        boolean isFirstApp = SpUtils.getInstance().getBoolean(Constants.SP_IS_FIRST_APP, true);
        Intent intent = new Intent();
        if (isFirstApp) {
            //跳轉到引導頁
            intent.setClass(this, GuideActivity.class);
            //非第一次啓動
            SpUtils.getInstance().putBoolean(Constants.SP_IS_FIRST_APP, false);
        } else {
			...
		}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章