blob: 05ef1947400fd38a6d40e9a9aafed7faad32e1be [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 Sharkeye5d49332012-03-13 12:13:17 -0700273 private void enforceReadPermission(Uri uri) throws SecurityException {
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();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700277 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700278
279 if (uid == mMyUid) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700280 return;
281 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700282
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700283 if (mExported) {
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700284 final String componentPerm = getReadPermission();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700285 if (componentPerm != null) {
286 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
287 return;
288 } else {
289 missingPerm = componentPerm;
290 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700291 }
292
293 // track if unprotected read is allowed; any denied
294 // <path-permission> below removes this ability
295 boolean allowDefaultRead = (componentPerm == null);
296
297 final PathPermission[] pps = getPathPermissions();
298 if (pps != null) {
299 final String path = uri.getPath();
300 for (PathPermission pp : pps) {
301 final String pathPerm = pp.getReadPermission();
302 if (pathPerm != null && pp.match(path)) {
303 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700304 return;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700305 } else {
306 // any denied <path-permission> means we lose
307 // default <provider> access.
308 allowDefaultRead = false;
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700309 missingPerm = pathPerm;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700310 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700311 }
312 }
313 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700314
315 // if we passed <path-permission> checks above, and no default
316 // <provider> permission, then allow access.
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700317 if (allowDefaultRead) return;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700318 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700319
320 // last chance, check against any uri grants
321 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION)
322 == PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 return;
324 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700325
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700326 final String failReason = mExported
327 ? " requires " + missingPerm + ", or grantUriPermission()"
328 : " requires the provider be exported, or grantUriPermission()";
329 throw new SecurityException("Permission Denial: reading "
330 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
331 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 }
333
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700334 private void enforceWritePermission(Uri uri) throws SecurityException {
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700335 final Context context = getContext();
336 final int pid = Binder.getCallingPid();
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700337 final int uid = Binder.getCallingUid();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700338 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700339
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700340 if (uid == mMyUid) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700341 return;
342 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700343
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700344 if (mExported) {
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700345 final String componentPerm = getWritePermission();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700346 if (componentPerm != null) {
347 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
348 return;
349 } else {
350 missingPerm = componentPerm;
351 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700352 }
353
354 // track if unprotected write is allowed; any denied
355 // <path-permission> below removes this ability
356 boolean allowDefaultWrite = (componentPerm == null);
357
358 final PathPermission[] pps = getPathPermissions();
359 if (pps != null) {
360 final String path = uri.getPath();
361 for (PathPermission pp : pps) {
362 final String pathPerm = pp.getWritePermission();
363 if (pathPerm != null && pp.match(path)) {
364 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700365 return;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700366 } else {
367 // any denied <path-permission> means we lose
368 // default <provider> access.
369 allowDefaultWrite = false;
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700370 missingPerm = pathPerm;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700371 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700372 }
373 }
374 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700375
376 // if we passed <path-permission> checks above, and no default
377 // <provider> permission, then allow access.
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700378 if (allowDefaultWrite) return;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700379 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700380
381 // last chance, check against any uri grants
382 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
383 == PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 return;
385 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700386
387 final String failReason = mExported
388 ? " requires " + missingPerm + ", or grantUriPermission()"
389 : " requires the provider be exported, or grantUriPermission()";
390 throw new SecurityException("Permission Denial: writing "
391 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
392 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393 }
394 }
395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700397 * Retrieves the Context this provider is running in. Only available once
398 * {@link #onCreate} has been called -- this will return null in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 * constructor.
400 */
401 public final Context getContext() {
402 return mContext;
403 }
404
405 /**
406 * Change the permission required to read data from the content
407 * provider. This is normally set for you from its manifest information
408 * when the provider is first created.
409 *
410 * @param permission Name of the permission required for read-only access.
411 */
412 protected final void setReadPermission(String permission) {
413 mReadPermission = permission;
414 }
415
416 /**
417 * Return the name of the permission required for read-only access to
418 * this content provider. This method can be called from multiple
419 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800420 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
421 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 */
423 public final String getReadPermission() {
424 return mReadPermission;
425 }
426
427 /**
428 * Change the permission required to read and write data in the content
429 * provider. This is normally set for you from its manifest information
430 * when the provider is first created.
431 *
432 * @param permission Name of the permission required for read/write access.
433 */
434 protected final void setWritePermission(String permission) {
435 mWritePermission = permission;
436 }
437
438 /**
439 * Return the name of the permission required for read/write access to
440 * this content provider. This method can be called from multiple
441 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800442 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
443 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 */
445 public final String getWritePermission() {
446 return mWritePermission;
447 }
448
449 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700450 * Change the path-based permission required to read and/or write data in
451 * the content provider. This is normally set for you from its manifest
452 * information when the provider is first created.
453 *
454 * @param permissions Array of path permission descriptions.
455 */
456 protected final void setPathPermissions(PathPermission[] permissions) {
457 mPathPermissions = permissions;
458 }
459
460 /**
461 * Return the path-based permissions required for read and/or write access to
462 * this content provider. This method can be called from multiple
463 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800464 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
465 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700466 */
467 public final PathPermission[] getPathPermissions() {
468 return mPathPermissions;
469 }
470
471 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700472 * Implement this to initialize your content provider on startup.
473 * This method is called for all registered content providers on the
474 * application main thread at application launch time. It must not perform
475 * lengthy operations, or application startup will be delayed.
476 *
477 * <p>You should defer nontrivial initialization (such as opening,
478 * upgrading, and scanning databases) until the content provider is used
479 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
480 * keeps application startup fast, avoids unnecessary work if the provider
481 * turns out not to be needed, and stops database errors (such as a full
482 * disk) from halting application launch.
483 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700484 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700485 * is a helpful utility class that makes it easy to manage databases,
486 * and will automatically defer opening until first use. If you do use
487 * SQLiteOpenHelper, make sure to avoid calling
488 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
489 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
490 * from this method. (Instead, override
491 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
492 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 *
494 * @return true if the provider was successfully loaded, false otherwise
495 */
496 public abstract boolean onCreate();
497
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700498 /**
499 * {@inheritDoc}
500 * This method is always called on the application main thread, and must
501 * not perform lengthy operations.
502 *
503 * <p>The default content provider implementation does nothing.
504 * Override this method to take appropriate action.
505 * (Content providers do not usually care about things like screen
506 * orientation, but may want to know about locale changes.)
507 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 public void onConfigurationChanged(Configuration newConfig) {
509 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700510
511 /**
512 * {@inheritDoc}
513 * This method is always called on the application main thread, and must
514 * not perform lengthy operations.
515 *
516 * <p>The default content provider implementation does nothing.
517 * Subclasses may override this method to take appropriate action.
518 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 public void onLowMemory() {
520 }
521
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700522 public void onTrimMemory(int level) {
523 }
524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700526 * Implement this to handle query requests from clients.
527 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800528 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
529 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 * <p>
531 * Example client call:<p>
532 * <pre>// Request a specific record.
533 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000534 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 projection, // Which columns to return.
536 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000537 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 People.NAME + " ASC"); // Sort order.</pre>
539 * Example implementation:<p>
540 * <pre>// SQLiteQueryBuilder is a helper class that creates the
541 // proper SQL syntax for us.
542 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
543
544 // Set the table we're querying.
545 qBuilder.setTables(DATABASE_TABLE_NAME);
546
547 // If the query ends in a specific record number, we're
548 // being asked for a specific record, so set the
549 // WHERE clause in our query.
550 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
551 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
552 }
553
554 // Make the query.
555 Cursor c = qBuilder.query(mDb,
556 projection,
557 selection,
558 selectionArgs,
559 groupBy,
560 having,
561 sortOrder);
562 c.setNotificationUri(getContext().getContentResolver(), uri);
563 return c;</pre>
564 *
565 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000566 * if the client is requesting a specific record, the URI will end in a record number
567 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
568 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 * @param projection The list of columns to put into the cursor. If
570 * null all columns are included.
571 * @param selection A selection criteria to apply when filtering rows.
572 * If null then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000573 * @param selectionArgs You may include ?s in selection, which will be replaced by
574 * the values from selectionArgs, in order that they appear in the selection.
575 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 * @param sortOrder How the rows in the cursor should be sorted.
Alan Jones81a476f2009-05-21 12:32:17 +1000577 * If null then the provider is free to define the sort order.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 * @return a Cursor or null.
579 */
580 public abstract Cursor query(Uri uri, String[] projection,
581 String selection, String[] selectionArgs, String sortOrder);
582
Fred Quintana5bba6322009-10-05 14:21:12 -0700583 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800584 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800585 * This method can be called from multiple threads, as described in
586 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
587 * and Threads</a>.
588 * <p>
589 * Example client call:<p>
590 * <pre>// Request a specific record.
591 * Cursor managedCursor = managedQuery(
592 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
593 projection, // Which columns to return.
594 null, // WHERE clause.
595 null, // WHERE clause value substitution
596 People.NAME + " ASC"); // Sort order.</pre>
597 * Example implementation:<p>
598 * <pre>// SQLiteQueryBuilder is a helper class that creates the
599 // proper SQL syntax for us.
600 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
601
602 // Set the table we're querying.
603 qBuilder.setTables(DATABASE_TABLE_NAME);
604
605 // If the query ends in a specific record number, we're
606 // being asked for a specific record, so set the
607 // WHERE clause in our query.
608 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
609 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
610 }
611
612 // Make the query.
613 Cursor c = qBuilder.query(mDb,
614 projection,
615 selection,
616 selectionArgs,
617 groupBy,
618 having,
619 sortOrder);
620 c.setNotificationUri(getContext().getContentResolver(), uri);
621 return c;</pre>
622 * <p>
623 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800624 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
625 * signal to ensure correct operation on older versions of the Android Framework in
626 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800627 *
628 * @param uri The URI to query. This will be the full URI sent by the client;
629 * if the client is requesting a specific record, the URI will end in a record number
630 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
631 * that _id value.
632 * @param projection The list of columns to put into the cursor. If
633 * null all columns are included.
634 * @param selection A selection criteria to apply when filtering rows.
635 * If null then all rows are included.
636 * @param selectionArgs You may include ?s in selection, which will be replaced by
637 * the values from selectionArgs, in order that they appear in the selection.
638 * The values will be bound as Strings.
639 * @param sortOrder How the rows in the cursor should be sorted.
640 * If null then the provider is free to define the sort order.
Jeff Brown4c1241d2012-02-02 17:05:00 -0800641 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800642 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
643 * when the query is executed.
644 * @return a Cursor or null.
645 */
646 public Cursor query(Uri uri, String[] projection,
647 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800648 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800649 return query(uri, projection, selection, selectionArgs, sortOrder);
650 }
651
652 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700653 * Implement this to handle requests for the MIME type of the data at the
654 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 * <code>vnd.android.cursor.item</code> for a single record,
656 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700657 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800658 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
659 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700661 * <p>Note that there are no permissions needed for an application to
662 * access this information; if your content provider requires read and/or
663 * write permissions, or is not exported, all applications can still call
664 * this method regardless of their access permissions. This allows them
665 * to retrieve the MIME type for a URI when dispatching intents.
666 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 * @param uri the URI to query.
668 * @return a MIME type string, or null if there is no type.
669 */
670 public abstract String getType(Uri uri);
671
672 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700673 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
675 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700676 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800677 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
678 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 * @param uri The content:// URI of the insertion request.
680 * @param values A set of column_name/value pairs to add to the database.
681 * @return The URI for the newly inserted item.
682 */
683 public abstract Uri insert(Uri uri, ContentValues values);
684
685 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700686 * Override this to handle requests to insert a set of new rows, or the
687 * default implementation will iterate over the values and call
688 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
690 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700691 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800692 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
693 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 *
695 * @param uri The content:// URI of the insertion request.
696 * @param values An array of sets of column_name/value pairs to add to the database.
697 * @return The number of values that were inserted.
698 */
699 public int bulkInsert(Uri uri, ContentValues[] values) {
700 int numValues = values.length;
701 for (int i = 0; i < numValues; i++) {
702 insert(uri, values[i]);
703 }
704 return numValues;
705 }
706
707 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700708 * Implement this to handle requests to delete one or more rows.
709 * The implementation should apply the selection clause when performing
710 * deletion, allowing the operation to affect multiple rows in a directory.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyDelete()}
712 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700713 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800714 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
715 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 *
717 * <p>The implementation is responsible for parsing out a row ID at the end
718 * of the URI, if a specific row is being deleted. That is, the client would
719 * pass in <code>content://contacts/people/22</code> and the implementation is
720 * responsible for parsing the record number (22) when creating a SQL statement.
721 *
722 * @param uri The full URI to query, including a row ID (if a specific record is requested).
723 * @param selection An optional restriction to apply to rows when deleting.
724 * @return The number of rows affected.
725 * @throws SQLException
726 */
727 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
728
729 /**
Dan Egnor17876aa2010-07-28 12:28:04 -0700730 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700731 * The implementation should update all rows matching the selection
732 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
734 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700735 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800736 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
737 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 *
739 * @param uri The URI to query. This can potentially have a record ID if this
740 * is an update request for a specific record.
741 * @param values A Bundle mapping from column names to new column values (NULL is a
742 * valid value).
743 * @param selection An optional filter to match rows to update.
744 * @return the number of rows affected.
745 */
746 public abstract int update(Uri uri, ContentValues values, String selection,
747 String[] selectionArgs);
748
749 /**
Dan Egnor17876aa2010-07-28 12:28:04 -0700750 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700751 * The default implementation always throws {@link FileNotFoundException}.
752 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800753 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
754 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700755 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700756 * <p>This method returns a ParcelFileDescriptor, which is returned directly
757 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700758 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 *
760 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
761 * their responsibility to close it when done. That is, the implementation
762 * of this method should create a new ParcelFileDescriptor for each call.
763 *
764 * @param uri The URI whose file is to be opened.
765 * @param mode Access mode for the file. May be "r" for read-only access,
766 * "rw" for read and write access, or "rwt" for read and write access
767 * that truncates any existing file.
768 *
769 * @return Returns a new ParcelFileDescriptor which you can use to access
770 * the file.
771 *
772 * @throws FileNotFoundException Throws FileNotFoundException if there is
773 * no file associated with the given URI or the mode is invalid.
774 * @throws SecurityException Throws SecurityException if the caller does
775 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700776 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 * @see #openAssetFile(Uri, String)
778 * @see #openFileHelper(Uri, String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700779 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 public ParcelFileDescriptor openFile(Uri uri, String mode)
781 throws FileNotFoundException {
782 throw new FileNotFoundException("No files supported by provider at "
783 + uri);
784 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 /**
787 * This is like {@link #openFile}, but can be implemented by providers
788 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700789 * inside of their .apk.
790 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800791 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
792 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700793 *
794 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -0700795 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700796 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
798 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
799 * methods.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700800 *
801 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 * should create the AssetFileDescriptor with
803 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700804 * applications that can not handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 *
806 * @param uri The URI whose file is to be opened.
807 * @param mode Access mode for the file. May be "r" for read-only access,
808 * "w" for write-only access (erasing whatever data is currently in
809 * the file), "wa" for write-only access to append to any existing data,
810 * "rw" for read and write access on any existing data, and "rwt" for read
811 * and write access that truncates any existing file.
812 *
813 * @return Returns a new AssetFileDescriptor which you can use to access
814 * the file.
815 *
816 * @throws FileNotFoundException Throws FileNotFoundException if there is
817 * no file associated with the given URI or the mode is invalid.
818 * @throws SecurityException Throws SecurityException if the caller does
819 * not have permission to access the file.
820 *
821 * @see #openFile(Uri, String)
822 * @see #openFileHelper(Uri, String)
823 */
824 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
825 throws FileNotFoundException {
826 ParcelFileDescriptor fd = openFile(uri, mode);
827 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
828 }
829
830 /**
831 * Convenience for subclasses that wish to implement {@link #openFile}
832 * by looking up a column named "_data" at the given URI.
833 *
834 * @param uri The URI to be opened.
835 * @param mode The file mode. May be "r" for read-only access,
836 * "w" for write-only access (erasing whatever data is currently in
837 * the file), "wa" for write-only access to append to any existing data,
838 * "rw" for read and write access on any existing data, and "rwt" for read
839 * and write access that truncates any existing file.
840 *
841 * @return Returns a new ParcelFileDescriptor that can be used by the
842 * client to access the file.
843 */
844 protected final ParcelFileDescriptor openFileHelper(Uri uri,
845 String mode) throws FileNotFoundException {
846 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
847 int count = (c != null) ? c.getCount() : 0;
848 if (count != 1) {
849 // If there is not exactly one result, throw an appropriate
850 // exception.
851 if (c != null) {
852 c.close();
853 }
854 if (count == 0) {
855 throw new FileNotFoundException("No entry for " + uri);
856 }
857 throw new FileNotFoundException("Multiple items at " + uri);
858 }
859
860 c.moveToFirst();
861 int i = c.getColumnIndex("_data");
862 String path = (i >= 0 ? c.getString(i) : null);
863 c.close();
864 if (path == null) {
865 throw new FileNotFoundException("Column _data not found.");
866 }
867
868 int modeBits = ContentResolver.modeToMode(uri, mode);
869 return ParcelFileDescriptor.open(new File(path), modeBits);
870 }
871
872 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700873 * Called by a client to determine the types of data streams that this
874 * content provider supports for the given URI. The default implementation
875 * returns null, meaning no types. If your content provider stores data
876 * of a particular type, return that MIME type if it matches the given
877 * mimeTypeFilter. If it can perform type conversions, return an array
878 * of all supported MIME types that match mimeTypeFilter.
879 *
880 * @param uri The data in the content provider being queried.
881 * @param mimeTypeFilter The type of data the client desires. May be
882 * a pattern, such as *\/* to retrieve all possible data types.
Dianne Hackborn3f00be52010-08-15 18:03:27 -0700883 * @return Returns null if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700884 * given mimeTypeFilter. Otherwise returns an array of all available
885 * concrete MIME types.
886 *
887 * @see #getType(Uri)
888 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700889 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700890 */
891 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
892 return null;
893 }
894
895 /**
896 * Called by a client to open a read-only stream containing data of a
897 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
898 * except the file can only be read-only and the content provider may
899 * perform data conversions to generate data of the desired type.
900 *
901 * <p>The default implementation compares the given mimeType against the
902 * result of {@link #getType(Uri)} and, if the match, simple calls
903 * {@link #openAssetFile(Uri, String)}.
904 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700905 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700906 * of this method.
907 *
908 * @param uri The data in the content provider being queried.
909 * @param mimeTypeFilter The type of data the client desires. May be
910 * a pattern, such as *\/*, if the caller does not have specific type
911 * requirements; in this case the content provider will pick its best
912 * type matching the pattern.
913 * @param opts Additional options from the client. The definitions of
914 * these are specific to the content provider being called.
915 *
916 * @return Returns a new AssetFileDescriptor from which the client can
917 * read data of the desired type.
918 *
919 * @throws FileNotFoundException Throws FileNotFoundException if there is
920 * no file associated with the given URI or the mode is invalid.
921 * @throws SecurityException Throws SecurityException if the caller does
922 * not have permission to access the data.
923 * @throws IllegalArgumentException Throws IllegalArgumentException if the
924 * content provider does not support the requested MIME type.
925 *
926 * @see #getStreamTypes(Uri, String)
927 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700928 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700929 */
930 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
931 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -0700932 if ("*/*".equals(mimeTypeFilter)) {
933 // If they can take anything, the untyped open call is good enough.
934 return openAssetFile(uri, "r");
935 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700936 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700937 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -0700938 // Use old untyped open call if this provider has a type for this
939 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700940 return openAssetFile(uri, "r");
941 }
942 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
943 }
944
945 /**
946 * Interface to write a stream of data to a pipe. Use with
947 * {@link ContentProvider#openPipeHelper}.
948 */
949 public interface PipeDataWriter<T> {
950 /**
951 * Called from a background thread to stream data out to a pipe.
952 * Note that the pipe is blocking, so this thread can block on
953 * writes for an arbitrary amount of time if the client is slow
954 * at reading.
955 *
956 * @param output The pipe where data should be written. This will be
957 * closed for you upon returning from this function.
958 * @param uri The URI whose data is to be written.
959 * @param mimeType The desired type of data to be written.
960 * @param opts Options supplied by caller.
961 * @param args Your own custom arguments.
962 */
963 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
964 Bundle opts, T args);
965 }
966
967 /**
968 * A helper function for implementing {@link #openTypedAssetFile}, for
969 * creating a data pipe and background thread allowing you to stream
970 * generated data back to the client. This function returns a new
971 * ParcelFileDescriptor that should be returned to the caller (the caller
972 * is responsible for closing it).
973 *
974 * @param uri The URI whose data is to be written.
975 * @param mimeType The desired type of data to be written.
976 * @param opts Options supplied by caller.
977 * @param args Your own custom arguments.
978 * @param func Interface implementing the function that will actually
979 * stream the data.
980 * @return Returns a new ParcelFileDescriptor holding the read side of
981 * the pipe. This should be returned to the caller for reading; the caller
982 * is responsible for closing it when done.
983 */
984 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
985 final Bundle opts, final T args, final PipeDataWriter<T> func)
986 throws FileNotFoundException {
987 try {
988 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
989
990 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
991 @Override
992 protected Object doInBackground(Object... params) {
993 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
994 try {
995 fds[1].close();
996 } catch (IOException e) {
997 Log.w(TAG, "Failure closing pipe", e);
998 }
999 return null;
1000 }
1001 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001002 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001003
1004 return fds[0];
1005 } catch (IOException e) {
1006 throw new FileNotFoundException("failure making pipe");
1007 }
1008 }
1009
1010 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 * Returns true if this instance is a temporary content provider.
1012 * @return true if this instance is a temporary content provider
1013 */
1014 protected boolean isTemporary() {
1015 return false;
1016 }
1017
1018 /**
1019 * Returns the Binder object for this provider.
1020 *
1021 * @return the Binder object for this provider
1022 * @hide
1023 */
1024 public IContentProvider getIContentProvider() {
1025 return mTransport;
1026 }
1027
1028 /**
1029 * After being instantiated, this is called to tell the content provider
1030 * about itself.
1031 *
1032 * @param context The context this provider is running in
1033 * @param info Registered information about this content provider
1034 */
1035 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001036 /*
1037 * We may be using AsyncTask from binder threads. Make it init here
1038 * so its static handler is on the main thread.
1039 */
1040 AsyncTask.init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041
1042 /*
1043 * Only allow it to be set once, so after the content service gives
1044 * this to us clients can't change it.
1045 */
1046 if (mContext == null) {
1047 mContext = context;
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001048 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 if (info != null) {
1050 setReadPermission(info.readPermission);
1051 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001052 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001053 mExported = info.exported;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 }
1055 ContentProvider.this.onCreate();
1056 }
1057 }
Fred Quintanace31b232009-05-04 16:01:15 -07001058
1059 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001060 * Override this to handle requests to perform a batch of operations, or the
1061 * default implementation will iterate over the operations and call
1062 * {@link ContentProviderOperation#apply} on each of them.
1063 * If all calls to {@link ContentProviderOperation#apply} succeed
1064 * then a {@link ContentProviderResult} array with as many
1065 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001066 * fail, it is up to the implementation how many of the others take effect.
1067 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001068 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1069 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001070 *
Fred Quintanace31b232009-05-04 16:01:15 -07001071 * @param operations the operations to apply
1072 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001073 * @throws OperationApplicationException thrown if any operation fails.
1074 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001075 */
Fred Quintana03d94902009-05-22 14:23:31 -07001076 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001077 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001078 final int numOperations = operations.size();
1079 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1080 for (int i = 0; i < numOperations; i++) {
1081 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001082 }
1083 return results;
1084 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001085
1086 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001087 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001088 * interfaces that are cheaper and/or unnatural for a table-like
1089 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001090 *
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001091 * @param method method name to call. Opaque to framework, but should not be null.
1092 * @param arg provider-defined String argument. May be null.
1093 * @param extras provider-defined Bundle argument. May be null.
1094 * @return provider-defined return value. May be null. Null is also
1095 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001096 */
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001097 public Bundle call(String method, String arg, Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001098 return null;
1099 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001100
1101 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001102 * Implement this to shut down the ContentProvider instance. You can then
1103 * invoke this method in unit tests.
1104 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001105 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001106 * Android normally handles ContentProvider startup and shutdown
1107 * automatically. You do not need to start up or shut down a
1108 * ContentProvider. When you invoke a test method on a ContentProvider,
1109 * however, a ContentProvider instance is started and keeps running after
1110 * the test finishes, even if a succeeding test instantiates another
1111 * ContentProvider. A conflict develops because the two instances are
1112 * usually running against the same underlying data source (for example, an
1113 * sqlite database).
1114 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001115 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001116 * Implementing shutDown() avoids this conflict by providing a way to
1117 * terminate the ContentProvider. This method can also prevent memory leaks
1118 * from multiple instantiations of the ContentProvider, and it can ensure
1119 * unit test isolation by allowing you to completely clean up the test
1120 * fixture before moving on to the next test.
1121 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001122 */
1123 public void shutdown() {
1124 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1125 "connections are gracefully shutdown");
1126 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001127
1128 /**
1129 * Print the Provider's state into the given stream. This gets invoked if
1130 * you run "adb shell dumpsys activity provider <provider_component_name>".
1131 *
1132 * @param prefix Desired prefix to prepend at each line of output.
1133 * @param fd The raw file descriptor that the dump is being sent to.
1134 * @param writer The PrintWriter to which you should dump your state. This will be
1135 * closed for you after you return.
1136 * @param args additional arguments to the dump request.
1137 * @hide
1138 */
1139 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1140 writer.println("nothing to dump");
1141 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001142}