ContentProvider.java revision 4c1241df8f8b7fd5ec3dff6c7e0f66271248e76e
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.content;
18
19import android.content.pm.PackageManager;
20import android.content.pm.PathPermission;
21import android.content.pm.ProviderInfo;
22import android.content.res.AssetFileDescriptor;
23import android.content.res.Configuration;
24import android.database.Cursor;
25import android.database.SQLException;
26import android.net.Uri;
27import android.os.AsyncTask;
28import android.os.Binder;
29import android.os.Bundle;
30import android.os.ParcelFileDescriptor;
31import android.os.Process;
32import android.os.RemoteException;
33import android.util.Log;
34
35import java.io.File;
36import java.io.FileDescriptor;
37import java.io.FileNotFoundException;
38import java.io.IOException;
39import java.io.PrintWriter;
40import java.util.ArrayList;
41
42/**
43 * Content providers are one of the primary building blocks of Android applications, providing
44 * content to applications. They encapsulate data and provide it to applications through the single
45 * {@link ContentResolver} interface. A content provider is only required if you need to share
46 * data between multiple applications. For example, the contacts data is used by multiple
47 * applications and must be stored in a content provider. If you don't need to share data amongst
48 * multiple applications you can use a database directly via
49 * {@link android.database.sqlite.SQLiteDatabase}.
50 *
51 * <p>When a request is made via
52 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
53 * request to the content provider registered with the authority. The content provider can interpret
54 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
55 * URIs.</p>
56 *
57 * <p>The primary methods that need to be implemented are:
58 * <ul>
59 *   <li>{@link #onCreate} which is called to initialize the provider</li>
60 *   <li>{@link #query} which returns data to the caller</li>
61 *   <li>{@link #insert} which inserts new data into the content provider</li>
62 *   <li>{@link #update} which updates existing data in the content provider</li>
63 *   <li>{@link #delete} which deletes data from the content provider</li>
64 *   <li>{@link #getType} which returns the MIME type of data in the content provider</li>
65 * </ul></p>
66 *
67 * <p class="caution">Data access methods (such as {@link #insert} and
68 * {@link #update}) may be called from many threads at once, and must be thread-safe.
69 * Other methods (such as {@link #onCreate}) are only called from the application
70 * main thread, and must avoid performing lengthy operations.  See the method
71 * descriptions for their expected thread behavior.</p>
72 *
73 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
74 * ContentProvider instance, so subclasses don't have to worry about the details of
75 * cross-process calls.</p>
76 *
77 * <div class="special reference">
78 * <h3>Developer Guides</h3>
79 * <p>For more information about using content providers, read the
80 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
81 * developer guide.</p>
82 */
83public abstract class ContentProvider implements ComponentCallbacks2 {
84    private static final String TAG = "ContentProvider";
85
86    /*
87     * Note: if you add methods to ContentProvider, you must add similar methods to
88     *       MockContentProvider.
89     */
90
91    private Context mContext = null;
92    private int mMyUid;
93    private String mReadPermission;
94    private String mWritePermission;
95    private PathPermission[] mPathPermissions;
96    private boolean mExported;
97
98    private Transport mTransport = new Transport();
99
100    /**
101     * Construct a ContentProvider instance.  Content providers must be
102     * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
103     * in the manifest</a>, accessed with {@link ContentResolver}, and created
104     * automatically by the system, so applications usually do not create
105     * ContentProvider instances directly.
106     *
107     * <p>At construction time, the object is uninitialized, and most fields and
108     * methods are unavailable.  Subclasses should initialize themselves in
109     * {@link #onCreate}, not the constructor.
110     *
111     * <p>Content providers are created on the application main thread at
112     * application launch time.  The constructor must not perform lengthy
113     * operations, or application startup will be delayed.
114     */
115    public ContentProvider() {
116    }
117
118    /**
119     * Constructor just for mocking.
120     *
121     * @param context A Context object which should be some mock instance (like the
122     * instance of {@link android.test.mock.MockContext}).
123     * @param readPermission The read permision you want this instance should have in the
124     * test, which is available via {@link #getReadPermission()}.
125     * @param writePermission The write permission you want this instance should have
126     * in the test, which is available via {@link #getWritePermission()}.
127     * @param pathPermissions The PathPermissions you want this instance should have
128     * in the test, which is available via {@link #getPathPermissions()}.
129     * @hide
130     */
131    public ContentProvider(
132            Context context,
133            String readPermission,
134            String writePermission,
135            PathPermission[] pathPermissions) {
136        mContext = context;
137        mReadPermission = readPermission;
138        mWritePermission = writePermission;
139        mPathPermissions = pathPermissions;
140    }
141
142    /**
143     * Given an IContentProvider, try to coerce it back to the real
144     * ContentProvider object if it is running in the local process.  This can
145     * be used if you know you are running in the same process as a provider,
146     * and want to get direct access to its implementation details.  Most
147     * clients should not nor have a reason to use it.
148     *
149     * @param abstractInterface The ContentProvider interface that is to be
150     *              coerced.
151     * @return If the IContentProvider is non-null and local, returns its actual
152     * ContentProvider instance.  Otherwise returns null.
153     * @hide
154     */
155    public static ContentProvider coerceToLocalContentProvider(
156            IContentProvider abstractInterface) {
157        if (abstractInterface instanceof Transport) {
158            return ((Transport)abstractInterface).getContentProvider();
159        }
160        return null;
161    }
162
163    /**
164     * Binder object that deals with remoting.
165     *
166     * @hide
167     */
168    class Transport extends ContentProviderNative {
169        ContentProvider getContentProvider() {
170            return ContentProvider.this;
171        }
172
173        @Override
174        public String getProviderName() {
175            return getContentProvider().getClass().getName();
176        }
177
178        @Override
179        public Cursor query(Uri uri, String[] projection,
180                String selection, String[] selectionArgs, String sortOrder,
181                ICancellationSignal cancellationSignal) {
182            enforceReadPermission(uri);
183            return ContentProvider.this.query(uri, projection, selection, selectionArgs, sortOrder,
184                    CancellationSignal.fromTransport(cancellationSignal));
185        }
186
187        @Override
188        public String getType(Uri uri) {
189            return ContentProvider.this.getType(uri);
190        }
191
192        @Override
193        public Uri insert(Uri uri, ContentValues initialValues) {
194            enforceWritePermission(uri);
195            return ContentProvider.this.insert(uri, initialValues);
196        }
197
198        @Override
199        public int bulkInsert(Uri uri, ContentValues[] initialValues) {
200            enforceWritePermission(uri);
201            return ContentProvider.this.bulkInsert(uri, initialValues);
202        }
203
204        @Override
205        public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
206                throws OperationApplicationException {
207            for (ContentProviderOperation operation : operations) {
208                if (operation.isReadOperation()) {
209                    enforceReadPermission(operation.getUri());
210                }
211
212                if (operation.isWriteOperation()) {
213                    enforceWritePermission(operation.getUri());
214                }
215            }
216            return ContentProvider.this.applyBatch(operations);
217        }
218
219        @Override
220        public int delete(Uri uri, String selection, String[] selectionArgs) {
221            enforceWritePermission(uri);
222            return ContentProvider.this.delete(uri, selection, selectionArgs);
223        }
224
225        @Override
226        public int update(Uri uri, ContentValues values, String selection,
227                String[] selectionArgs) {
228            enforceWritePermission(uri);
229            return ContentProvider.this.update(uri, values, selection, selectionArgs);
230        }
231
232        @Override
233        public ParcelFileDescriptor openFile(Uri uri, String mode)
234                throws FileNotFoundException {
235            if (mode != null && mode.startsWith("rw")) enforceWritePermission(uri);
236            else enforceReadPermission(uri);
237            return ContentProvider.this.openFile(uri, mode);
238        }
239
240        @Override
241        public AssetFileDescriptor openAssetFile(Uri uri, String mode)
242                throws FileNotFoundException {
243            if (mode != null && mode.startsWith("rw")) enforceWritePermission(uri);
244            else enforceReadPermission(uri);
245            return ContentProvider.this.openAssetFile(uri, mode);
246        }
247
248        @Override
249        public Bundle call(String method, String arg, Bundle extras) {
250            return ContentProvider.this.call(method, arg, extras);
251        }
252
253        @Override
254        public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
255            return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
256        }
257
258        @Override
259        public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeType, Bundle opts)
260                throws FileNotFoundException {
261            enforceReadPermission(uri);
262            return ContentProvider.this.openTypedAssetFile(uri, mimeType, opts);
263        }
264
265        @Override
266        public ICancellationSignal createCancellationSignal() throws RemoteException {
267            return CancellationSignal.createTransport();
268        }
269
270        private void enforceReadPermission(Uri uri) {
271            final int uid = Binder.getCallingUid();
272            if (uid == mMyUid) {
273                return;
274            }
275
276            final Context context = getContext();
277            final String rperm = getReadPermission();
278            final int pid = Binder.getCallingPid();
279            if (mExported && (rperm == null
280                    || context.checkPermission(rperm, pid, uid)
281                    == PackageManager.PERMISSION_GRANTED)) {
282                return;
283            }
284
285            PathPermission[] pps = getPathPermissions();
286            if (pps != null) {
287                final String path = uri.getPath();
288                int i = pps.length;
289                while (i > 0) {
290                    i--;
291                    final PathPermission pp = pps[i];
292                    final String pprperm = pp.getReadPermission();
293                    if (pprperm != null && pp.match(path)) {
294                        if (context.checkPermission(pprperm, pid, uid)
295                                == PackageManager.PERMISSION_GRANTED) {
296                            return;
297                        }
298                    }
299                }
300            }
301
302            if (context.checkUriPermission(uri, pid, uid,
303                    Intent.FLAG_GRANT_READ_URI_PERMISSION)
304                    == PackageManager.PERMISSION_GRANTED) {
305                return;
306            }
307
308            String msg = "Permission Denial: reading "
309                    + ContentProvider.this.getClass().getName()
310                    + " uri " + uri + " from pid=" + Binder.getCallingPid()
311                    + ", uid=" + Binder.getCallingUid()
312                    + " requires " + rperm;
313            throw new SecurityException(msg);
314        }
315
316        private boolean hasWritePermission(Uri uri) {
317            final int uid = Binder.getCallingUid();
318            if (uid == mMyUid) {
319                return true;
320            }
321
322            final Context context = getContext();
323            final String wperm = getWritePermission();
324            final int pid = Binder.getCallingPid();
325            if (mExported && (wperm == null
326                    || context.checkPermission(wperm, pid, uid)
327                    == PackageManager.PERMISSION_GRANTED)) {
328                return true;
329            }
330
331            PathPermission[] pps = getPathPermissions();
332            if (pps != null) {
333                final String path = uri.getPath();
334                int i = pps.length;
335                while (i > 0) {
336                    i--;
337                    final PathPermission pp = pps[i];
338                    final String ppwperm = pp.getWritePermission();
339                    if (ppwperm != null && pp.match(path)) {
340                        if (context.checkPermission(ppwperm, pid, uid)
341                                == PackageManager.PERMISSION_GRANTED) {
342                            return true;
343                        }
344                    }
345                }
346            }
347
348            if (context.checkUriPermission(uri, pid, uid,
349                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
350                    == PackageManager.PERMISSION_GRANTED) {
351                return true;
352            }
353
354            return false;
355        }
356
357        private void enforceWritePermission(Uri uri) {
358            if (hasWritePermission(uri)) {
359                return;
360            }
361
362            String msg = "Permission Denial: writing "
363                    + ContentProvider.this.getClass().getName()
364                    + " uri " + uri + " from pid=" + Binder.getCallingPid()
365                    + ", uid=" + Binder.getCallingUid()
366                    + " requires " + getWritePermission();
367            throw new SecurityException(msg);
368        }
369    }
370
371
372    /**
373     * Retrieves the Context this provider is running in.  Only available once
374     * {@link #onCreate} has been called -- this will return null in the
375     * constructor.
376     */
377    public final Context getContext() {
378        return mContext;
379    }
380
381    /**
382     * Change the permission required to read data from the content
383     * provider.  This is normally set for you from its manifest information
384     * when the provider is first created.
385     *
386     * @param permission Name of the permission required for read-only access.
387     */
388    protected final void setReadPermission(String permission) {
389        mReadPermission = permission;
390    }
391
392    /**
393     * Return the name of the permission required for read-only access to
394     * this content provider.  This method can be called from multiple
395     * threads, as described in
396     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
397     * and Threads</a>.
398     */
399    public final String getReadPermission() {
400        return mReadPermission;
401    }
402
403    /**
404     * Change the permission required to read and write data in the content
405     * provider.  This is normally set for you from its manifest information
406     * when the provider is first created.
407     *
408     * @param permission Name of the permission required for read/write access.
409     */
410    protected final void setWritePermission(String permission) {
411        mWritePermission = permission;
412    }
413
414    /**
415     * Return the name of the permission required for read/write access to
416     * this content provider.  This method can be called from multiple
417     * threads, as described in
418     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
419     * and Threads</a>.
420     */
421    public final String getWritePermission() {
422        return mWritePermission;
423    }
424
425    /**
426     * Change the path-based permission required to read and/or write data in
427     * the content provider.  This is normally set for you from its manifest
428     * information when the provider is first created.
429     *
430     * @param permissions Array of path permission descriptions.
431     */
432    protected final void setPathPermissions(PathPermission[] permissions) {
433        mPathPermissions = permissions;
434    }
435
436    /**
437     * Return the path-based permissions required for read and/or write access to
438     * this content provider.  This method can be called from multiple
439     * threads, as described in
440     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
441     * and Threads</a>.
442     */
443    public final PathPermission[] getPathPermissions() {
444        return mPathPermissions;
445    }
446
447    /**
448     * Implement this to initialize your content provider on startup.
449     * This method is called for all registered content providers on the
450     * application main thread at application launch time.  It must not perform
451     * lengthy operations, or application startup will be delayed.
452     *
453     * <p>You should defer nontrivial initialization (such as opening,
454     * upgrading, and scanning databases) until the content provider is used
455     * (via {@link #query}, {@link #insert}, etc).  Deferred initialization
456     * keeps application startup fast, avoids unnecessary work if the provider
457     * turns out not to be needed, and stops database errors (such as a full
458     * disk) from halting application launch.
459     *
460     * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
461     * is a helpful utility class that makes it easy to manage databases,
462     * and will automatically defer opening until first use.  If you do use
463     * SQLiteOpenHelper, make sure to avoid calling
464     * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
465     * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
466     * from this method.  (Instead, override
467     * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
468     * database when it is first opened.)
469     *
470     * @return true if the provider was successfully loaded, false otherwise
471     */
472    public abstract boolean onCreate();
473
474    /**
475     * {@inheritDoc}
476     * This method is always called on the application main thread, and must
477     * not perform lengthy operations.
478     *
479     * <p>The default content provider implementation does nothing.
480     * Override this method to take appropriate action.
481     * (Content providers do not usually care about things like screen
482     * orientation, but may want to know about locale changes.)
483     */
484    public void onConfigurationChanged(Configuration newConfig) {
485    }
486
487    /**
488     * {@inheritDoc}
489     * This method is always called on the application main thread, and must
490     * not perform lengthy operations.
491     *
492     * <p>The default content provider implementation does nothing.
493     * Subclasses may override this method to take appropriate action.
494     */
495    public void onLowMemory() {
496    }
497
498    public void onTrimMemory(int level) {
499    }
500
501    /**
502     * Implement this to handle query requests from clients.
503     * This method can be called from multiple threads, as described in
504     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
505     * and Threads</a>.
506     * <p>
507     * Example client call:<p>
508     * <pre>// Request a specific record.
509     * Cursor managedCursor = managedQuery(
510                ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
511                projection,    // Which columns to return.
512                null,          // WHERE clause.
513                null,          // WHERE clause value substitution
514                People.NAME + " ASC");   // Sort order.</pre>
515     * Example implementation:<p>
516     * <pre>// SQLiteQueryBuilder is a helper class that creates the
517        // proper SQL syntax for us.
518        SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
519
520        // Set the table we're querying.
521        qBuilder.setTables(DATABASE_TABLE_NAME);
522
523        // If the query ends in a specific record number, we're
524        // being asked for a specific record, so set the
525        // WHERE clause in our query.
526        if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
527            qBuilder.appendWhere("_id=" + uri.getPathLeafId());
528        }
529
530        // Make the query.
531        Cursor c = qBuilder.query(mDb,
532                projection,
533                selection,
534                selectionArgs,
535                groupBy,
536                having,
537                sortOrder);
538        c.setNotificationUri(getContext().getContentResolver(), uri);
539        return c;</pre>
540     *
541     * @param uri The URI to query. This will be the full URI sent by the client;
542     *      if the client is requesting a specific record, the URI will end in a record number
543     *      that the implementation should parse and add to a WHERE or HAVING clause, specifying
544     *      that _id value.
545     * @param projection The list of columns to put into the cursor. If
546     *      null all columns are included.
547     * @param selection A selection criteria to apply when filtering rows.
548     *      If null then all rows are included.
549     * @param selectionArgs You may include ?s in selection, which will be replaced by
550     *      the values from selectionArgs, in order that they appear in the selection.
551     *      The values will be bound as Strings.
552     * @param sortOrder How the rows in the cursor should be sorted.
553     *      If null then the provider is free to define the sort order.
554     * @return a Cursor or null.
555     */
556    public abstract Cursor query(Uri uri, String[] projection,
557            String selection, String[] selectionArgs, String sortOrder);
558
559    /**
560     * Implement this to handle query requests from clients with support for cancellation.
561     * This method can be called from multiple threads, as described in
562     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
563     * and Threads</a>.
564     * <p>
565     * Example client call:<p>
566     * <pre>// Request a specific record.
567     * Cursor managedCursor = managedQuery(
568                ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
569                projection,    // Which columns to return.
570                null,          // WHERE clause.
571                null,          // WHERE clause value substitution
572                People.NAME + " ASC");   // Sort order.</pre>
573     * Example implementation:<p>
574     * <pre>// SQLiteQueryBuilder is a helper class that creates the
575        // proper SQL syntax for us.
576        SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
577
578        // Set the table we're querying.
579        qBuilder.setTables(DATABASE_TABLE_NAME);
580
581        // If the query ends in a specific record number, we're
582        // being asked for a specific record, so set the
583        // WHERE clause in our query.
584        if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
585            qBuilder.appendWhere("_id=" + uri.getPathLeafId());
586        }
587
588        // Make the query.
589        Cursor c = qBuilder.query(mDb,
590                projection,
591                selection,
592                selectionArgs,
593                groupBy,
594                having,
595                sortOrder);
596        c.setNotificationUri(getContext().getContentResolver(), uri);
597        return c;</pre>
598     * <p>
599     * If you implement this method then you must also implement the version of
600     * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
601     * signal to ensure correct operation on older versions of the Android Framework in
602     * which the cancellation signal overload was not available.
603     *
604     * @param uri The URI to query. This will be the full URI sent by the client;
605     *      if the client is requesting a specific record, the URI will end in a record number
606     *      that the implementation should parse and add to a WHERE or HAVING clause, specifying
607     *      that _id value.
608     * @param projection The list of columns to put into the cursor. If
609     *      null all columns are included.
610     * @param selection A selection criteria to apply when filtering rows.
611     *      If null then all rows are included.
612     * @param selectionArgs You may include ?s in selection, which will be replaced by
613     *      the values from selectionArgs, in order that they appear in the selection.
614     *      The values will be bound as Strings.
615     * @param sortOrder How the rows in the cursor should be sorted.
616     *      If null then the provider is free to define the sort order.
617     * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
618     * If the operation is canceled, then {@link OperationCanceledException} will be thrown
619     * when the query is executed.
620     * @return a Cursor or null.
621     */
622    public Cursor query(Uri uri, String[] projection,
623            String selection, String[] selectionArgs, String sortOrder,
624            CancellationSignal cancellationSignal) {
625        return query(uri, projection, selection, selectionArgs, sortOrder);
626    }
627
628    /**
629     * Implement this to handle requests for the MIME type of the data at the
630     * given URI.  The returned MIME type should start with
631     * <code>vnd.android.cursor.item</code> for a single record,
632     * or <code>vnd.android.cursor.dir/</code> for multiple items.
633     * This method can be called from multiple threads, as described in
634     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
635     * and Threads</a>.
636     *
637     * <p>Note that there are no permissions needed for an application to
638     * access this information; if your content provider requires read and/or
639     * write permissions, or is not exported, all applications can still call
640     * this method regardless of their access permissions.  This allows them
641     * to retrieve the MIME type for a URI when dispatching intents.
642     *
643     * @param uri the URI to query.
644     * @return a MIME type string, or null if there is no type.
645     */
646    public abstract String getType(Uri uri);
647
648    /**
649     * Implement this to handle requests to insert a new row.
650     * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
651     * after inserting.
652     * This method can be called from multiple threads, as described in
653     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
654     * and Threads</a>.
655     * @param uri The content:// URI of the insertion request.
656     * @param values A set of column_name/value pairs to add to the database.
657     * @return The URI for the newly inserted item.
658     */
659    public abstract Uri insert(Uri uri, ContentValues values);
660
661    /**
662     * Override this to handle requests to insert a set of new rows, or the
663     * default implementation will iterate over the values and call
664     * {@link #insert} on each of them.
665     * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
666     * after inserting.
667     * This method can be called from multiple threads, as described in
668     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
669     * and Threads</a>.
670     *
671     * @param uri The content:// URI of the insertion request.
672     * @param values An array of sets of column_name/value pairs to add to the database.
673     * @return The number of values that were inserted.
674     */
675    public int bulkInsert(Uri uri, ContentValues[] values) {
676        int numValues = values.length;
677        for (int i = 0; i < numValues; i++) {
678            insert(uri, values[i]);
679        }
680        return numValues;
681    }
682
683    /**
684     * Implement this to handle requests to delete one or more rows.
685     * The implementation should apply the selection clause when performing
686     * deletion, allowing the operation to affect multiple rows in a directory.
687     * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyDelete()}
688     * after deleting.
689     * This method can be called from multiple threads, as described in
690     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
691     * and Threads</a>.
692     *
693     * <p>The implementation is responsible for parsing out a row ID at the end
694     * of the URI, if a specific row is being deleted. That is, the client would
695     * pass in <code>content://contacts/people/22</code> and the implementation is
696     * responsible for parsing the record number (22) when creating a SQL statement.
697     *
698     * @param uri The full URI to query, including a row ID (if a specific record is requested).
699     * @param selection An optional restriction to apply to rows when deleting.
700     * @return The number of rows affected.
701     * @throws SQLException
702     */
703    public abstract int delete(Uri uri, String selection, String[] selectionArgs);
704
705    /**
706     * Implement this to handle requests to update one or more rows.
707     * The implementation should update all rows matching the selection
708     * to set the columns according to the provided values map.
709     * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
710     * after updating.
711     * This method can be called from multiple threads, as described in
712     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
713     * and Threads</a>.
714     *
715     * @param uri The URI to query. This can potentially have a record ID if this
716     * is an update request for a specific record.
717     * @param values A Bundle mapping from column names to new column values (NULL is a
718     *               valid value).
719     * @param selection An optional filter to match rows to update.
720     * @return the number of rows affected.
721     */
722    public abstract int update(Uri uri, ContentValues values, String selection,
723            String[] selectionArgs);
724
725    /**
726     * Override this to handle requests to open a file blob.
727     * The default implementation always throws {@link FileNotFoundException}.
728     * This method can be called from multiple threads, as described in
729     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
730     * and Threads</a>.
731     *
732     * <p>This method returns a ParcelFileDescriptor, which is returned directly
733     * to the caller.  This way large data (such as images and documents) can be
734     * returned without copying the content.
735     *
736     * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
737     * their responsibility to close it when done.  That is, the implementation
738     * of this method should create a new ParcelFileDescriptor for each call.
739     *
740     * @param uri The URI whose file is to be opened.
741     * @param mode Access mode for the file.  May be "r" for read-only access,
742     * "rw" for read and write access, or "rwt" for read and write access
743     * that truncates any existing file.
744     *
745     * @return Returns a new ParcelFileDescriptor which you can use to access
746     * the file.
747     *
748     * @throws FileNotFoundException Throws FileNotFoundException if there is
749     * no file associated with the given URI or the mode is invalid.
750     * @throws SecurityException Throws SecurityException if the caller does
751     * not have permission to access the file.
752     *
753     * @see #openAssetFile(Uri, String)
754     * @see #openFileHelper(Uri, String)
755     */
756    public ParcelFileDescriptor openFile(Uri uri, String mode)
757            throws FileNotFoundException {
758        throw new FileNotFoundException("No files supported by provider at "
759                + uri);
760    }
761
762    /**
763     * This is like {@link #openFile}, but can be implemented by providers
764     * that need to be able to return sub-sections of files, often assets
765     * inside of their .apk.
766     * This method can be called from multiple threads, as described in
767     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
768     * and Threads</a>.
769     *
770     * <p>If you implement this, your clients must be able to deal with such
771     * file slices, either directly with
772     * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
773     * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
774     * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
775     * methods.
776     *
777     * <p class="note">If you are implementing this to return a full file, you
778     * should create the AssetFileDescriptor with
779     * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
780     * applications that can not handle sub-sections of files.</p>
781     *
782     * @param uri The URI whose file is to be opened.
783     * @param mode Access mode for the file.  May be "r" for read-only access,
784     * "w" for write-only access (erasing whatever data is currently in
785     * the file), "wa" for write-only access to append to any existing data,
786     * "rw" for read and write access on any existing data, and "rwt" for read
787     * and write access that truncates any existing file.
788     *
789     * @return Returns a new AssetFileDescriptor which you can use to access
790     * the file.
791     *
792     * @throws FileNotFoundException Throws FileNotFoundException if there is
793     * no file associated with the given URI or the mode is invalid.
794     * @throws SecurityException Throws SecurityException if the caller does
795     * not have permission to access the file.
796     *
797     * @see #openFile(Uri, String)
798     * @see #openFileHelper(Uri, String)
799     */
800    public AssetFileDescriptor openAssetFile(Uri uri, String mode)
801            throws FileNotFoundException {
802        ParcelFileDescriptor fd = openFile(uri, mode);
803        return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
804    }
805
806    /**
807     * Convenience for subclasses that wish to implement {@link #openFile}
808     * by looking up a column named "_data" at the given URI.
809     *
810     * @param uri The URI to be opened.
811     * @param mode The file mode.  May be "r" for read-only access,
812     * "w" for write-only access (erasing whatever data is currently in
813     * the file), "wa" for write-only access to append to any existing data,
814     * "rw" for read and write access on any existing data, and "rwt" for read
815     * and write access that truncates any existing file.
816     *
817     * @return Returns a new ParcelFileDescriptor that can be used by the
818     * client to access the file.
819     */
820    protected final ParcelFileDescriptor openFileHelper(Uri uri,
821            String mode) throws FileNotFoundException {
822        Cursor c = query(uri, new String[]{"_data"}, null, null, null);
823        int count = (c != null) ? c.getCount() : 0;
824        if (count != 1) {
825            // If there is not exactly one result, throw an appropriate
826            // exception.
827            if (c != null) {
828                c.close();
829            }
830            if (count == 0) {
831                throw new FileNotFoundException("No entry for " + uri);
832            }
833            throw new FileNotFoundException("Multiple items at " + uri);
834        }
835
836        c.moveToFirst();
837        int i = c.getColumnIndex("_data");
838        String path = (i >= 0 ? c.getString(i) : null);
839        c.close();
840        if (path == null) {
841            throw new FileNotFoundException("Column _data not found.");
842        }
843
844        int modeBits = ContentResolver.modeToMode(uri, mode);
845        return ParcelFileDescriptor.open(new File(path), modeBits);
846    }
847
848    /**
849     * Called by a client to determine the types of data streams that this
850     * content provider supports for the given URI.  The default implementation
851     * returns null, meaning no types.  If your content provider stores data
852     * of a particular type, return that MIME type if it matches the given
853     * mimeTypeFilter.  If it can perform type conversions, return an array
854     * of all supported MIME types that match mimeTypeFilter.
855     *
856     * @param uri The data in the content provider being queried.
857     * @param mimeTypeFilter The type of data the client desires.  May be
858     * a pattern, such as *\/* to retrieve all possible data types.
859     * @return Returns null if there are no possible data streams for the
860     * given mimeTypeFilter.  Otherwise returns an array of all available
861     * concrete MIME types.
862     *
863     * @see #getType(Uri)
864     * @see #openTypedAssetFile(Uri, String, Bundle)
865     * @see ClipDescription#compareMimeTypes(String, String)
866     */
867    public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
868        return null;
869    }
870
871    /**
872     * Called by a client to open a read-only stream containing data of a
873     * particular MIME type.  This is like {@link #openAssetFile(Uri, String)},
874     * except the file can only be read-only and the content provider may
875     * perform data conversions to generate data of the desired type.
876     *
877     * <p>The default implementation compares the given mimeType against the
878     * result of {@link #getType(Uri)} and, if the match, simple calls
879     * {@link #openAssetFile(Uri, String)}.
880     *
881     * <p>See {@link ClipData} for examples of the use and implementation
882     * of this method.
883     *
884     * @param uri The data in the content provider being queried.
885     * @param mimeTypeFilter The type of data the client desires.  May be
886     * a pattern, such as *\/*, if the caller does not have specific type
887     * requirements; in this case the content provider will pick its best
888     * type matching the pattern.
889     * @param opts Additional options from the client.  The definitions of
890     * these are specific to the content provider being called.
891     *
892     * @return Returns a new AssetFileDescriptor from which the client can
893     * read data of the desired type.
894     *
895     * @throws FileNotFoundException Throws FileNotFoundException if there is
896     * no file associated with the given URI or the mode is invalid.
897     * @throws SecurityException Throws SecurityException if the caller does
898     * not have permission to access the data.
899     * @throws IllegalArgumentException Throws IllegalArgumentException if the
900     * content provider does not support the requested MIME type.
901     *
902     * @see #getStreamTypes(Uri, String)
903     * @see #openAssetFile(Uri, String)
904     * @see ClipDescription#compareMimeTypes(String, String)
905     */
906    public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
907            throws FileNotFoundException {
908        if ("*/*".equals(mimeTypeFilter)) {
909            // If they can take anything, the untyped open call is good enough.
910            return openAssetFile(uri, "r");
911        }
912        String baseType = getType(uri);
913        if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
914            // Use old untyped open call if this provider has a type for this
915            // URI and it matches the request.
916            return openAssetFile(uri, "r");
917        }
918        throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
919    }
920
921    /**
922     * Interface to write a stream of data to a pipe.  Use with
923     * {@link ContentProvider#openPipeHelper}.
924     */
925    public interface PipeDataWriter<T> {
926        /**
927         * Called from a background thread to stream data out to a pipe.
928         * Note that the pipe is blocking, so this thread can block on
929         * writes for an arbitrary amount of time if the client is slow
930         * at reading.
931         *
932         * @param output The pipe where data should be written.  This will be
933         * closed for you upon returning from this function.
934         * @param uri The URI whose data is to be written.
935         * @param mimeType The desired type of data to be written.
936         * @param opts Options supplied by caller.
937         * @param args Your own custom arguments.
938         */
939        public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
940                Bundle opts, T args);
941    }
942
943    /**
944     * A helper function for implementing {@link #openTypedAssetFile}, for
945     * creating a data pipe and background thread allowing you to stream
946     * generated data back to the client.  This function returns a new
947     * ParcelFileDescriptor that should be returned to the caller (the caller
948     * is responsible for closing it).
949     *
950     * @param uri The URI whose data is to be written.
951     * @param mimeType The desired type of data to be written.
952     * @param opts Options supplied by caller.
953     * @param args Your own custom arguments.
954     * @param func Interface implementing the function that will actually
955     * stream the data.
956     * @return Returns a new ParcelFileDescriptor holding the read side of
957     * the pipe.  This should be returned to the caller for reading; the caller
958     * is responsible for closing it when done.
959     */
960    public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
961            final Bundle opts, final T args, final PipeDataWriter<T> func)
962            throws FileNotFoundException {
963        try {
964            final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
965
966            AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
967                @Override
968                protected Object doInBackground(Object... params) {
969                    func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
970                    try {
971                        fds[1].close();
972                    } catch (IOException e) {
973                        Log.w(TAG, "Failure closing pipe", e);
974                    }
975                    return null;
976                }
977            };
978            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
979
980            return fds[0];
981        } catch (IOException e) {
982            throw new FileNotFoundException("failure making pipe");
983        }
984    }
985
986    /**
987     * Returns true if this instance is a temporary content provider.
988     * @return true if this instance is a temporary content provider
989     */
990    protected boolean isTemporary() {
991        return false;
992    }
993
994    /**
995     * Returns the Binder object for this provider.
996     *
997     * @return the Binder object for this provider
998     * @hide
999     */
1000    public IContentProvider getIContentProvider() {
1001        return mTransport;
1002    }
1003
1004    /**
1005     * After being instantiated, this is called to tell the content provider
1006     * about itself.
1007     *
1008     * @param context The context this provider is running in
1009     * @param info Registered information about this content provider
1010     */
1011    public void attachInfo(Context context, ProviderInfo info) {
1012        /*
1013         * We may be using AsyncTask from binder threads.  Make it init here
1014         * so its static handler is on the main thread.
1015         */
1016        AsyncTask.init();
1017
1018        /*
1019         * Only allow it to be set once, so after the content service gives
1020         * this to us clients can't change it.
1021         */
1022        if (mContext == null) {
1023            mContext = context;
1024            mMyUid = Process.myUid();
1025            if (info != null) {
1026                setReadPermission(info.readPermission);
1027                setWritePermission(info.writePermission);
1028                setPathPermissions(info.pathPermissions);
1029                mExported = info.exported;
1030            }
1031            ContentProvider.this.onCreate();
1032        }
1033    }
1034
1035    /**
1036     * Override this to handle requests to perform a batch of operations, or the
1037     * default implementation will iterate over the operations and call
1038     * {@link ContentProviderOperation#apply} on each of them.
1039     * If all calls to {@link ContentProviderOperation#apply} succeed
1040     * then a {@link ContentProviderResult} array with as many
1041     * elements as there were operations will be returned.  If any of the calls
1042     * fail, it is up to the implementation how many of the others take effect.
1043     * This method can be called from multiple threads, as described in
1044     * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1045     * and Threads</a>.
1046     *
1047     * @param operations the operations to apply
1048     * @return the results of the applications
1049     * @throws OperationApplicationException thrown if any operation fails.
1050     * @see ContentProviderOperation#apply
1051     */
1052    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
1053            throws OperationApplicationException {
1054        final int numOperations = operations.size();
1055        final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1056        for (int i = 0; i < numOperations; i++) {
1057            results[i] = operations.get(i).apply(this, results, i);
1058        }
1059        return results;
1060    }
1061
1062    /**
1063     * Call a provider-defined method.  This can be used to implement
1064     * interfaces that are cheaper and/or unnatural for a table-like
1065     * model.
1066     *
1067     * @param method method name to call.  Opaque to framework, but should not be null.
1068     * @param arg provider-defined String argument.  May be null.
1069     * @param extras provider-defined Bundle argument.  May be null.
1070     * @return provider-defined return value.  May be null.  Null is also
1071     *   the default for providers which don't implement any call methods.
1072     */
1073    public Bundle call(String method, String arg, Bundle extras) {
1074        return null;
1075    }
1076
1077    /**
1078     * Implement this to shut down the ContentProvider instance. You can then
1079     * invoke this method in unit tests.
1080     *
1081     * <p>
1082     * Android normally handles ContentProvider startup and shutdown
1083     * automatically. You do not need to start up or shut down a
1084     * ContentProvider. When you invoke a test method on a ContentProvider,
1085     * however, a ContentProvider instance is started and keeps running after
1086     * the test finishes, even if a succeeding test instantiates another
1087     * ContentProvider. A conflict develops because the two instances are
1088     * usually running against the same underlying data source (for example, an
1089     * sqlite database).
1090     * </p>
1091     * <p>
1092     * Implementing shutDown() avoids this conflict by providing a way to
1093     * terminate the ContentProvider. This method can also prevent memory leaks
1094     * from multiple instantiations of the ContentProvider, and it can ensure
1095     * unit test isolation by allowing you to completely clean up the test
1096     * fixture before moving on to the next test.
1097     * </p>
1098     */
1099    public void shutdown() {
1100        Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1101                "connections are gracefully shutdown");
1102    }
1103
1104    /**
1105     * Print the Provider's state into the given stream.  This gets invoked if
1106     * you run "adb shell dumpsys activity provider <provider_component_name>".
1107     *
1108     * @param prefix Desired prefix to prepend at each line of output.
1109     * @param fd The raw file descriptor that the dump is being sent to.
1110     * @param writer The PrintWriter to which you should dump your state.  This will be
1111     * closed for you after you return.
1112     * @param args additional arguments to the dump request.
1113     * @hide
1114     */
1115    public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1116        writer.println("nothing to dump");
1117    }
1118}
1119