How to implement a ContentObserver for call logs

前端 未结 2 763
粉色の甜心
粉色の甜心 2020-11-27 14:05

I\'d like to know if there is a way to know if the content provider of callings has changed. I mean, if I make a call, or I answer a call, it returns a \"flag\" that a new l

相关标签:
2条回答
  • 2020-11-27 14:29

    Simply create a new subclass of ContentObserver class and override it's onChange() method. The onChange() method will contain all the code that will be executed on content change.

    public class MyObserver extends ContentObserver {
        public MyObserver(Handler handler) {
                super(handler);
            }
    
        @Override
        public void onChange(boolean selfChange) {
            this.onChange(selfChange,null);
        }
    
        @Override
        public void onChange(boolean selfChange, Uri uri) {
            //Write your code here      }
    }
    

    Then all you have to do is register your content provider to the URI.

    getContentResolver().registerContentObserver(YourURI,true,myObserver);
    

    Remember to unregister your content observer object or else it can lead to memory leak.

    Source: Use Android's ContentObserver To React On Content Changes

    0 讨论(0)
  • 2020-11-27 14:44

    Here is the answer. Dont forget to register the content observer with this method:

    registerContentObserver (Uri uri, boolean notifyForDescendents, ContentObserver observer)
    

    And then you can create it like this.

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getApplicationContext()
        .getContentResolver()
        .registerContentObserver(
                android.provider.CallLog.Calls.CONTENT_URI, true,
                new MyContentObserver(handler)); 
    }
    
    class MyContentObserver extends ContentObserver {
        public MyContentObserver(Handler h) {
            super(h);
        }
    
        @Override
        public boolean deliverSelfNotifications() {
            return true;
        }
    
        @Override
        public void onChange(boolean selfChange) {
            Log.d(LOG_TAG, "MyContentObserver.onChange("+selfChange+")");
            super.onChange(selfChange);
    
            // here you call the method to fill the list
        }
    }
    
    0 讨论(0)
提交回复
热议问题