summaryrefslogtreecommitdiffstats
path: root/src/com/android/calendar/AsyncQueryService.java
blob: 1f022db94ab674a5cebbe1cf14904fda063af173 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.calendar;

import com.android.calendar.AsyncQueryServiceHelper.OperationInfo;

import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * A helper class that executes {@link ContentResolver} calls in a background
 * {@link android.app.Service}. This minimizes the chance of the call getting
 * lost because the caller ({@link android.app.Activity}) is killed. It is
 * designed for easy migration from {@link android.content.AsyncQueryHandler}
 * which calls the {@link ContentResolver} in a background thread. This supports
 * query/insert/update/delete and also batch mode i.e.
 * {@link ContentProviderOperation}. It also supports delay execution and cancel
 * which allows for time-limited undo. Note that there's one queue per
 * application which serializes all the calls.
 */
public class AsyncQueryService extends Handler {
    private static final String TAG = "AsyncQuery";
    static final boolean localLOGV = false;

    // Used for generating unique tokens for calls to this service
    private static AtomicInteger mUniqueToken = new AtomicInteger(0);

    private Context mContext;
    private Handler mHandler = this; // can be overridden for testing

    /**
     * Data class which holds into info of the queued operation
     */
    public static class Operation {
        static final int EVENT_ARG_QUERY = 1;
        static final int EVENT_ARG_INSERT = 2;
        static final int EVENT_ARG_UPDATE = 3;
        static final int EVENT_ARG_DELETE = 4;
        static final int EVENT_ARG_BATCH = 5;

        /**
         * unique identify for cancellation purpose
         */
        public int token;

        /**
         * One of the EVENT_ARG_ constants in the class describing the operation
         */
        public int op;

        /**
         * {@link SystemClock.elapsedRealtime()} based
         */
        public long scheduledExecutionTime;

        protected static char opToChar(int op) {
            switch (op) {
                case Operation.EVENT_ARG_QUERY:
                    return 'Q';
                case Operation.EVENT_ARG_INSERT:
                    return 'I';
                case Operation.EVENT_ARG_UPDATE:
                    return 'U';
                case Operation.EVENT_ARG_DELETE:
                    return 'D';
                case Operation.EVENT_ARG_BATCH:
                    return 'B';
                default:
                    return '?';
            }
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("Operation [op=");
            builder.append(op);
            builder.append(", token=");
            builder.append(token);
            builder.append(", scheduledExecutionTime=");
            builder.append(scheduledExecutionTime);
            builder.append("]");
            return builder.toString();
        }
    }

    public AsyncQueryService(Context context) {
        mContext = context;
    }

    /**
     * returns a practically unique token for db operations
     */
    public final int getNextToken() {
        return mUniqueToken.getAndIncrement();
    }

    /**
     * Gets the last delayed operation. It is typically used for canceling.
     *
     * @return Operation object which contains of the last cancelable operation
     */
    public final Operation getLastCancelableOperation() {
        return AsyncQueryServiceHelper.getLastCancelableOperation();
    }

    /**
     * Attempts to cancel operation that has not already started. Note that
     * there is no guarantee that the operation will be canceled. They still may
     * result in a call to on[Query/Insert/Update/Delete/Batch]Complete after
     * this call has completed.
     *
     * @param token The token representing the operation to be canceled. If
     *            multiple operations have the same token they will all be
     *            canceled.
     */
    public final int cancelOperation(int token) {
        return AsyncQueryServiceHelper.cancelOperation(token);
    }

    /**
     * This method begins an asynchronous query. When the query is done
     * {@link #onQueryComplete} is called.
     *
     * @param token A token passed into {@link #onQueryComplete} to identify the
     *            query.
     * @param cookie An object that gets passed into {@link #onQueryComplete}
     * @param uri The URI, using the content:// scheme, for the content to
     *            retrieve.
     * @param projection A list of which columns to return. Passing null will
     *            return all columns, which is discouraged to prevent reading
     *            data from storage that isn't going to be used.
     * @param selection A filter declaring which rows to return, formatted as an
     *            SQL WHERE clause (excluding the WHERE itself). Passing null
     *            will return all rows for the given URI.
     * @param selectionArgs You may include ?s in selection, which will be
     *            replaced by the values from selectionArgs, in the order that
     *            they appear in the selection. The values will be bound as
     *            Strings.
     * @param orderBy How to order the rows, formatted as an SQL ORDER BY clause
     *            (excluding the ORDER BY itself). Passing null will use the
     *            default sort order, which may be unordered.
     */
    public void startQuery(int token, Object cookie, Uri uri, String[] projection,
            String selection, String[] selectionArgs, String orderBy) {
        OperationInfo info = new OperationInfo();
        info.op = Operation.EVENT_ARG_QUERY;
        info.resolver = mContext.getContentResolver();

        info.handler = mHandler;
        info.token = token;
        info.cookie = cookie;
        info.uri = uri;
        info.projection = projection;
        info.selection = selection;
        info.selectionArgs = selectionArgs;
        info.orderBy = orderBy;

        AsyncQueryServiceHelper.queueOperation(mContext, info);
    }

