2011-05-31 98 views
2

我想觀看系統設置並在其值發生變化時收到通知。光標類有一個setNotificationUri方法聽起來不錯,但它不能正常工作和編碼,也覺得很奇怪......那是我所做的:監視Android系統設置值

// 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系統設置?

感謝您的任何提示!

回答

4

下面是一些示例代碼:

ContentResolver contentResolver = getContentResolver(); 
Uri setting = Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION); 
ContentObserver observer = new ContentObserver(new Handler()) { 
    @Override 
    public void onChange(boolean selfChange) { 
     super.onChange(selfChange); 
    } 

    @Override 
    public boolean deliverSelfNotifications() { 
     return true; 
    } 
}; 
contentResolver.registerContentObserver(setting, false, observer); 
contentResolver.unregisterContentObserver(observer); 

退房任何這些方法的詳細信息的文檔。