android界面或公共参数怎么保存呢,
使用Config
是key->value简单的保存方案。支持任意类型。
收录代码Config.java:
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.LruCache;
import java.io.Serializable;
public class Config {
private static int M = 1024 * 1024;
private volatile static Config mConfig;
private static LruCache<String, Object> mLruCache = new LruCache<>(1 * M);
public Config(Context context){}
public static Config init(Context context) {
if (null == mConfig) {
synchronized (Config.class) {
if (null == mConfig) {
mConfig = new Config(context);
}
}
}
return mConfig;
}
public static Config getSingleInstance() {
return mConfig;
}
//--- 基础 -----------------------------------------------------------------------------------
public <T extends Serializable> void saveData(@NonNull String key, @NonNull T value) {
mLruCache.put(key, value);
}
public <T extends Serializable> T getData(@NonNull String key, @Nullable T defaultValue) {
T result = (T) mLruCache.get(key);
if (result != null) {
return result;
}
return defaultValue;
}
//--下面要看情况了,写一些要记录的信息
//--方式如:private static Key_something="something";
//--类型看情况,这里用string了。参数也看清况,这里用一个Integer吧
//---------- publlic String saveSomething(Integer position){
// savaData(something,position);
// }
//--然后是获取了,看情况传不传参,getData第二个参数是默认的,看情况
//-----------public Integer getSomething(){
// return getData(Key_something,0)
// }
}
调用方式:
private Config cfg; cfg=new Config(mcontext); 以CheckBox为例
CheckBox chkbox1 = findViewById(R.id.chkbox1);
chkbox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
cfg.saveData("chkbox1",isChecked);
}
});
读取时
cfg.getData("chkbox1",false)
就是这么简单。
但是这种不支持跨App,比如xposed
跨不同包,建议使用websocket方案读写。