Settings.System.putXXX数据变化,ContentObserver监听

    用Settings来保存数据简单易用,app把数据保存到Settings的数据库里面,在另外一个app访问该数据库的数据,到达应用共享数据的效果。如果能实时监听到数据的变化就更加完美,



比如要监听安全辅助功能的开关状态

private static abstract class SettingsContentObserver extends ContentObserver {

        public SettingsContentObserver(Handler handler) {
            super(handler);
        }

        public void register(ContentResolver contentResolver) {
            contentResolver.registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.ACCESSIBILITY_ENABLED), false, this);
            contentResolver.registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES), false, this);
        }

        public void unregister(ContentResolver contentResolver) {
            contentResolver.unregisterContentObserver(this);
        }

        @Override
        public abstract void onChange(boolean selfChange, Uri uri);
    }
}


实例化一个SettingsContentObserver对象

private final SettingsContentObserver mSettingsContentObserver = new SettingsContentObserver(new Handler()) {
       @Override
       public void onChange(boolean selfChange, Uri uri) {
             String settingValue = Settings.Secure.getString(getContentResolver(),Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
             final boolean enabled = settingValue.contains(mComponentName.flattenToString());
             mToggleSwitch.setCheckedInternal(enabled);
       }
};


注册ContentObserver

mSettingsContentObserver.register(getContentResolver());

你可能感兴趣的:(android)