What's the mechanism of setNotificationUri?

前端 未结 1 1936
旧巷少年郎
旧巷少年郎 2021-01-30 17:20

I\'ve just implemented a CursorLoader and it works great! In fact, I didn\'t believe that my ListView would automatically update when the underlying data changed until I tested

相关标签:
1条回答
  • 2021-01-30 18:11

    Please, correct me if I'm wrong somewhere.

    ContentProvider calls something like this in query(…) method:

    // Tell the cursor what uri to watch, so it knows when its source data changes
    cursor.setNotificationUri(getContext().getContentResolver(), uri);
    

    CursorLoader get cursor back and registers an observer.

    /* Runs on a worker thread */
    @Override
    public Cursor loadInBackground() {
        Cursor cursor = getContext().getContentResolver().query(mUri, mProjection,
                mSelection, mSelectionArgs, mSortOrder);
        if (cursor != null) {
            // Ensure the cursor window is filled
            cursor.getCount();
            registerContentObserver(cursor, mObserver);
        }
        return cursor;
    }
    
    /**
     * Registers an observer to get notifications from the content provider
     * when the cursor needs to be refreshed.
     */
    void registerContentObserver(Cursor cursor, ContentObserver observer) {
        cursor.registerContentObserver(mObserver);
    }
    

    When someone modifies data, ContentProvider notifies ContentResolver about changes:

    getContext().getContentResolver().notifyChange(uri, null);
    

    ContentResolver in its turn notifies all registered observers.

    Observer, registered by CursorLoader, forces it to load new data.

    0 讨论(0)
提交回复
热议问题