Monitor Android system settings values

谁说胖子不能爱 提交于 2019-12-18 16:58:59

问题


I want to watch a system setting and get notified when its value changes. The Cursor class has a setNotificationUri method which sounded nice, but it doesn't work and coding it also feels strange... Thats what I did:

    // Create a content resolver and add a listener
    ContentResolver resolver = getContentResolver();
    resolver.addStatusChangeListener(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS | ContentResolver.SYNC_OBSERVER_TYPE_PENDING | ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE, new MyObserver());

    // I somehow need to get an instance of Cursor to use setNotificationUri in the next step...
    Cursor cursor2 = resolver.query(Settings.System.CONTENT_URI, null, null, null, null);

    // For testing purposes monitor all system settings
    cursor2.setNotificationUri(resolver, Settings.System.CONTENT_URI);

The listener:

public class MyObserver implements SyncStatusObserver {

public void onStatusChanged(int which) {
    Log.d("TEST", "status changed, which = " + which);

}
}

Well, obviously the listener gets never called, I can't find an entry with the specified TEST tag in logcat ): (For testing I manually changed the brightness setting from manual to automatic in the android settings menu). Any hint what I am doing wrong? Any other, better way to monitor Android system settings?

Thanks for any hint!


回答1:


Here's some example code:

ContentResolver contentResolver = getContentResolver();
Uri setting = Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION);

// Make a listener
ContentObserver observer = new ContentObserver(new Handler()) {
    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
    }

    @Override
    public boolean deliverSelfNotifications() {
        return true;
    }
};

// Start listening
contentResolver.registerContentObserver(setting, false, observer);

// Stop listening
contentResolver.unregisterContentObserver(observer);

Check out the documentation for any of these methods for more details.




回答2:


here is how it can be done, works great: How to implement a ContentObserver for call logs. note than some settings are first written / reallly changed when the user presses the back key in the system preference screen where he changed something!



来源:https://stackoverflow.com/questions/6190779/monitor-android-system-settings-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!