SharedPreferencesHelper.java
2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package com.cnlive.goldenline.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.Set;
/**
* Created by zuoxian on 15/9/7.
*/
public class SharedPreferencesHelper {
private static final String APP_NAME = "com.cnlive.goldenline";
public static SharedPreferencesHelper instance;
protected Context mContext;
protected SharedPreferences sharedPreferences;
public SharedPreferencesHelper(Context context) {
mContext = context;
sharedPreferences = mContext.getSharedPreferences(APP_NAME, 0);
}
/**
* 线程安全调用
*
* @param context
* @return
*/
public static synchronized SharedPreferencesHelper getInstance(@NonNull Context context) {
if (null == instance)
instance = new SharedPreferencesHelper(context.getApplicationContext());
return instance;
}
@Nullable
public String getValue(String key) {
return sharedPreferences.getString(key, "");
}
public Boolean getBoolValue(String key) {
return sharedPreferences.getBoolean(key, false);
}
public Boolean getBoolean(String key, boolean defaultValue) {
return sharedPreferences.getBoolean(key, defaultValue);
}
public int getIntValue(String key) {
return sharedPreferences.getInt(key, 0);
}
public void setValue(String key, Boolean value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.apply();
}
public void setValue(String key, String value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.apply();
}
public void setValue(String key, int value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.apply();
}
public void setValue(String key, long value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putLong(key, value);
editor.apply();
}
public Long getLong(String key){
return sharedPreferences.getLong(key,0);
}
public void remove(String key) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove(key);
editor.apply();
}
public void clear() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}
@NonNull
public Set<String> getSaveKeys() {
return sharedPreferences.getAll().keySet();
}
}