1.Application
public class AppApplication extends Application {
private static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
public static Context getContext() {
return context;
}
}
2.单例PreferencesUtils
public class PreferencesUtils {
private SharedPreferences share;
private SharedPreferences.Editor editor;
private String SHARED_NAME = "appshare";
private PreferencesUtils() {
share = AppApplication.getContext().getSharedPreferences(SHARED_NAME, Context.MODE_PRIVATE);
editor = share.edit();
}
private static class PreferencesUtilHolders {
private static PreferencesUtils INSTANCE = new PreferencesUtils();
}
public static PreferencesUtils getInstance() {
return PreferencesUtilHolders.INSTANCE;
}
public boolean putString(String key, String value) {
editor.putString(key, value);
return editor.commit();
}
public String getString(String key) {
return share.getString(key, null);
}
public String getString(String key, String defaultValue) {
return share.getString(key, defaultValue);
}
public boolean putLong(String key, long value) {
editor.putLong(key, value);
return editor.commit();
}
public boolean putFloat(String key, float value) {
editor.putFloat(key, value);
return editor.commit();
}
public boolean putInt(String key, int value) {
editor.putInt(key, value);
return editor.commit();
}
public boolean putBoolean(String key, boolean value) {
editor.putBoolean(key, value);
return editor.commit();
}
public long getLong(String key) {
return share.getLong(key, -1);
}
public int getInt(String key, int defaultValue) {
return share.getInt(key, defaultValue);
}
public float getFloat(String key, float defaultValue) {
return share.getFloat(key, defaultValue);
}
public long getLong(String key, long defaultValue) {
return share.getLong(key, defaultValue);
}
public boolean getBoolean(String key, boolean defaultValue) {
return share.getBoolean(key, defaultValue);
}
public boolean removeSharedPreferenceByKey(String key) {
editor.remove(key);
return editor.commit();
}
}