    /**
     * This method begins an asynchronous insert. When the insert operation is
     * done {@link #onInsertComplete} is called.
     *
     * @param token A token passed into {@link #onInsertComplete} to identify
     *            the insert operation.
     * @param cookie An object that gets passed into {@link #onInsertComplete}
     * @param uri the Uri passed to the insert operation.
     * @param initialValues the ContentValues parameter passed to the insert
     *            operation.
     * @param delayMillis delay in executing the operation. This operation will
     *            execute before the delayed time when another operation is
     *            added. Useful for implementing single level undo.
     */
    public void startInsert(int token, Object cookie, Uri uri, ContentValues initialValues,
            long delayMillis) {
        OperationInfo info = new OperationInfo();
        info.op = Operation.EVENT_ARG_INSERT;
        info.resolver = mContext.getContentResolver();
        info.handler = mHandler;

        info.token = token;
        info.cookie = cookie;
        info.uri = uri;
        info.values = initialValues;
        info.delayMillis = delayMillis;

        AsyncQueryServiceHelper.queueOperation(mContext, info);
    }

    /**
     * This method begins an asynchronous update. When the update operation is
     * done {@link #onUpdateComplete} is called.
     *
     * @param token A token passed into {@link #onUpdateComplete} to identify
     *            the update operation.
     * @param cookie An object that gets passed into {@link #onUpdateComplete}
     * @param uri the Uri passed to the update operation.
     * @param values the ContentValues parameter passed to the update operation.
     * @param selection A filter declaring which rows to update, formatted as an
     *            SQL WHERE clause (excluding the WHERE itself). Passing null
     *            will update all rows for the given URI.
     * @param selectionArgs You may include ?s in selection, which will be
     *            replaced by the values from selectionArgs, in the order that
     *            they appear in the selection. The values will be bound as
     *            Strings.
     * @param delayMillis delay in executing the operation. This operation will
     *            execute before the delayed time when another operation is
     *            added. Useful for implementing single level undo.
     */
    public void startUpdate(int token, Object cookie, Uri uri, ContentValues values,
            String selection, String[] selectionArgs, long delayMillis) {
        OperationInfo info = new OperationInfo();
        info.op = Operation.EVENT_ARG_UPDATE;
        info.resolver = mContext.getContentResolver();
        info.handler = mHandler;

        info.token = token;
        info.cookie = cookie;
        info.uri = uri;
        info.values = values;
        info.selection = selection;
        info.selectionArgs = selectionArgs;
        info.delayMillis = delayMillis;

        AsyncQueryServiceHelper.queueOperation(mContext, info);
    }

    /**
     * This method begins an asynchronous delete. When the delete operation is
     * done {@link #onDeleteComplete} is called.
     *
     * @param token A token passed into {@link #onDeleteComplete} to identify
     *            the delete operation.
     * @param cookie An object that gets passed into {@link #onDeleteComplete}
     * @param uri the Uri passed to the delete operation.
     * @param selection A filter declaring which rows to delete, formatted as an
     *            SQL WHERE clause (excluding the WHERE itself). Passing null
     *            will delete all rows for the given URI.
     * @param selectionArgs You may include ?s in selection, which will be
     *            replaced by the values from selectionArgs, in the order that
     *            they appear in the selection. The values will be bound as
     *            Strings.
     * @param delayMillis delay in executing the operation. This operation will
     *            execute before the delayed time when another operation is
     *            added. Useful for implementing single level undo.
     */
    public void startDelete(int token, Object cookie, Uri uri, String selection,
            String[] selectionArgs, long delayMillis) {
        OperationInfo info = new OperationInfo();
        info.op = Operation.EVENT_ARG_DELETE;
        info.resolver = mContext.getContentResolver();
        info.handler = mHandler;

        info.token = token;
        info.cookie = cookie;
        info.uri = uri;
        info.selection = selection;
        info.selectionArgs = selectionArgs;
        info.delayMillis = delayMillis;

        AsyncQueryServiceHelper.queueOperation(mContext, info);
    }

