我想观看系统设置,并在其值发生变化时收到通知。 Cursor类有一个setNotificationUri方法听起来不错,但它不起作用,编码也感觉很奇怪......那就是我做的:
// 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);
听众:
public class MyObserver implements SyncStatusObserver {
public void onStatusChanged(int which) {
Log.d("TEST", "status changed, which = " + which);
}
}
嗯,很明显,监听器永远不会被调用,我无法在logcat中找到具有指定TEST标签的条目):(对于测试,我在android设置菜单中手动将亮度设置从手动更改为自动)。什么提示我做错了什么?还有其他更好的方法来监控Android系统设置吗?
感谢任何提示!
答案 0 :(得分:9)
以下是一些示例代码:
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);
有关详细信息,请查看任何这些方法的文档。
答案 1 :(得分:6)
这是如何做到的,效果很好:How to implement a ContentObserver for call logs。请注意,当用户在系统首选项屏幕中按下后退键时,首先会写入/重新更改某些设置!