如何实现SettingsObserver extends ContentObserver 来监听Settings设值变化

如何实现SettingsObserver extends ContentObserver 来监听Settings设值变化

关于如何在Settings中添加自己的值在之前如何在setting里面添加自己的值中说过,现在来说如何监听监听Settings设值变化。

首先可以新建一个内部类SettingsObserver来继承自ContentObserver

    private final class SettingsObserver extends ContentObserver {
    private final Uri FREE_URI = Settings.System.getUriFor("free_uri");

    private SettingsObserver() {
        super(mHandler);
    }

    public void register() {
        mContext.getContentResolver().registerContentObserver(FREE_URI, true, new ContentObserver(mHandler) {
            @Override
            public boolean deliverSelfNotifications() {
                return super.deliverSelfNotifications();
            }

            @Override
            public void onChange(boolean selfChange) {
                super.onChange(selfChange);
            }

            @Override
            public void onChange(boolean selfChange, Uri uri) {
                super.onChange(selfChange, uri);
                mHandler.sendEmptyMessage(2);
            }
        });
    }

    public void unregister() {
        mContext.getContentResolver().unregisterContentObserver(this);
    }

    @Override
    public void onChange(boolean selfChange, Uri uri) {
        super.onChange(selfChange, uri);
        if (SMART_URI.equals(uri)) {
            mHandler.sendEmptyMessage(1);
        }else if (FREE_URI.equals(uri)){
            mHandler.sendEmptyMessage(2);
        }
    }
}

这样在FREE_URI值变化时就可以监听到
当然你同样需要在,函数的初始化方法中先注册,在结束方法中注销

private SettingsObserver mSettingsObserver = new SettingsObserver();




public void init(Context context) {
    if (mSettingsObserver != null) {
        mSettingsObserver.register();
       }
    }

public void release() {
    if (mSettingsObserver != null) {
        mSettingsObserver.unregister();
       }
    }

你可能感兴趣的:(技术总结)