Question

I'm using a custom ContentProvider. For querying, there is a CancellationSignal (API 16+) which can be used to cancel a previous call to query().

My question: How can I archive that with delete()? For clarification, my custom provider manages files on SD card, and so I want to be able to cancel delete operation inside my provider.

Was it helpful?

Solution

I solved this with a simple solution.

For example, for every call to query(), we put a parameter pointing to the task ID, and use a SparseBooleanArray to hold that ID, like:

...
private static final SparseBooleanArray _MapInterruption = new SparseBooleanArray();

...
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    Cursor cursor = ...

    int taskId = ... // obtain task ID from uri
    boolean cancel = ... // obtain cancellation flag from uri
    if (cancel) {
        _MapInterruption.put(taskId, true);
        return null; // don't return any cursor
    } else {
        doQuery(taskId);
        if (_MapInterruption.get(taskId)) {
            _MapInterruption.delete(taskId);
            return null; // because the task was cancelled
        }
    }

    ...
    return cursor;
}// query()

private void doQuery(int taskId) {
    while (!_MapInterruption.get(taskId)) {
        ... // do the task here
    }
}// doQuery()

Usage:

  • To query:

    ...
    getContentResolver().query("content://your-uri?task_id=1", ...);
    
  • To cancel:

    ...
    getContentResolver().query("content://your-uri?task_id=1&cancel=true", ...);
    

For a complete working solution, have a look at android-filechooser.

The advantage is you can use this technique in Android… 1+ and for other methods such as delete(), update()... While CancellationSignal is only available in API 16+ and is limited to only query().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top