blob: 12e3ccf883b6fc6c079eca6bfbad266cfb096fe9 [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
19import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070020import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.content.pm.ProviderInfo;
22import android.content.res.AssetFileDescriptor;
23import android.content.res.Configuration;
24import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.database.SQLException;
26import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070027import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080029import android.os.Bundle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070031import android.os.Process;
Jeff Brown75ea64f2012-01-25 19:37:13 -080032import android.os.RemoteException;
Vasu Nori0c9e14a2010-08-04 13:31:48 -070033import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034
35import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080036import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070038import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080039import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070040import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041
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 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051 * <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>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070059 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060 * <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 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070067 * <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>
Joe Fernandez558459f2011-10-13 16:47:36 -070076 *
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>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -070083public abstract class ContentProvider implements ComponentCallbacks2 {
Vasu Nori0c9e14a2010-08-04 13:31:48 -070084 private static final String TAG = "ContentProvider";
85
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +090086 /*
87 * Note: if you add methods to ContentProvider, you must add similar methods to
88 * MockContentProvider.
89 */
90
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070092 private int mMyUid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 private String mReadPermission;
94 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070095 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -070096 private boolean mExported;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097
98 private Transport mTransport = new Transport();
99
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700100 /**
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 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900115 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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 /**
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
Jeff Brownd2183652011-10-09 12:39:53 -0700173 @Override
174 public String getProviderName() {
175 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 }
177
Jeff Brown75ea64f2012-01-25 19:37:13 -0800178 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 public Cursor query(Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800180 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800181 ICancellationSignal cancellationSignal) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700182 enforceReadPermission(uri);
Jeff Brown75ea64f2012-01-25 19:37:13 -0800183 return ContentProvider.this.query(uri, projection, selection, selectionArgs, sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800184 CancellationSignal.fromTransport(cancellationSignal));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 }
186
Jeff Brown75ea64f2012-01-25 19:37:13 -0800187 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 public String getType(Uri uri) {
189 return ContentProvider.this.getType(uri);
190 }
191
Jeff Brown75ea64f2012-01-25 19:37:13 -0800192 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 public Uri insert(Uri uri, ContentValues initialValues) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700194 enforceWritePermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 return ContentProvider.this.insert(uri, initialValues);
196 }
197
Jeff Brown75ea64f2012-01-25 19:37:13 -0800198 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 public int bulkInsert(Uri uri, ContentValues[] initialValues) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700200 enforceWritePermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 return ContentProvider.this.bulkInsert(uri, initialValues);
202 }
203
Jeff Brown75ea64f2012-01-25 19:37:13 -0800204 @Override
Fred Quintana03d94902009-05-22 14:23:31 -0700205 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700206 throws OperationApplicationException {
207 for (ContentProviderOperation operation : operations) {
208 if (operation.isReadOperation()) {
Dianne Hackborne3f05442009-07-09 12:15:46 -0700209 enforceReadPermission(operation.getUri());
Fred Quintana89437372009-05-15 15:10:40 -0700210 }
211
212 if (operation.isWriteOperation()) {
Dianne Hackborne3f05442009-07-09 12:15:46 -0700213 enforceWritePermission(operation.getUri());
Fred Quintana89437372009-05-15 15:10:40 -0700214 }
215 }
216 return ContentProvider.this.applyBatch(operations);
Fred Quintana6a8d5332009-05-07 17:35:38 -0700217 }
218
Jeff Brown75ea64f2012-01-25 19:37:13 -0800219 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 public int delete(Uri uri, String selection, String[] selectionArgs) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700221 enforceWritePermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 return ContentProvider.this.delete(uri, selection, selectionArgs);
223 }
224
Jeff Brown75ea64f2012-01-25 19:37:13 -0800225 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 public int update(Uri uri, ContentValues values, String selection,
227 String[] selectionArgs) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700228 enforceWritePermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 return ContentProvider.this.update(uri, values, selection, selectionArgs);
230 }
231
Jeff Brown75ea64f2012-01-25 19:37:13 -0800232 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 public ParcelFileDescriptor openFile(Uri uri, String mode)
234 throws FileNotFoundException {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700235 if (mode != null && mode.startsWith("rw")) enforceWritePermission(uri);
236 else enforceReadPermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 return ContentProvider.this.openFile(uri, mode);
238 }
239
Jeff Brown75ea64f2012-01-25 19:37:13 -0800240 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
242 throws FileNotFoundException {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700243 if (mode != null && mode.startsWith("rw")) enforceWritePermission(uri);
244 else enforceReadPermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 return ContentProvider.this.openAssetFile(uri, mode);
246 }
247
Jeff Brown75ea64f2012-01-25 19:37:13 -0800248 @Override
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -0800249 public Bundle call(String method, String arg, Bundle extras) {
250 return ContentProvider.this.call(method, arg, extras);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800251 }
252
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700253 @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
Jeff Brown75ea64f2012-01-25 19:37:13 -0800265 @Override
Jeff Brown4c1241d2012-02-02 17:05:00 -0800266 public ICancellationSignal createCancellationSignal() throws RemoteException {
267 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800268 }
269
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700270 private void enforceReadPermission(Uri uri) {
271 final int uid = Binder.getCallingUid();
272 if (uid == mMyUid) {
273 return;
274 }
275
276 final Context context = getContext();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 final String rperm = getReadPermission();
278 final int pid = Binder.getCallingPid();
Dianne Hackbornb424b632010-08-18 15:59:05 -0700279 if (mExported && (rperm == null
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700280 || context.checkPermission(rperm, pid, uid)
Dianne Hackbornb424b632010-08-18 15:59:05 -0700281 == PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700282 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,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 Intent.FLAG_GRANT_READ_URI_PERMISSION)
304 == PackageManager.PERMISSION_GRANTED) {
305 return;
306 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 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
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700316 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();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 final String wperm = getWritePermission();
324 final int pid = Binder.getCallingPid();
Dianne Hackbornb424b632010-08-18 15:59:05 -0700325 if (mExported && (wperm == null
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700326 || context.checkPermission(wperm, pid, uid)
Dianne Hackbornb424b632010-08-18 15:59:05 -0700327 == PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700328 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,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
350 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700351 return true;
352 }
353
354 return false;
355 }
356
357 private void enforceWritePermission(Uri uri) {
358 if (hasWritePermission(uri)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 return;
360 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 String msg = "Permission Denial: writing "
363 + ContentProvider.this.getClass().getName()
364 + " uri " + uri + " from pid=" + Binder.getCallingPid()
365 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700366 + " requires " + getWritePermission();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 throw new SecurityException(msg);
368 }
369 }
370
371
372 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700373 * Retrieves the Context this provider is running in. Only available once
374 * {@link #onCreate} has been called -- this will return null in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 * 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
Scott Main7aee61f2011-02-08 11:25:01 -0800396 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
397 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 */
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
Scott Main7aee61f2011-02-08 11:25:01 -0800418 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
419 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 */
421 public final String getWritePermission() {
422 return mWritePermission;
423 }
424
425 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700426 * 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
Scott Main7aee61f2011-02-08 11:25:01 -0800440 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
441 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700442 */
443 public final PathPermission[] getPathPermissions() {
444 return mPathPermissions;
445 }
446
447 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700448 * 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 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700460 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700461 * 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.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 *
470 * @return true if the provider was successfully loaded, false otherwise
471 */
472 public abstract boolean onCreate();
473
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700474 /**
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 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 public void onConfigurationChanged(Configuration newConfig) {
485 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700486
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 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 public void onLowMemory() {
496 }
497
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700498 public void onTrimMemory(int level) {
499 }
500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700502 * Implement this to handle query requests from clients.
503 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800504 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
505 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 * <p>
507 * Example client call:<p>
508 * <pre>// Request a specific record.
509 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000510 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 projection, // Which columns to return.
512 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000513 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 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;
Alan Jones81a476f2009-05-21 12:32:17 +1000542 * 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.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800545 * @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.
Alan Jones81a476f2009-05-21 12:32:17 +1000549 * @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.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 * @param sortOrder How the rows in the cursor should be sorted.
Alan Jones81a476f2009-05-21 12:32:17 +1000553 * If null then the provider is free to define the sort order.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 * @return a Cursor or null.
555 */
556 public abstract Cursor query(Uri uri, String[] projection,
557 String selection, String[] selectionArgs, String sortOrder);
558
Fred Quintana5bba6322009-10-05 14:21:12 -0700559 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800560 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800561 * 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
Jeff Brown4c1241d2012-02-02 17:05:00 -0800600 * {@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.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800603 *
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.
Jeff Brown4c1241d2012-02-02 17:05:00 -0800617 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800618 * 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,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800624 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800625 return query(uri, projection, selection, selectionArgs, sortOrder);
626 }
627
628 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700629 * Implement this to handle requests for the MIME type of the data at the
630 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 * <code>vnd.android.cursor.item</code> for a single record,
632 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700633 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800634 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
635 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700637 * <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 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 * @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 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700649 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
651 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700652 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800653 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
654 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 * @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 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700662 * 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.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
666 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700667 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800668 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
669 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 *
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 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700684 * 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.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyDelete()}
688 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700689 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800690 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
691 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 *
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 /**
Dan Egnor17876aa2010-07-28 12:28:04 -0700706 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700707 * The implementation should update all rows matching the selection
708 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
710 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700711 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800712 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
713 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 *
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 /**
Dan Egnor17876aa2010-07-28 12:28:04 -0700726 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700727 * The default implementation always throws {@link FileNotFoundException}.
728 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800729 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
730 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700731 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700732 * <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
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700734 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 *
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.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700752 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 * @see #openAssetFile(Uri, String)
754 * @see #openFileHelper(Uri, String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700755 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 public ParcelFileDescriptor openFile(Uri uri, String mode)
757 throws FileNotFoundException {
758 throw new FileNotFoundException("No files supported by provider at "
759 + uri);
760 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 /**
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
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700765 * inside of their .apk.
766 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800767 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
768 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700769 *
770 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -0700771 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700772 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
774 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
775 * methods.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700776 *
777 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 * should create the AssetFileDescriptor with
779 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700780 * applications that can not handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 *
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 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700849 * 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.
Dianne Hackborn3f00be52010-08-15 18:03:27 -0700859 * @return Returns null if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700860 * given mimeTypeFilter. Otherwise returns an array of all available
861 * concrete MIME types.
862 *
863 * @see #getType(Uri)
864 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700865 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700866 */
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 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700881 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700882 * 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)
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700904 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700905 */
906 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
907 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -0700908 if ("*/*".equals(mimeTypeFilter)) {
909 // If they can take anything, the untyped open call is good enough.
910 return openAssetFile(uri, "r");
911 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700912 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700913 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -0700914 // Use old untyped open call if this provider has a type for this
915 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700916 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 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -0800978 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700979
980 return fds[0];
981 } catch (IOException e) {
982 throw new FileNotFoundException("failure making pipe");
983 }
984 }
985
986 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 * 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) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001012 /*
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();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017
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;
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001024 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 if (info != null) {
1026 setReadPermission(info.readPermission);
1027 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001028 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001029 mExported = info.exported;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 }
1031 ContentProvider.this.onCreate();
1032 }
1033 }
Fred Quintanace31b232009-05-04 16:01:15 -07001034
1035 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001036 * 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
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001042 * 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
Scott Main7aee61f2011-02-08 11:25:01 -08001044 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1045 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001046 *
Fred Quintanace31b232009-05-04 16:01:15 -07001047 * @param operations the operations to apply
1048 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001049 * @throws OperationApplicationException thrown if any operation fails.
1050 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001051 */
Fred Quintana03d94902009-05-22 14:23:31 -07001052 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001053 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001054 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);
Fred Quintanace31b232009-05-04 16:01:15 -07001058 }
1059 return results;
1060 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001061
1062 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001063 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001064 * interfaces that are cheaper and/or unnatural for a table-like
1065 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001066 *
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001067 * @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.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001072 */
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001073 public Bundle call(String method, String arg, Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001074 return null;
1075 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001076
1077 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001078 * Implement this to shut down the ContentProvider instance. You can then
1079 * invoke this method in unit tests.
1080 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001081 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001082 * 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>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001091 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001092 * 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>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001098 */
1099 public void shutdown() {
1100 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1101 "connections are gracefully shutdown");
1102 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001103
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 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001118}