Android8.0 Settings数据库监听的一个通用工具类

当Settings数据库某个字段的值发生变化,要监听怎么办,就用下面这个类。我是从qs settigns中发现的。

        /** Helper for managing a global setting. **/   
                public abstract class GlobalSetting extends ContentObserver implements Listenable { 
                    private final Context mContext; 
                    private final String mSettingName;  

                    protected abstract void handleValueChanged(int value);  

                    public GlobalSetting(Context context, Handler handler, String settingName) {    
                        super(handler); 
                        mContext = context; 
                        mSettingName = settingName; 
                    }   

                    public int getValue() { 
                        return Global.getInt(mContext.getContentResolver(), mSettingName, 0);   
                    }   

                    public void setValue(int value) {   
                        Global.putInt(mContext.getContentResolver(), mSettingName, value);  
                    }   

                    @Override
                    public void setListening(boolean listening) {
                        if (listening) {
                            mContext.getContentResolver().registerContentObserver(Global.getUriFor(mSettingName)
, false, this); 198
                        } else {    
                            mContext.getContentResolver().unregisterContentObserver(this);
                        }   
                    }   

                    @Override
                    public void onChange(boolean selfChange) {
                        handleValueChanged(getValue()); 
                    }
                }

                /** Common interface for components with an active listening state. **/
                public interface Listenable {
                    void setListening(boolean listening);   
                }

这么用

        Looper looper = this.getPrefContext().getMainLooper();  
                    mHandler = new Handler(looper); 
                    mSetting = new GlobalSetting(this.getPrefContext(), mHandler, Global.xxx) {
                    //global.xxx就是要监听的字段
                        @Override   
                        protected void handleValueChanged(int value) {
                            //value就是监听的值
                                }   
                            }   

                        }   
                    };  

mSetting.setListening(true);    

mSetting.setListening(true);就是设置监听,不需要的时候就设false.

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页