blob: ec67d8c1fe82d3cd78ac066383f244a965091d23 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070022import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.pm.ProviderInfo;
24import android.content.res.AssetFileDescriptor;
25import android.content.res.Configuration;
26import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.database.SQLException;
28import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070029import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080031import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070033import android.os.Process;
Jeff Brown75ea64f2012-01-25 19:37:13 -080034import android.os.RemoteException;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070035import android.os.UserId;
Vasu Nori0c9e14a2010-08-04 13:31:48 -070036import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037
38import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080039import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070041import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080042import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070043import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044
45/**
46 * Content providers are one of the primary building blocks of Android applications, providing
47 * content to applications. They encapsulate data and provide it to applications through the single
48 * {@link ContentResolver} interface. A content provider is only required if you need to share
49 * data between multiple applications. For example, the contacts data is used by multiple
50 * applications and must be stored in a content provider. If you don't need to share data amongst
51 * multiple applications you can use a database directly via
52 * {@link android.database.sqlite.SQLiteDatabase}.
53 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054 * <p>When a request is made via
55 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
56 * request to the content provider registered with the authority. The content provider can interpret
57 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
58 * URIs.</p>
59 *
60 * <p>The primary methods that need to be implemented are:
61 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070062 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063 * <li>{@link #query} which returns data to the caller</li>
64 * <li>{@link #insert} which inserts new data into the content provider</li>
65 * <li>{@link #update} which updates existing data in the content provider</li>
66 * <li>{@link #delete} which deletes data from the content provider</li>
67 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
68 * </ul></p>
69 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070070 * <p class="caution">Data access methods (such as {@link #insert} and
71 * {@link #update}) may be called from many threads at once, and must be thread-safe.
72 * Other methods (such as {@link #onCreate}) are only called from the application
73 * main thread, and must avoid performing lengthy operations. See the method
74 * descriptions for their expected thread behavior.</p>
75 *
76 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
77 * ContentProvider instance, so subclasses don't have to worry about the details of
78 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070079 *
80 * <div class="special reference">
81 * <h3>Developer Guides</h3>
82 * <p>For more information about using content providers, read the
83 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
84 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -070086public abstract class ContentProvider implements ComponentCallbacks2 {
Vasu Nori0c9e14a2010-08-04 13:31:48 -070087 private static final String TAG = "ContentProvider";
88
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +090089 /*
90 * Note: if you add methods to ContentProvider, you must add similar methods to
91 * MockContentProvider.
92 */
93
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070095 private int mMyUid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private String mReadPermission;
97 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070098 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -070099 private boolean mExported;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
101 private Transport mTransport = new Transport();
102
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700103 /**
104 * Construct a ContentProvider instance. Content providers must be
105 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
106 * in the manifest</a>, accessed with {@link ContentResolver}, and created
107 * automatically by the system, so applications usually do not create
108 * ContentProvider instances directly.
109 *
110 * <p>At construction time, the object is uninitialized, and most fields and
111 * methods are unavailable. Subclasses should initialize themselves in
112 * {@link #onCreate}, not the constructor.
113 *
114 * <p>Content providers are created on the application main thread at
115 * application launch time. The constructor must not perform lengthy
116 * operations, or application startup will be delayed.
117 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900118 public ContentProvider() {
119 }
120
121 /**
122 * Constructor just for mocking.
123 *
124 * @param context A Context object which should be some mock instance (like the
125 * instance of {@link android.test.mock.MockContext}).
126 * @param readPermission The read permision you want this instance should have in the
127 * test, which is available via {@link #getReadPermission()}.
128 * @param writePermission The write permission you want this instance should have
129 * in the test, which is available via {@link #getWritePermission()}.
130 * @param pathPermissions The PathPermissions you want this instance should have
131 * in the test, which is available via {@link #getPathPermissions()}.
132 * @hide
133 */
134 public ContentProvider(
135 Context context,
136 String readPermission,
137 String writePermission,
138 PathPermission[] pathPermissions) {
139 mContext = context;
140 mReadPermission = readPermission;
141 mWritePermission = writePermission;
142 mPathPermissions = pathPermissions;
143 }
144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 /**
146 * Given an IContentProvider, try to coerce it back to the real
147 * ContentProvider object if it is running in the local process. This can
148 * be used if you know you are running in the same process as a provider,
149 * and want to get direct access to its implementation details. Most
150 * clients should not nor have a reason to use it.
151 *
152 * @param abstractInterface The ContentProvider interface that is to be
153 * coerced.
154 * @return If the IContentProvider is non-null and local, returns its actual
155 * ContentProvider instance. Otherwise returns null.
156 * @hide
157 */
158 public static ContentProvider coerceToLocalContentProvider(
159 IContentProvider abstractInterface) {
160 if (abstractInterface instanceof Transport) {
161 return ((Transport)abstractInterface).getContentProvider();
162 }
163 return null;
164 }
165
166 /**
167 * Binder object that deals with remoting.
168 *
169 * @hide
170 */
171 class Transport extends ContentProviderNative {
172 ContentProvider getContentProvider() {
173 return ContentProvider.this;
174 }
175
Jeff Brownd2183652011-10-09 12:39:53 -0700176 @Override
177 public String getProviderName() {
178 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 }
180
Jeff Brown75ea64f2012-01-25 19:37:13 -0800181 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 public Cursor query(Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800183 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800184 ICancellationSignal cancellationSignal) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700185 enforceReadPermission(uri);
Jeff Brown75ea64f2012-01-25 19:37:13 -0800186 return ContentProvider.this.query(uri, projection, selection, selectionArgs, sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800187 CancellationSignal.fromTransport(cancellationSignal));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 }
189
Jeff Brown75ea64f2012-01-25 19:37:13 -0800190 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 public String getType(Uri uri) {
192 return ContentProvider.this.getType(uri);
193 }
194
Jeff Brown75ea64f2012-01-25 19:37:13 -0800195 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 public Uri insert(Uri uri, ContentValues initialValues) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700197 enforceWritePermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 return ContentProvider.this.insert(uri, initialValues);
199 }
200
Jeff Brown75ea64f2012-01-25 19:37:13 -0800201 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 public int bulkInsert(Uri uri, ContentValues[] initialValues) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700203 enforceWritePermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 return ContentProvider.this.bulkInsert(uri, initialValues);
205 }
206
Jeff Brown75ea64f2012-01-25 19:37:13 -0800207 @Override
Fred Quintana03d94902009-05-22 14:23:31 -0700208 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700209 throws OperationApplicationException {
210 for (ContentProviderOperation operation : operations) {
211 if (operation.isReadOperation()) {
Dianne Hackborne3f05442009-07-09 12:15:46 -0700212 enforceReadPermission(operation.getUri());
Fred Quintana89437372009-05-15 15:10:40 -0700213 }
214
215 if (operation.isWriteOperation()) {
Dianne Hackborne3f05442009-07-09 12:15:46 -0700216 enforceWritePermission(operation.getUri());
Fred Quintana89437372009-05-15 15:10:40 -0700217 }
218 }
219 return ContentProvider.this.applyBatch(operations);
Fred Quintana6a8d5332009-05-07 17:35:38 -0700220 }
221
Jeff Brown75ea64f2012-01-25 19:37:13 -0800222 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 public int delete(Uri uri, String selection, String[] selectionArgs) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700224 enforceWritePermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 return ContentProvider.this.delete(uri, selection, selectionArgs);
226 }
227
Jeff Brown75ea64f2012-01-25 19:37:13 -0800228 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 public int update(Uri uri, ContentValues values, String selection,
230 String[] selectionArgs) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700231 enforceWritePermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 return ContentProvider.this.update(uri, values, selection, selectionArgs);
233 }
234
Jeff Brown75ea64f2012-01-25 19:37:13 -0800235 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 public ParcelFileDescriptor openFile(Uri uri, String mode)
237 throws FileNotFoundException {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700238 if (mode != null && mode.startsWith("rw")) enforceWritePermission(uri);
239 else enforceReadPermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 return ContentProvider.this.openFile(uri, mode);
241 }
242
Jeff Brown75ea64f2012-01-25 19:37:13 -0800243 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
245 throws FileNotFoundException {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700246 if (mode != null && mode.startsWith("rw")) enforceWritePermission(uri);
247 else enforceReadPermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 return ContentProvider.this.openAssetFile(uri, mode);
249 }
250
Jeff Brown75ea64f2012-01-25 19:37:13 -0800251 @Override
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -0800252 public Bundle call(String method, String arg, Bundle extras) {
253 return ContentProvider.this.call(method, arg, extras);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800254 }
255
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700256 @Override
257 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
258 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
259 }
260
261 @Override
262 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeType, Bundle opts)
263 throws FileNotFoundException {
264 enforceReadPermission(uri);
265 return ContentProvider.this.openTypedAssetFile(uri, mimeType, opts);
266 }
267
Jeff Brown75ea64f2012-01-25 19:37:13 -0800268 @Override
Jeff Brown4c1241d2012-02-02 17:05:00 -0800269 public ICancellationSignal createCancellationSignal() throws RemoteException {
270 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800271 }
272
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700273 private boolean hasReadPermission(Uri uri) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700274 final Context context = getContext();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 final int pid = Binder.getCallingPid();
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700276 final int uid = Binder.getCallingUid();
277
278 if (uid == mMyUid) {
279 return true;
280
281 } else if (mExported) {
282 final String componentPerm = getReadPermission();
283 if (componentPerm != null
284 && (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED)) {
285 return true;
286 }
287
288 // track if unprotected read is allowed; any denied
289 // <path-permission> below removes this ability
290 boolean allowDefaultRead = (componentPerm == null);
291
292 final PathPermission[] pps = getPathPermissions();
293 if (pps != null) {
294 final String path = uri.getPath();
295 for (PathPermission pp : pps) {
296 final String pathPerm = pp.getReadPermission();
297 if (pathPerm != null && pp.match(path)) {
298 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
299 return true;
300 } else {
301 // any denied <path-permission> means we lose
302 // default <provider> access.
303 allowDefaultRead = false;
304 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700305 }
306 }
307 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700308
309 // if we passed <path-permission> checks above, and no default
310 // <provider> permission, then allow access.
311 if (allowDefaultRead) return true;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700312 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700313
314 // last chance, check against any uri grants
315 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION)
316 == PERMISSION_GRANTED) {
317 return true;
318 }
319
320 return false;
321 }
322
323 private void enforceReadPermission(Uri uri) {
324 if (hasReadPermission(uri)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 return;
326 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 String msg = "Permission Denial: reading "
329 + ContentProvider.this.getClass().getName()
330 + " uri " + uri + " from pid=" + Binder.getCallingPid()
331 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700332 + " requires " + getReadPermission();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 throw new SecurityException(msg);
334 }
335
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700336 private boolean hasWritePermission(Uri uri) {
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700337 final Context context = getContext();
338 final int pid = Binder.getCallingPid();
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700339 final int uid = Binder.getCallingUid();
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700340
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700341 if (uid == mMyUid) {
342 return true;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700343
344 } else if (mExported) {
345 final String componentPerm = getWritePermission();
346 if (componentPerm != null
347 && (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED)) {
348 return true;
349 }
350
351 // track if unprotected write is allowed; any denied
352 // <path-permission> below removes this ability
353 boolean allowDefaultWrite = (componentPerm == null);
354
355 final PathPermission[] pps = getPathPermissions();
356 if (pps != null) {
357 final String path = uri.getPath();
358 for (PathPermission pp : pps) {
359 final String pathPerm = pp.getWritePermission();
360 if (pathPerm != null && pp.match(path)) {
361 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
362 return true;
363 } else {
364 // any denied <path-permission> means we lose
365 // default <provider> access.
366 allowDefaultWrite = false;
367 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700368 }
369 }
370 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700371
372 // if we passed <path-permission> checks above, and no default
373 // <provider> permission, then allow access.
374 if (allowDefaultWrite) return true;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700375 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700376
377 // last chance, check against any uri grants
378 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
379 == PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700380 return true;
381 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700382
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700383 return false;
384 }
385
386 private void enforceWritePermission(Uri uri) {
387 if (hasWritePermission(uri)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 return;
389 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 String msg = "Permission Denial: writing "
392 + ContentProvider.this.getClass().getName()
393 + " uri " + uri + " from pid=" + Binder.getCallingPid()
394 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700395 + " requires " + getWritePermission();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 throw new SecurityException(msg);
397 }
398 }
399
400
401 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700402 * Retrieves the Context this provider is running in. Only available once
403 * {@link #onCreate} has been called -- this will return null in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 * constructor.
405 */
406 public final Context getContext() {
407 return mContext;
408 }
409
410 /**
411 * Change the permission required to read data from the content
412 * provider. This is normally set for you from its manifest information
413 * when the provider is first created.
414 *
415 * @param permission Name of the permission required for read-only access.
416 */
417 protected final void setReadPermission(String permission) {
418 mReadPermission = permission;
419 }
420
421 /**
422 * Return the name of the permission required for read-only access to
423 * this content provider. This method can be called from multiple
424 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800425 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
426 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 */
428 public final String getReadPermission() {
429 return mReadPermission;
430 }
431
432 /**
433 * Change the permission required to read and write data in the content
434 * provider. This is normally set for you from its manifest information
435 * when the provider is first created.
436 *
437 * @param permission Name of the permission required for read/write access.
438 */
439 protected final void setWritePermission(String permission) {
440 mWritePermission = permission;
441 }
442
443 /**
444 * Return the name of the permission required for read/write access to
445 * this content provider. This method can be called from multiple
446 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800447 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
448 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 */
450 public final String getWritePermission() {
451 return mWritePermission;
452 }
453
454 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700455 * Change the path-based permission required to read and/or write data in
456 * the content provider. This is normally set for you from its manifest
457 * information when the provider is first created.
458 *
459 * @param permissions Array of path permission descriptions.
460 */
461 protected final void setPathPermissions(PathPermission[] permissions) {
462 mPathPermissions = permissions;
463 }
464
465 /**
466 * Return the path-based permissions required for read and/or write access to
467 * this content provider. This method can be called from multiple
468 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800469 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
470 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700471 */
472 public final PathPermission[] getPathPermissions() {
473 return mPathPermissions;
474 }
475
476 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700477 * Implement this to initialize your content provider on startup.
478 * This method is called for all registered content providers on the
479 * application main thread at application launch time. It must not perform
480 * lengthy operations, or application startup will be delayed.
481 *
482 * <p>You should defer nontrivial initialization (such as opening,
483 * upgrading, and scanning databases) until the content provider is used
484 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
485 * keeps application startup fast, avoids unnecessary work if the provider
486 * turns out not to be needed, and stops database errors (such as a full
487 * disk) from halting application launch.
488 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700489 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700490 * is a helpful utility class that makes it easy to manage databases,
491 * and will automatically defer opening until first use. If you do use
492 * SQLiteOpenHelper, make sure to avoid calling
493 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
494 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
495 * from this method. (Instead, override
496 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
497 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 *
499 * @return true if the provider was successfully loaded, false otherwise
500 */
501 public abstract boolean onCreate();
502
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700503 /**
504 * {@inheritDoc}
505 * This method is always called on the application main thread, and must
506 * not perform lengthy operations.
507 *
508 * <p>The default content provider implementation does nothing.
509 * Override this method to take appropriate action.
510 * (Content providers do not usually care about things like screen
511 * orientation, but may want to know about locale changes.)
512 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 public void onConfigurationChanged(Configuration newConfig) {
514 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700515
516 /**
517 * {@inheritDoc}
518 * This method is always called on the application main thread, and must
519 * not perform lengthy operations.
520 *
521 * <p>The default content provider implementation does nothing.
522 * Subclasses may override this method to take appropriate action.
523 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 public void onLowMemory() {
525 }
526
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700527 public void onTrimMemory(int level) {
528 }
529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700531 * Implement this to handle query requests from clients.
532 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800533 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
534 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 * <p>
536 * Example client call:<p>
537 * <pre>// Request a specific record.
538 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000539 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 projection, // Which columns to return.
541 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000542 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 People.NAME + " ASC"); // Sort order.</pre>
544 * Example implementation:<p>
545 * <pre>// SQLiteQueryBuilder is a helper class that creates the
546 // proper SQL syntax for us.
547 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
548
549 // Set the table we're querying.
550 qBuilder.setTables(DATABASE_TABLE_NAME);
551
552 // If the query ends in a specific record number, we're
553 // being asked for a specific record, so set the
554 // WHERE clause in our query.
555 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
556 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
557 }
558
559 // Make the query.
560 Cursor c = qBuilder.query(mDb,
561 projection,
562 selection,
563 selectionArgs,
564 groupBy,
565 having,
566 sortOrder);
567 c.setNotificationUri(getContext().getContentResolver(), uri);
568 return c;</pre>
569 *
570 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000571 * if the client is requesting a specific record, the URI will end in a record number
572 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
573 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 * @param projection The list of columns to put into the cursor. If
575 * null all columns are included.
576 * @param selection A selection criteria to apply when filtering rows.
577 * If null then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000578 * @param selectionArgs You may include ?s in selection, which will be replaced by
579 * the values from selectionArgs, in order that they appear in the selection.
580 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 * @param sortOrder How the rows in the cursor should be sorted.
Alan Jones81a476f2009-05-21 12:32:17 +1000582 * If null then the provider is free to define the sort order.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 * @return a Cursor or null.
584 */
585 public abstract Cursor query(Uri uri, String[] projection,
586 String selection, String[] selectionArgs, String sortOrder);
587
Fred Quintana5bba6322009-10-05 14:21:12 -0700588 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800589 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800590 * This method can be called from multiple threads, as described in
591 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
592 * and Threads</a>.
593 * <p>
594 * Example client call:<p>
595 * <pre>// Request a specific record.
596 * Cursor managedCursor = managedQuery(
597 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
598 projection, // Which columns to return.
599 null, // WHERE clause.
600 null, // WHERE clause value substitution
601 People.NAME + " ASC"); // Sort order.</pre>
602 * Example implementation:<p>
603 * <pre>// SQLiteQueryBuilder is a helper class that creates the
604 // proper SQL syntax for us.
605 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
606
607 // Set the table we're querying.
608 qBuilder.setTables(DATABASE_TABLE_NAME);
609
610 // If the query ends in a specific record number, we're
611 // being asked for a specific record, so set the
612 // WHERE clause in our query.
613 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
614 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
615 }
616
617 // Make the query.
618 Cursor c = qBuilder.query(mDb,
619 projection,
620 selection,
621 selectionArgs,
622 groupBy,
623 having,
624 sortOrder);
625 c.setNotificationUri(getContext().getContentResolver(), uri);
626 return c;</pre>
627 * <p>
628 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800629 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
630 * signal to ensure correct operation on older versions of the Android Framework in
631 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800632 *
633 * @param uri The URI to query. This will be the full URI sent by the client;
634 * if the client is requesting a specific record, the URI will end in a record number
635 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
636 * that _id value.
637 * @param projection The list of columns to put into the cursor. If
638 * null all columns are included.
639 * @param selection A selection criteria to apply when filtering rows.
640 * If null then all rows are included.
641 * @param selectionArgs You may include ?s in selection, which will be replaced by
642 * the values from selectionArgs, in order that they appear in the selection.
643 * The values will be bound as Strings.
644 * @param sortOrder How the rows in the cursor should be sorted.
645 * If null then the provider is free to define the sort order.
Jeff Brown4c1241d2012-02-02 17:05:00 -0800646 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800647 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
648 * when the query is executed.
649 * @return a Cursor or null.
650 */
651 public Cursor query(Uri uri, String[] projection,
652 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800653 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800654 return query(uri, projection, selection, selectionArgs, sortOrder);
655 }
656
657 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700658 * Implement this to handle requests for the MIME type of the data at the
659 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 * <code>vnd.android.cursor.item</code> for a single record,
661 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700662 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800663 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
664 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700666 * <p>Note that there are no permissions needed for an application to
667 * access this information; if your content provider requires read and/or
668 * write permissions, or is not exported, all applications can still call
669 * this method regardless of their access permissions. This allows them
670 * to retrieve the MIME type for a URI when dispatching intents.
671 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 * @param uri the URI to query.
673 * @return a MIME type string, or null if there is no type.
674 */
675 public abstract String getType(Uri uri);
676
677 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700678 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
680 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700681 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800682 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
683 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 * @param uri The content:// URI of the insertion request.
685 * @param values A set of column_name/value pairs to add to the database.
686 * @return The URI for the newly inserted item.
687 */
688 public abstract Uri insert(Uri uri, ContentValues values);
689
690 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700691 * Override this to handle requests to insert a set of new rows, or the
692 * default implementation will iterate over the values and call
693 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
695 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700696 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800697 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
698 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 *
700 * @param uri The content:// URI of the insertion request.
701 * @param values An array of sets of column_name/value pairs to add to the database.
702 * @return The number of values that were inserted.
703 */
704 public int bulkInsert(Uri uri, ContentValues[] values) {
705 int numValues = values.length;
706 for (int i = 0; i < numValues; i++) {
707 insert(uri, values[i]);
708 }
709 return numValues;
710 }
711
712 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700713 * Implement this to handle requests to delete one or more rows.
714 * The implementation should apply the selection clause when performing
715 * deletion, allowing the operation to affect multiple rows in a directory.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyDelete()}
717 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700718 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800719 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
720 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 *
722 * <p>The implementation is responsible for parsing out a row ID at the end
723 * of the URI, if a specific row is being deleted. That is, the client would
724 * pass in <code>content://contacts/people/22</code> and the implementation is
725 * responsible for parsing the record number (22) when creating a SQL statement.
726 *
727 * @param uri The full URI to query, including a row ID (if a specific record is requested).
728 * @param selection An optional restriction to apply to rows when deleting.
729 * @return The number of rows affected.
730 * @throws SQLException
731 */
732 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
733
734 /**
Dan Egnor17876aa2010-07-28 12:28:04 -0700735 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700736 * The implementation should update all rows matching the selection
737 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
739 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700740 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800741 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
742 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 *
744 * @param uri The URI to query. This can potentially have a record ID if this
745 * is an update request for a specific record.
746 * @param values A Bundle mapping from column names to new column values (NULL is a
747 * valid value).
748 * @param selection An optional filter to match rows to update.
749 * @return the number of rows affected.
750 */
751 public abstract int update(Uri uri, ContentValues values, String selection,
752 String[] selectionArgs);
753
754 /**
Dan Egnor17876aa2010-07-28 12:28:04 -0700755 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700756 * The default implementation always throws {@link FileNotFoundException}.
757 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800758 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
759 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700760 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700761 * <p>This method returns a ParcelFileDescriptor, which is returned directly
762 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700763 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 *
765 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
766 * their responsibility to close it when done. That is, the implementation
767 * of this method should create a new ParcelFileDescriptor for each call.
768 *
769 * @param uri The URI whose file is to be opened.
770 * @param mode Access mode for the file. May be "r" for read-only access,
771 * "rw" for read and write access, or "rwt" for read and write access
772 * that truncates any existing file.
773 *
774 * @return Returns a new ParcelFileDescriptor which you can use to access
775 * the file.
776 *
777 * @throws FileNotFoundException Throws FileNotFoundException if there is
778 * no file associated with the given URI or the mode is invalid.
779 * @throws SecurityException Throws SecurityException if the caller does
780 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700781 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 * @see #openAssetFile(Uri, String)
783 * @see #openFileHelper(Uri, String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700784 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 public ParcelFileDescriptor openFile(Uri uri, String mode)
786 throws FileNotFoundException {
787 throw new FileNotFoundException("No files supported by provider at "
788 + uri);
789 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 /**
792 * This is like {@link #openFile}, but can be implemented by providers
793 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700794 * inside of their .apk.
795 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800796 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
797 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700798 *
799 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -0700800 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700801 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
803 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
804 * methods.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700805 *
806 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 * should create the AssetFileDescriptor with
808 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700809 * applications that can not handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 *
811 * @param uri The URI whose file is to be opened.
812 * @param mode Access mode for the file. May be "r" for read-only access,
813 * "w" for write-only access (erasing whatever data is currently in
814 * the file), "wa" for write-only access to append to any existing data,
815 * "rw" for read and write access on any existing data, and "rwt" for read
816 * and write access that truncates any existing file.
817 *
818 * @return Returns a new AssetFileDescriptor which you can use to access
819 * the file.
820 *
821 * @throws FileNotFoundException Throws FileNotFoundException if there is
822 * no file associated with the given URI or the mode is invalid.
823 * @throws SecurityException Throws SecurityException if the caller does
824 * not have permission to access the file.
825 *
826 * @see #openFile(Uri, String)
827 * @see #openFileHelper(Uri, String)
828 */
829 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
830 throws FileNotFoundException {
831 ParcelFileDescriptor fd = openFile(uri, mode);
832 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
833 }
834
835 /**
836 * Convenience for subclasses that wish to implement {@link #openFile}
837 * by looking up a column named "_data" at the given URI.
838 *
839 * @param uri The URI to be opened.
840 * @param mode The file mode. May be "r" for read-only access,
841 * "w" for write-only access (erasing whatever data is currently in
842 * the file), "wa" for write-only access to append to any existing data,
843 * "rw" for read and write access on any existing data, and "rwt" for read
844 * and write access that truncates any existing file.
845 *
846 * @return Returns a new ParcelFileDescriptor that can be used by the
847 * client to access the file.
848 */
849 protected final ParcelFileDescriptor openFileHelper(Uri uri,
850 String mode) throws FileNotFoundException {
851 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
852 int count = (c != null) ? c.getCount() : 0;
853 if (count != 1) {
854 // If there is not exactly one result, throw an appropriate
855 // exception.
856 if (c != null) {
857 c.close();
858 }
859 if (count == 0) {
860 throw new FileNotFoundException("No entry for " + uri);
861 }
862 throw new FileNotFoundException("Multiple items at " + uri);
863 }
864
865 c.moveToFirst();
866 int i = c.getColumnIndex("_data");
867 String path = (i >= 0 ? c.getString(i) : null);
868 c.close();
869 if (path == null) {
870 throw new FileNotFoundException("Column _data not found.");
871 }
872
873 int modeBits = ContentResolver.modeToMode(uri, mode);
874 return ParcelFileDescriptor.open(new File(path), modeBits);
875 }
876
877 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700878 * Called by a client to determine the types of data streams that this
879 * content provider supports for the given URI. The default implementation
880 * returns null, meaning no types. If your content provider stores data
881 * of a particular type, return that MIME type if it matches the given
882 * mimeTypeFilter. If it can perform type conversions, return an array
883 * of all supported MIME types that match mimeTypeFilter.
884 *
885 * @param uri The data in the content provider being queried.
886 * @param mimeTypeFilter The type of data the client desires. May be
887 * a pattern, such as *\/* to retrieve all possible data types.
Dianne Hackborn3f00be52010-08-15 18:03:27 -0700888 * @return Returns null if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700889 * given mimeTypeFilter. Otherwise returns an array of all available
890 * concrete MIME types.
891 *
892 * @see #getType(Uri)
893 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700894 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700895 */
896 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
897 return null;
898 }
899
900 /**
901 * Called by a client to open a read-only stream containing data of a
902 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
903 * except the file can only be read-only and the content provider may
904 * perform data conversions to generate data of the desired type.
905 *
906 * <p>The default implementation compares the given mimeType against the
907 * result of {@link #getType(Uri)} and, if the match, simple calls
908 * {@link #openAssetFile(Uri, String)}.
909 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700910 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700911 * of this method.
912 *
913 * @param uri The data in the content provider being queried.
914 * @param mimeTypeFilter The type of data the client desires. May be
915 * a pattern, such as *\/*, if the caller does not have specific type
916 * requirements; in this case the content provider will pick its best
917 * type matching the pattern.
918 * @param opts Additional options from the client. The definitions of
919 * these are specific to the content provider being called.
920 *
921 * @return Returns a new AssetFileDescriptor from which the client can
922 * read data of the desired type.
923 *
924 * @throws FileNotFoundException Throws FileNotFoundException if there is
925 * no file associated with the given URI or the mode is invalid.
926 * @throws SecurityException Throws SecurityException if the caller does
927 * not have permission to access the data.
928 * @throws IllegalArgumentException Throws IllegalArgumentException if the
929 * content provider does not support the requested MIME type.
930 *
931 * @see #getStreamTypes(Uri, String)
932 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700933 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700934 */
935 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
936 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -0700937 if ("*/*".equals(mimeTypeFilter)) {
938 // If they can take anything, the untyped open call is good enough.
939 return openAssetFile(uri, "r");
940 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700941 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700942 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -0700943 // Use old untyped open call if this provider has a type for this
944 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700945 return openAssetFile(uri, "r");
946 }
947 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
948 }
949
950 /**
951 * Interface to write a stream of data to a pipe. Use with
952 * {@link ContentProvider#openPipeHelper}.
953 */
954 public interface PipeDataWriter<T> {
955 /**
956 * Called from a background thread to stream data out to a pipe.
957 * Note that the pipe is blocking, so this thread can block on
958 * writes for an arbitrary amount of time if the client is slow
959 * at reading.
960 *
961 * @param output The pipe where data should be written. This will be
962 * closed for you upon returning from this function.
963 * @param uri The URI whose data is to be written.
964 * @param mimeType The desired type of data to be written.
965 * @param opts Options supplied by caller.
966 * @param args Your own custom arguments.
967 */
968 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
969 Bundle opts, T args);
970 }
971
972 /**
973 * A helper function for implementing {@link #openTypedAssetFile}, for
974 * creating a data pipe and background thread allowing you to stream
975 * generated data back to the client. This function returns a new
976 * ParcelFileDescriptor that should be returned to the caller (the caller
977 * is responsible for closing it).
978 *
979 * @param uri The URI whose data is to be written.
980 * @param mimeType The desired type of data to be written.
981 * @param opts Options supplied by caller.
982 * @param args Your own custom arguments.
983 * @param func Interface implementing the function that will actually
984 * stream the data.
985 * @return Returns a new ParcelFileDescriptor holding the read side of
986 * the pipe. This should be returned to the caller for reading; the caller
987 * is responsible for closing it when done.
988 */
989 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
990 final Bundle opts, final T args, final PipeDataWriter<T> func)
991 throws FileNotFoundException {
992 try {
993 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
994
995 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
996 @Override
997 protected Object doInBackground(Object... params) {
998 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
999 try {
1000 fds[1].close();
1001 } catch (IOException e) {
1002 Log.w(TAG, "Failure closing pipe", e);
1003 }
1004 return null;
1005 }
1006 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001007 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001008
1009 return fds[0];
1010 } catch (IOException e) {
1011 throw new FileNotFoundException("failure making pipe");
1012 }
1013 }
1014
1015 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 * Returns true if this instance is a temporary content provider.
1017 * @return true if this instance is a temporary content provider
1018 */
1019 protected boolean isTemporary() {
1020 return false;
1021 }
1022
1023 /**
1024 * Returns the Binder object for this provider.
1025 *
1026 * @return the Binder object for this provider
1027 * @hide
1028 */
1029 public IContentProvider getIContentProvider() {
1030 return mTransport;
1031 }
1032
1033 /**
1034 * After being instantiated, this is called to tell the content provider
1035 * about itself.
1036 *
1037 * @param context The context this provider is running in
1038 * @param info Registered information about this content provider
1039 */
1040 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001041 /*
1042 * We may be using AsyncTask from binder threads. Make it init here
1043 * so its static handler is on the main thread.
1044 */
1045 AsyncTask.init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046
1047 /*
1048 * Only allow it to be set once, so after the content service gives
1049 * this to us clients can't change it.
1050 */
1051 if (mContext == null) {
1052 mContext = context;
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001053 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 if (info != null) {
1055 setReadPermission(info.readPermission);
1056 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001057 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001058 mExported = info.exported;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 }
1060 ContentProvider.this.onCreate();
1061 }
1062 }
Fred Quintanace31b232009-05-04 16:01:15 -07001063
1064 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001065 * Override this to handle requests to perform a batch of operations, or the
1066 * default implementation will iterate over the operations and call
1067 * {@link ContentProviderOperation#apply} on each of them.
1068 * If all calls to {@link ContentProviderOperation#apply} succeed
1069 * then a {@link ContentProviderResult} array with as many
1070 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001071 * fail, it is up to the implementation how many of the others take effect.
1072 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001073 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1074 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001075 *
Fred Quintanace31b232009-05-04 16:01:15 -07001076 * @param operations the operations to apply
1077 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001078 * @throws OperationApplicationException thrown if any operation fails.
1079 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001080 */
Fred Quintana03d94902009-05-22 14:23:31 -07001081 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001082 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001083 final int numOperations = operations.size();
1084 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1085 for (int i = 0; i < numOperations; i++) {
1086 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001087 }
1088 return results;
1089 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001090
1091 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001092 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001093 * interfaces that are cheaper and/or unnatural for a table-like
1094 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001095 *
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001096 * @param method method name to call. Opaque to framework, but should not be null.
1097 * @param arg provider-defined String argument. May be null.
1098 * @param extras provider-defined Bundle argument. May be null.
1099 * @return provider-defined return value. May be null. Null is also
1100 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001101 */
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001102 public Bundle call(String method, String arg, Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001103 return null;
1104 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001105
1106 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001107 * Implement this to shut down the ContentProvider instance. You can then
1108 * invoke this method in unit tests.
1109 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001110 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001111 * Android normally handles ContentProvider startup and shutdown
1112 * automatically. You do not need to start up or shut down a
1113 * ContentProvider. When you invoke a test method on a ContentProvider,
1114 * however, a ContentProvider instance is started and keeps running after
1115 * the test finishes, even if a succeeding test instantiates another
1116 * ContentProvider. A conflict develops because the two instances are
1117 * usually running against the same underlying data source (for example, an
1118 * sqlite database).
1119 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001120 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001121 * Implementing shutDown() avoids this conflict by providing a way to
1122 * terminate the ContentProvider. This method can also prevent memory leaks
1123 * from multiple instantiations of the ContentProvider, and it can ensure
1124 * unit test isolation by allowing you to completely clean up the test
1125 * fixture before moving on to the next test.
1126 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001127 */
1128 public void shutdown() {
1129 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1130 "connections are gracefully shutdown");
1131 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001132
1133 /**
1134 * Print the Provider's state into the given stream. This gets invoked if
1135 * you run "adb shell dumpsys activity provider <provider_component_name>".
1136 *
1137 * @param prefix Desired prefix to prepend at each line of output.
1138 * @param fd The raw file descriptor that the dump is being sent to.
1139 * @param writer The PrintWriter to which you should dump your state. This will be
1140 * closed for you after you return.
1141 * @param args additional arguments to the dump request.
1142 * @hide
1143 */
1144 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1145 writer.println("nothing to dump");
1146 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001147}