    /**
     * This method begins an asynchronous {@link ContentProviderOperation}. When
     * the operation is done {@link #onBatchComplete} is called.
     *
     * @param token A token passed into {@link #onDeleteComplete} to identify
     *            the delete operation.
     * @param cookie An object that gets passed into {@link #onDeleteComplete}
     * @param authority the authority used for the
     *            {@link ContentProviderOperation}.
     * @param cpo the {@link ContentProviderOperation} to be executed.
     * @param delayMillis delay in executing the operation. This operation will
     *            execute before the delayed time when another operation is
     *            added. Useful for implementing single level undo.
     */
    public void startBatch(int token, Object cookie, String authority,
            ArrayList<ContentProviderOperation> cpo, long delayMillis) {
        OperationInfo info = new OperationInfo();
        info.op = Operation.EVENT_ARG_BATCH;
        info.resolver = mContext.getContentResolver();
        info.handler = mHandler;

        info.token = token;
        info.cookie = cookie;
        info.authority = authority;
        info.cpo = cpo;
        info.delayMillis = delayMillis;

        AsyncQueryServiceHelper.queueOperation(mContext, info);
    }

    /**
     * Called when an asynchronous query is completed.
     *
     * @param token the token to identify the query, passed in from
     *            {@link #startQuery}.
     * @param cookie the cookie object passed in from {@link #startQuery}.
     * @param cursor The cursor holding the results from the query.
     */
    protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
        if (localLOGV) {
            Log.d(TAG, "########## default onQueryComplete");
        }
    }

    /**
     * Called when an asynchronous insert is completed.
     *
     * @param token the token to identify the query, passed in from
     *            {@link #startInsert}.
     * @param cookie the cookie object that's passed in from
     *            {@link #startInsert}.
     * @param uri the uri returned from the insert operation.
     */
    protected void onInsertComplete(int token, Object cookie, Uri uri) {
        if (localLOGV) {
            Log.d(TAG, "########## default onInsertComplete");
        }
    }

    /**
     * Called when an asynchronous update is completed.
     *
     * @param token the token to identify the query, passed in from
     *            {@link #startUpdate}.
     * @param cookie the cookie object that's passed in from
     *            {@link #startUpdate}.
     * @param result the result returned from the update operation
     */
    protected void onUpdateComplete(int token, Object cookie, int result) {
        if (localLOGV) {
            Log.d(TAG, "########## default onUpdateComplete");
        }
    }

    /**
     * Called when an asynchronous delete is completed.
     *
     * @param token the token to identify the query, passed in from
     *            {@link #startDelete}.
     * @param cookie the cookie object that's passed in from
     *            {@link #startDelete}.
     * @param result the result returned from the delete operation
     */
    protected void onDeleteComplete(int token, Object cookie, int result) {
        if (localLOGV) {
            Log.d(TAG, "########## default onDeleteComplete");
        }
    }

    /**
     * Called when an asynchronous {@link ContentProviderOperation} is
     * completed.
     *
     * @param token the token to identify the query, passed in from
     *            {@link #startDelete}.
     * @param cookie the cookie object that's passed in from
     *            {@link #startDelete}.
     * @param results the result returned from executing the
     *            {@link ContentProviderOperation}
     */
    protected void onBatchComplete(int token, Object cookie, ContentProviderResult[] results) {
        if (localLOGV) {
            Log.d(TAG, "########## default onBatchComplete");
        }
    }

    @Override
    public void handleMessage(Message msg) {
        OperationInfo info = (OperationInfo) msg.obj;

        int token = msg.what;
        int op = msg.arg1;

        if (localLOGV) {
            Log.d(TAG, "AsyncQueryService.handleMessage: token=" + token + ", op=" + op
                    + ", result=" + info.result);
        }

        // pass token back to caller on each callback.
        switch (op) {
            case Operation.EVENT_ARG_QUERY:
                onQueryComplete(token, info.cookie, (Cursor) info.result);
                break;

            case Operation.EVENT_ARG_INSERT:
                onInsertComplete(token, info.cookie, (Uri) info.result);
                break;

            case Operation.EVENT_ARG_UPDATE:
                onUpdateComplete(token, info.cookie, (Integer) info.result);
                break;

            case Operation.EVENT_ARG_DELETE:
                onDeleteComplete(token, info.cookie, (Integer) info.result);
                break;

            case Operation.EVENT_ARG_BATCH:
                onBatchComplete(token, info.cookie, (ContentProviderResult[]) info.result);
                break;
        }
    }

//    @VisibleForTesting
    protected void setTestHandler(Handler handler) {
        mHandler = handler;
    }
}