应用场景:项目开发中,遇到有些参数,比如系统设置开关状态,需要保存起来,改变了需要通知其他应用,开机重启,要保存上一次的状态。
方案一:
直接用系统提供的接口
样例实现代码:
public static final String ADAYO_ChildrenLossSafeTip = "ChildrenLossSafeTip";
mContext = getContext();
Settings.System.getInt(mContext.getContentResolver(), ADAYO_ChildrenLossSafeTip, 0);//0 默认
注册监听变化接口
private void registerProvider() {
if (mContext != null) {
if(mContext.getContentResolver()!=null){
mContext.getContentResolver().registerContentObserver(Settings.System.getUriFor(ADAYO_ChildrenLossSafeTip), true, mChildrenLossSafeTipObserver);
}
}
}
注消监听变化接口
private void unRegisterProvider() {
if (mContext != null) {
if (mContext.getContentResolver() != null) {
mContext.getContentResolver().unregisterContentObserver(mChildrenLossSafeTipObserver);
}
}
}
监听变化接口
private ContentObserver mChildrenLossSafeTipObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
Context context = getContext();
if (!selfChange) {
if (context != null) {
int iChildrenLossSafeTip = Settings.System.getInt(context.getContentResolver(), ADAYO_ChildrenLossSafeTip, 0);
Log.d(TAG,"ChildrenLossSafeTipObserver_"+iChildrenLossSafeTip);
if (mTlChildrenLossSafeTip != null) {
switch (iChildrenLossSafeTip) {
case 1:
break;
case 0:
break;
}
}
}
}
}
};