Android ContentProvider calls bursts of setNotificationUri() to CursorAdapter when many rows are inserted with a batch operation

后端 未结 3 786
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-08 01:51

I have a custom ContentProvider which manages the access to a SQLite database. To load the content of a database table in a ListFragment, I use the

3条回答
  •  孤街浪徒
    2021-02-08 02:53

    To address this exact problem, I overrode applyBatch and set a flag which blocked other methods from sending notifications.

        volatile boolean applyingBatch=false;
        public ContentProviderResult[] applyBatch(
            ArrayList operations)
            throws OperationApplicationException {
        applyingBatch=true;
        ContentProviderResult[] result;
        try {
            result = super.applyBatch(operations);
        } catch (OperationApplicationException e) {
            throw e;
        }
        applyingBatch=false;
        synchronized (delayedNotifications) {
            for (Uri uri : delayedNotifications) {
                getContext().getContentResolver().notifyChange(uri, null);
            }
        }
        return result;
    }
    

    I exposed a method to "store" notifications to be sent when the batch was complete:

    protected void sendNotification(Uri uri) {
        if (applyingBatch) {
            if (delayedNotifications==null) {
                delayedNotifications=new ArrayList();
            }
            synchronized (delayedNotifications) {
                if (!delayedNotifications.contains(uri)) {
                    delayedNotifications.add(uri);
                }
            }
        } else {
            getContext().getContentResolver().notifyChange(uri, null);
        }
    }
    

    And any methods that send notifications employ sendNotification, rather than directly firing a notification.

    There may well be better ways of doing this - it certainly seems as though they're ought to be - but that's what I did.

提交回复
热议问题