blob: c1411b0ed15166f91011559fa7e6915d0e243392 [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;
Jeff Browna7771df2012-05-07 20:06:46 -070032import android.os.CancellationSignal;
33import android.os.ICancellationSignal;
34import android.os.OperationCanceledException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070036import android.os.Process;
Jeff Brown75ea64f2012-01-25 19:37:13 -080037import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070038import android.os.UserHandle;
Vasu Nori0c9e14a2010-08-04 13:31:48 -070039import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040
41import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080042import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070044import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080045import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070046import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047
48/**
49 * Content providers are one of the primary building blocks of Android applications, providing
50 * content to applications. They encapsulate data and provide it to applications through the single
51 * {@link ContentResolver} interface. A content provider is only required if you need to share
52 * data between multiple applications. For example, the contacts data is used by multiple
53 * applications and must be stored in a content provider. If you don't need to share data amongst
54 * multiple applications you can use a database directly via
55 * {@link android.database.sqlite.SQLiteDatabase}.
56 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057 * <p>When a request is made via
58 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
59 * request to the content provider registered with the authority. The content provider can interpret
60 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
61 * URIs.</p>
62 *
63 * <p>The primary methods that need to be implemented are:
64 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070065 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 * <li>{@link #query} which returns data to the caller</li>
67 * <li>{@link #insert} which inserts new data into the content provider</li>
68 * <li>{@link #update} which updates existing data in the content provider</li>
69 * <li>{@link #delete} which deletes data from the content provider</li>
70 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
71 * </ul></p>
72 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070073 * <p class="caution">Data access methods (such as {@link #insert} and
74 * {@link #update}) may be called from many threads at once, and must be thread-safe.
75 * Other methods (such as {@link #onCreate}) are only called from the application
76 * main thread, and must avoid performing lengthy operations. See the method
77 * descriptions for their expected thread behavior.</p>
78 *
79 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
80 * ContentProvider instance, so subclasses don't have to worry about the details of
81 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070082 *
83 * <div class="special reference">
84 * <h3>Developer Guides</h3>
85 * <p>For more information about using content providers, read the
86 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
87 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -070089public abstract class ContentProvider implements ComponentCallbacks2 {
Vasu Nori0c9e14a2010-08-04 13:31:48 -070090 private static final String TAG = "ContentProvider";
91
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +090092 /*
93 * Note: if you add methods to ContentProvider, you must add similar methods to
94 * MockContentProvider.
95 */
96
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070098 private int mMyUid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 private String mReadPermission;
100 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700101 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700102 private boolean mExported;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103
104 private Transport mTransport = new Transport();
105
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700106 /**
107 * Construct a ContentProvider instance. Content providers must be
108 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
109 * in the manifest</a>, accessed with {@link ContentResolver}, and created
110 * automatically by the system, so applications usually do not create
111 * ContentProvider instances directly.
112 *
113 * <p>At construction time, the object is uninitialized, and most fields and
114 * methods are unavailable. Subclasses should initialize themselves in
115 * {@link #onCreate}, not the constructor.
116 *
117 * <p>Content providers are created on the application main thread at
118 * application launch time. The constructor must not perform lengthy
119 * operations, or application startup will be delayed.
120 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900121 public ContentProvider() {
122 }
123
124 /**
125 * Constructor just for mocking.
126 *
127 * @param context A Context object which should be some mock instance (like the
128 * instance of {@link android.test.mock.MockContext}).
129 * @param readPermission The read permision you want this instance should have in the
130 * test, which is available via {@link #getReadPermission()}.
131 * @param writePermission The write permission you want this instance should have
132 * in the test, which is available via {@link #getWritePermission()}.
133 * @param pathPermissions The PathPermissions you want this instance should have
134 * in the test, which is available via {@link #getPathPermissions()}.
135 * @hide
136 */
137 public ContentProvider(
138 Context context,
139 String readPermission,
140 String writePermission,
141 PathPermission[] pathPermissions) {
142 mContext = context;
143 mReadPermission = readPermission;
144 mWritePermission = writePermission;
145 mPathPermissions = pathPermissions;
146 }
147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 /**
149 * Given an IContentProvider, try to coerce it back to the real
150 * ContentProvider object if it is running in the local process. This can
151 * be used if you know you are running in the same process as a provider,
152 * and want to get direct access to its implementation details. Most
153 * clients should not nor have a reason to use it.
154 *
155 * @param abstractInterface The ContentProvider interface that is to be
156 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800157 * @return If the IContentProvider is non-{@code null} and local, returns its actual
158 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 * @hide
160 */
161 public static ContentProvider coerceToLocalContentProvider(
162 IContentProvider abstractInterface) {
163 if (abstractInterface instanceof Transport) {
164 return ((Transport)abstractInterface).getContentProvider();
165 }
166 return null;
167 }
168
169 /**
170 * Binder object that deals with remoting.
171 *
172 * @hide
173 */
174 class Transport extends ContentProviderNative {
175 ContentProvider getContentProvider() {
176 return ContentProvider.this;
177 }
178
Jeff Brownd2183652011-10-09 12:39:53 -0700179 @Override
180 public String getProviderName() {
181 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 }
183
Jeff Brown75ea64f2012-01-25 19:37:13 -0800184 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 public Cursor query(Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800186 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800187 ICancellationSignal cancellationSignal) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700188 enforceReadPermission(uri);
Jeff Brown75ea64f2012-01-25 19:37:13 -0800189 return ContentProvider.this.query(uri, projection, selection, selectionArgs, sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800190 CancellationSignal.fromTransport(cancellationSignal));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 }
192
Jeff Brown75ea64f2012-01-25 19:37:13 -0800193 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 public String getType(Uri uri) {
195 return ContentProvider.this.getType(uri);
196 }
197
Jeff Brown75ea64f2012-01-25 19:37:13 -0800198 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 public Uri insert(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.insert(uri, initialValues);
202 }
203
Jeff Brown75ea64f2012-01-25 19:37:13 -0800204 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 public int bulkInsert(Uri uri, ContentValues[] initialValues) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700206 enforceWritePermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 return ContentProvider.this.bulkInsert(uri, initialValues);
208 }
209
Jeff Brown75ea64f2012-01-25 19:37:13 -0800210 @Override
Fred Quintana03d94902009-05-22 14:23:31 -0700211 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700212 throws OperationApplicationException {
213 for (ContentProviderOperation operation : operations) {
214 if (operation.isReadOperation()) {
Dianne Hackborne3f05442009-07-09 12:15:46 -0700215 enforceReadPermission(operation.getUri());
Fred Quintana89437372009-05-15 15:10:40 -0700216 }
217
218 if (operation.isWriteOperation()) {
Dianne Hackborne3f05442009-07-09 12:15:46 -0700219 enforceWritePermission(operation.getUri());
Fred Quintana89437372009-05-15 15:10:40 -0700220 }
221 }
222 return ContentProvider.this.applyBatch(operations);
Fred Quintana6a8d5332009-05-07 17:35:38 -0700223 }
224
Jeff Brown75ea64f2012-01-25 19:37:13 -0800225 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 public int delete(Uri uri, String selection, String[] selectionArgs) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700227 enforceWritePermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 return ContentProvider.this.delete(uri, selection, selectionArgs);
229 }
230
Jeff Brown75ea64f2012-01-25 19:37:13 -0800231 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 public int update(Uri uri, ContentValues values, String selection,
233 String[] selectionArgs) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700234 enforceWritePermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 return ContentProvider.this.update(uri, values, selection, selectionArgs);
236 }
237
Jeff Brown75ea64f2012-01-25 19:37:13 -0800238 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 public ParcelFileDescriptor openFile(Uri uri, String mode)
240 throws FileNotFoundException {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700241 if (mode != null && mode.startsWith("rw")) enforceWritePermission(uri);
242 else enforceReadPermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 return ContentProvider.this.openFile(uri, mode);
244 }
245
Jeff Brown75ea64f2012-01-25 19:37:13 -0800246 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
248 throws FileNotFoundException {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700249 if (mode != null && mode.startsWith("rw")) enforceWritePermission(uri);
250 else enforceReadPermission(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 return ContentProvider.this.openAssetFile(uri, mode);
252 }
253
Jeff Brown75ea64f2012-01-25 19:37:13 -0800254 @Override
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -0800255 public Bundle call(String method, String arg, Bundle extras) {
256 return ContentProvider.this.call(method, arg, extras);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800257 }
258
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700259 @Override
260 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
261 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
262 }
263
264 @Override
265 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeType, Bundle opts)
266 throws FileNotFoundException {
267 enforceReadPermission(uri);
268 return ContentProvider.this.openTypedAssetFile(uri, mimeType, opts);
269 }
270
Jeff Brown75ea64f2012-01-25 19:37:13 -0800271 @Override
Jeff Brown4c1241d2012-02-02 17:05:00 -0800272 public ICancellationSignal createCancellationSignal() throws RemoteException {
273 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800274 }
275
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700276 private void enforceReadPermission(Uri uri) throws SecurityException {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700277 final Context context = getContext();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 final int pid = Binder.getCallingPid();
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700279 final int uid = Binder.getCallingUid();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700280 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700281
Dianne Hackborn0d8af782012-08-17 16:51:54 -0700282 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700283 return;
284 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700285
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700286 if (mExported) {
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700287 final String componentPerm = getReadPermission();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700288 if (componentPerm != null) {
289 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
290 return;
291 } else {
292 missingPerm = componentPerm;
293 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700294 }
295
296 // track if unprotected read is allowed; any denied
297 // <path-permission> below removes this ability
298 boolean allowDefaultRead = (componentPerm == null);
299
300 final PathPermission[] pps = getPathPermissions();
301 if (pps != null) {
302 final String path = uri.getPath();
303 for (PathPermission pp : pps) {
304 final String pathPerm = pp.getReadPermission();
305 if (pathPerm != null && pp.match(path)) {
306 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700307 return;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700308 } else {
309 // any denied <path-permission> means we lose
310 // default <provider> access.
311 allowDefaultRead = false;
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700312 missingPerm = pathPerm;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700313 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700314 }
315 }
316 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700317
318 // if we passed <path-permission> checks above, and no default
319 // <provider> permission, then allow access.
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700320 if (allowDefaultRead) return;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700321 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700322
323 // last chance, check against any uri grants
324 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION)
325 == PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326 return;
327 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700328
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700329 final String failReason = mExported
330 ? " requires " + missingPerm + ", or grantUriPermission()"
331 : " requires the provider be exported, or grantUriPermission()";
332 throw new SecurityException("Permission Denial: reading "
333 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
334 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 }
336
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700337 private void enforceWritePermission(Uri uri) throws SecurityException {
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700338 final Context context = getContext();
339 final int pid = Binder.getCallingPid();
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700340 final int uid = Binder.getCallingUid();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700341 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700342
Dianne Hackborn0d8af782012-08-17 16:51:54 -0700343 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700344 return;
345 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700346
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700347 if (mExported) {
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700348 final String componentPerm = getWritePermission();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700349 if (componentPerm != null) {
350 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
351 return;
352 } else {
353 missingPerm = componentPerm;
354 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700355 }
356
357 // track if unprotected write is allowed; any denied
358 // <path-permission> below removes this ability
359 boolean allowDefaultWrite = (componentPerm == null);
360
361 final PathPermission[] pps = getPathPermissions();
362 if (pps != null) {
363 final String path = uri.getPath();
364 for (PathPermission pp : pps) {
365 final String pathPerm = pp.getWritePermission();
366 if (pathPerm != null && pp.match(path)) {
367 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700368 return;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700369 } else {
370 // any denied <path-permission> means we lose
371 // default <provider> access.
372 allowDefaultWrite = false;
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700373 missingPerm = pathPerm;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700374 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700375 }
376 }
377 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700378
379 // if we passed <path-permission> checks above, and no default
380 // <provider> permission, then allow access.
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700381 if (allowDefaultWrite) return;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700382 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700383
384 // last chance, check against any uri grants
385 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
386 == PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 return;
388 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700389
390 final String failReason = mExported
391 ? " requires " + missingPerm + ", or grantUriPermission()"
392 : " requires the provider be exported, or grantUriPermission()";
393 throw new SecurityException("Permission Denial: writing "
394 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
395 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800396 }
397 }
398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800399 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700400 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800401 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800402 * constructor.
403 */
404 public final Context getContext() {
405 return mContext;
406 }
407
408 /**
409 * Change the permission required to read data from the content
410 * provider. This is normally set for you from its manifest information
411 * when the provider is first created.
412 *
413 * @param permission Name of the permission required for read-only access.
414 */
415 protected final void setReadPermission(String permission) {
416 mReadPermission = permission;
417 }
418
419 /**
420 * Return the name of the permission required for read-only access to
421 * this content provider. This method can be called from multiple
422 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800423 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
424 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 */
426 public final String getReadPermission() {
427 return mReadPermission;
428 }
429
430 /**
431 * Change the permission required to read and write data in the content
432 * provider. This is normally set for you from its manifest information
433 * when the provider is first created.
434 *
435 * @param permission Name of the permission required for read/write access.
436 */
437 protected final void setWritePermission(String permission) {
438 mWritePermission = permission;
439 }
440
441 /**
442 * Return the name of the permission required for read/write access to
443 * this content provider. This method can be called from multiple
444 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800445 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
446 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 */
448 public final String getWritePermission() {
449 return mWritePermission;
450 }
451
452 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700453 * Change the path-based permission required to read and/or write data in
454 * the content provider. This is normally set for you from its manifest
455 * information when the provider is first created.
456 *
457 * @param permissions Array of path permission descriptions.
458 */
459 protected final void setPathPermissions(PathPermission[] permissions) {
460 mPathPermissions = permissions;
461 }
462
463 /**
464 * Return the path-based permissions required for read and/or write access to
465 * this content provider. This method can be called from multiple
466 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800467 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
468 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700469 */
470 public final PathPermission[] getPathPermissions() {
471 return mPathPermissions;
472 }
473
474 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700475 * Implement this to initialize your content provider on startup.
476 * This method is called for all registered content providers on the
477 * application main thread at application launch time. It must not perform
478 * lengthy operations, or application startup will be delayed.
479 *
480 * <p>You should defer nontrivial initialization (such as opening,
481 * upgrading, and scanning databases) until the content provider is used
482 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
483 * keeps application startup fast, avoids unnecessary work if the provider
484 * turns out not to be needed, and stops database errors (such as a full
485 * disk) from halting application launch.
486 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700487 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700488 * is a helpful utility class that makes it easy to manage databases,
489 * and will automatically defer opening until first use. If you do use
490 * SQLiteOpenHelper, make sure to avoid calling
491 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
492 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
493 * from this method. (Instead, override
494 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
495 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 *
497 * @return true if the provider was successfully loaded, false otherwise
498 */
499 public abstract boolean onCreate();
500
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700501 /**
502 * {@inheritDoc}
503 * This method is always called on the application main thread, and must
504 * not perform lengthy operations.
505 *
506 * <p>The default content provider implementation does nothing.
507 * Override this method to take appropriate action.
508 * (Content providers do not usually care about things like screen
509 * orientation, but may want to know about locale changes.)
510 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 public void onConfigurationChanged(Configuration newConfig) {
512 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700513
514 /**
515 * {@inheritDoc}
516 * This method is always called on the application main thread, and must
517 * not perform lengthy operations.
518 *
519 * <p>The default content provider implementation does nothing.
520 * Subclasses may override this method to take appropriate action.
521 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 public void onLowMemory() {
523 }
524
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700525 public void onTrimMemory(int level) {
526 }
527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700529 * Implement this to handle query requests from clients.
530 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800531 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
532 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 * <p>
534 * Example client call:<p>
535 * <pre>// Request a specific record.
536 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000537 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 projection, // Which columns to return.
539 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000540 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 People.NAME + " ASC"); // Sort order.</pre>
542 * Example implementation:<p>
543 * <pre>// SQLiteQueryBuilder is a helper class that creates the
544 // proper SQL syntax for us.
545 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
546
547 // Set the table we're querying.
548 qBuilder.setTables(DATABASE_TABLE_NAME);
549
550 // If the query ends in a specific record number, we're
551 // being asked for a specific record, so set the
552 // WHERE clause in our query.
553 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
554 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
555 }
556
557 // Make the query.
558 Cursor c = qBuilder.query(mDb,
559 projection,
560 selection,
561 selectionArgs,
562 groupBy,
563 having,
564 sortOrder);
565 c.setNotificationUri(getContext().getContentResolver(), uri);
566 return c;</pre>
567 *
568 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000569 * if the client is requesting a specific record, the URI will end in a record number
570 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
571 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800573 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800575 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000576 * @param selectionArgs You may include ?s in selection, which will be replaced by
577 * the values from selectionArgs, in order that they appear in the selection.
578 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800580 * If {@code null} then the provider is free to define the sort order.
581 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 */
583 public abstract Cursor query(Uri uri, String[] projection,
584 String selection, String[] selectionArgs, String sortOrder);
585
Fred Quintana5bba6322009-10-05 14:21:12 -0700586 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800587 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800588 * This method can be called from multiple threads, as described in
589 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
590 * and Threads</a>.
591 * <p>
592 * Example client call:<p>
593 * <pre>// Request a specific record.
594 * Cursor managedCursor = managedQuery(
595 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
596 projection, // Which columns to return.
597 null, // WHERE clause.
598 null, // WHERE clause value substitution
599 People.NAME + " ASC"); // Sort order.</pre>
600 * Example implementation:<p>
601 * <pre>// SQLiteQueryBuilder is a helper class that creates the
602 // proper SQL syntax for us.
603 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
604
605 // Set the table we're querying.
606 qBuilder.setTables(DATABASE_TABLE_NAME);
607
608 // If the query ends in a specific record number, we're
609 // being asked for a specific record, so set the
610 // WHERE clause in our query.
611 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
612 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
613 }
614
615 // Make the query.
616 Cursor c = qBuilder.query(mDb,
617 projection,
618 selection,
619 selectionArgs,
620 groupBy,
621 having,
622 sortOrder);
623 c.setNotificationUri(getContext().getContentResolver(), uri);
624 return c;</pre>
625 * <p>
626 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800627 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
628 * signal to ensure correct operation on older versions of the Android Framework in
629 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800630 *
631 * @param uri The URI to query. This will be the full URI sent by the client;
632 * if the client is requesting a specific record, the URI will end in a record number
633 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
634 * that _id value.
635 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800636 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800637 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800638 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800639 * @param selectionArgs You may include ?s in selection, which will be replaced by
640 * the values from selectionArgs, in order that they appear in the selection.
641 * The values will be bound as Strings.
642 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800643 * If {@code null} then the provider is free to define the sort order.
644 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800645 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
646 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800647 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800648 */
649 public Cursor query(Uri uri, String[] projection,
650 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800651 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800652 return query(uri, projection, selection, selectionArgs, sortOrder);
653 }
654
655 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700656 * Implement this to handle requests for the MIME type of the data at the
657 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 * <code>vnd.android.cursor.item</code> for a single record,
659 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700660 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800661 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
662 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700664 * <p>Note that there are no permissions needed for an application to
665 * access this information; if your content provider requires read and/or
666 * write permissions, or is not exported, all applications can still call
667 * this method regardless of their access permissions. This allows them
668 * to retrieve the MIME type for a URI when dispatching intents.
669 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800671 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 */
673 public abstract String getType(Uri uri);
674
675 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700676 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
678 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700679 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800680 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
681 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800682 * @param uri The content:// URI of the insertion request. This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800684 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 * @return The URI for the newly inserted item.
686 */
687 public abstract Uri insert(Uri uri, ContentValues values);
688
689 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700690 * Override this to handle requests to insert a set of new rows, or the
691 * default implementation will iterate over the values and call
692 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
694 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700695 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800696 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
697 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 *
699 * @param uri The content:// URI of the insertion request.
700 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800701 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 * @return The number of values that were inserted.
703 */
704 public int bulkInsert(Uri uri, ContentValues[] values) {
705 int numValues = values.length;
706 for (int i = 0; i < numValues; i++) {
707 insert(uri, values[i]);
708 }
709 return numValues;
710 }
711
712 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700713 * Implement this to handle requests to delete one or more rows.
714 * The implementation should apply the selection clause when performing
715 * deletion, allowing the operation to affect multiple rows in a directory.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyDelete()}
717 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700718 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800719 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
720 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 *
722 * <p>The implementation is responsible for parsing out a row ID at the end
723 * of the URI, if a specific row is being deleted. That is, the client would
724 * pass in <code>content://contacts/people/22</code> and the implementation is
725 * responsible for parsing the record number (22) when creating a SQL statement.
726 *
727 * @param uri The full URI to query, including a row ID (if a specific record is requested).
728 * @param selection An optional restriction to apply to rows when deleting.
729 * @return The number of rows affected.
730 * @throws SQLException
731 */
732 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
733
734 /**
Dan Egnor17876aa2010-07-28 12:28:04 -0700735 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700736 * The implementation should update all rows matching the selection
737 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
739 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700740 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800741 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
742 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 *
744 * @param uri The URI to query. This can potentially have a record ID if this
745 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800746 * @param values A set of column_name/value pairs to update in the database.
747 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 * @param selection An optional filter to match rows to update.
749 * @return the number of rows affected.
750 */
751 public abstract int update(Uri uri, ContentValues values, String selection,
752 String[] selectionArgs);
753
754 /**
Dan Egnor17876aa2010-07-28 12:28:04 -0700755 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700756 * The default implementation always throws {@link FileNotFoundException}.
757 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800758 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
759 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700760 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700761 * <p>This method returns a ParcelFileDescriptor, which is returned directly
762 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700763 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 *
765 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
766 * their responsibility to close it when done. That is, the implementation
767 * of this method should create a new ParcelFileDescriptor for each call.
768 *
769 * @param uri The URI whose file is to be opened.
770 * @param mode Access mode for the file. May be "r" for read-only access,
771 * "rw" for read and write access, or "rwt" for read and write access
772 * that truncates any existing file.
773 *
774 * @return Returns a new ParcelFileDescriptor which you can use to access
775 * the file.
776 *
777 * @throws FileNotFoundException Throws FileNotFoundException if there is
778 * no file associated with the given URI or the mode is invalid.
779 * @throws SecurityException Throws SecurityException if the caller does
780 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700781 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 * @see #openAssetFile(Uri, String)
783 * @see #openFileHelper(Uri, String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700784 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 public ParcelFileDescriptor openFile(Uri uri, String mode)
786 throws FileNotFoundException {
787 throw new FileNotFoundException("No files supported by provider at "
788 + uri);
789 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 /**
792 * This is like {@link #openFile}, but can be implemented by providers
793 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700794 * inside of their .apk.
795 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800796 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
797 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700798 *
799 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -0700800 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700801 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
803 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
804 * methods.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700805 *
806 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 * should create the AssetFileDescriptor with
808 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700809 * applications that can not handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 *
811 * @param uri The URI whose file is to be opened.
812 * @param mode Access mode for the file. May be "r" for read-only access,
813 * "w" for write-only access (erasing whatever data is currently in
814 * the file), "wa" for write-only access to append to any existing data,
815 * "rw" for read and write access on any existing data, and "rwt" for read
816 * and write access that truncates any existing file.
817 *
818 * @return Returns a new AssetFileDescriptor which you can use to access
819 * the file.
820 *
821 * @throws FileNotFoundException Throws FileNotFoundException if there is
822 * no file associated with the given URI or the mode is invalid.
823 * @throws SecurityException Throws SecurityException if the caller does
824 * not have permission to access the file.
825 *
826 * @see #openFile(Uri, String)
827 * @see #openFileHelper(Uri, String)
828 */
829 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
830 throws FileNotFoundException {
831 ParcelFileDescriptor fd = openFile(uri, mode);
832 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
833 }
834
835 /**
836 * Convenience for subclasses that wish to implement {@link #openFile}
837 * by looking up a column named "_data" at the given URI.
838 *
839 * @param uri The URI to be opened.
840 * @param mode The file mode. May be "r" for read-only access,
841 * "w" for write-only access (erasing whatever data is currently in
842 * the file), "wa" for write-only access to append to any existing data,
843 * "rw" for read and write access on any existing data, and "rwt" for read
844 * and write access that truncates any existing file.
845 *
846 * @return Returns a new ParcelFileDescriptor that can be used by the
847 * client to access the file.
848 */
849 protected final ParcelFileDescriptor openFileHelper(Uri uri,
850 String mode) throws FileNotFoundException {
851 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
852 int count = (c != null) ? c.getCount() : 0;
853 if (count != 1) {
854 // If there is not exactly one result, throw an appropriate
855 // exception.
856 if (c != null) {
857 c.close();
858 }
859 if (count == 0) {
860 throw new FileNotFoundException("No entry for " + uri);
861 }
862 throw new FileNotFoundException("Multiple items at " + uri);
863 }
864
865 c.moveToFirst();
866 int i = c.getColumnIndex("_data");
867 String path = (i >= 0 ? c.getString(i) : null);
868 c.close();
869 if (path == null) {
870 throw new FileNotFoundException("Column _data not found.");
871 }
872
873 int modeBits = ContentResolver.modeToMode(uri, mode);
874 return ParcelFileDescriptor.open(new File(path), modeBits);
875 }
876
877 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700878 * Called by a client to determine the types of data streams that this
879 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800880 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700881 * of a particular type, return that MIME type if it matches the given
882 * mimeTypeFilter. If it can perform type conversions, return an array
883 * of all supported MIME types that match mimeTypeFilter.
884 *
885 * @param uri The data in the content provider being queried.
886 * @param mimeTypeFilter The type of data the client desires. May be
887 * a pattern, such as *\/* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800888 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700889 * given mimeTypeFilter. Otherwise returns an array of all available
890 * concrete MIME types.
891 *
892 * @see #getType(Uri)
893 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700894 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700895 */
896 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
897 return null;
898 }
899
900 /**
901 * Called by a client to open a read-only stream containing data of a
902 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
903 * except the file can only be read-only and the content provider may
904 * perform data conversions to generate data of the desired type.
905 *
906 * <p>The default implementation compares the given mimeType against the
907 * result of {@link #getType(Uri)} and, if the match, simple calls
908 * {@link #openAssetFile(Uri, String)}.
909 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700910 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700911 * of this method.
912 *
913 * @param uri The data in the content provider being queried.
914 * @param mimeTypeFilter The type of data the client desires. May be
915 * a pattern, such as *\/*, if the caller does not have specific type
916 * requirements; in this case the content provider will pick its best
917 * type matching the pattern.
918 * @param opts Additional options from the client. The definitions of
919 * these are specific to the content provider being called.
920 *
921 * @return Returns a new AssetFileDescriptor from which the client can
922 * read data of the desired type.
923 *
924 * @throws FileNotFoundException Throws FileNotFoundException if there is
925 * no file associated with the given URI or the mode is invalid.
926 * @throws SecurityException Throws SecurityException if the caller does
927 * not have permission to access the data.
928 * @throws IllegalArgumentException Throws IllegalArgumentException if the
929 * content provider does not support the requested MIME type.
930 *
931 * @see #getStreamTypes(Uri, String)
932 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700933 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700934 */
935 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
936 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -0700937 if ("*/*".equals(mimeTypeFilter)) {
938 // If they can take anything, the untyped open call is good enough.
939 return openAssetFile(uri, "r");
940 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700941 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700942 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -0700943 // Use old untyped open call if this provider has a type for this
944 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700945 return openAssetFile(uri, "r");
946 }
947 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
948 }
949
950 /**
951 * Interface to write a stream of data to a pipe. Use with
952 * {@link ContentProvider#openPipeHelper}.
953 */
954 public interface PipeDataWriter<T> {
955 /**
956 * Called from a background thread to stream data out to a pipe.
957 * Note that the pipe is blocking, so this thread can block on
958 * writes for an arbitrary amount of time if the client is slow
959 * at reading.
960 *
961 * @param output The pipe where data should be written. This will be
962 * closed for you upon returning from this function.
963 * @param uri The URI whose data is to be written.
964 * @param mimeType The desired type of data to be written.
965 * @param opts Options supplied by caller.
966 * @param args Your own custom arguments.
967 */
968 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
969 Bundle opts, T args);
970 }
971
972 /**
973 * A helper function for implementing {@link #openTypedAssetFile}, for
974 * creating a data pipe and background thread allowing you to stream
975 * generated data back to the client. This function returns a new
976 * ParcelFileDescriptor that should be returned to the caller (the caller
977 * is responsible for closing it).
978 *
979 * @param uri The URI whose data is to be written.
980 * @param mimeType The desired type of data to be written.
981 * @param opts Options supplied by caller.
982 * @param args Your own custom arguments.
983 * @param func Interface implementing the function that will actually
984 * stream the data.
985 * @return Returns a new ParcelFileDescriptor holding the read side of
986 * the pipe. This should be returned to the caller for reading; the caller
987 * is responsible for closing it when done.
988 */
989 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
990 final Bundle opts, final T args, final PipeDataWriter<T> func)
991 throws FileNotFoundException {
992 try {
993 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
994
995 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
996 @Override
997 protected Object doInBackground(Object... params) {
998 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
999 try {
1000 fds[1].close();
1001 } catch (IOException e) {
1002 Log.w(TAG, "Failure closing pipe", e);
1003 }
1004 return null;
1005 }
1006 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001007 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001008
1009 return fds[0];
1010 } catch (IOException e) {
1011 throw new FileNotFoundException("failure making pipe");
1012 }
1013 }
1014
1015 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 * Returns true if this instance is a temporary content provider.
1017 * @return true if this instance is a temporary content provider
1018 */
1019 protected boolean isTemporary() {
1020 return false;
1021 }
1022
1023 /**
1024 * Returns the Binder object for this provider.
1025 *
1026 * @return the Binder object for this provider
1027 * @hide
1028 */
1029 public IContentProvider getIContentProvider() {
1030 return mTransport;
1031 }
1032
1033 /**
1034 * After being instantiated, this is called to tell the content provider
1035 * about itself.
1036 *
1037 * @param context The context this provider is running in
1038 * @param info Registered information about this content provider
1039 */
1040 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001041 /*
1042 * We may be using AsyncTask from binder threads. Make it init here
1043 * so its static handler is on the main thread.
1044 */
1045 AsyncTask.init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046
1047 /*
1048 * Only allow it to be set once, so after the content service gives
1049 * this to us clients can't change it.
1050 */
1051 if (mContext == null) {
1052 mContext = context;
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001053 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 if (info != null) {
1055 setReadPermission(info.readPermission);
1056 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001057 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001058 mExported = info.exported;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 }
1060 ContentProvider.this.onCreate();
1061 }
1062 }
Fred Quintanace31b232009-05-04 16:01:15 -07001063
1064 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001065 * Override this to handle requests to perform a batch of operations, or the
1066 * default implementation will iterate over the operations and call
1067 * {@link ContentProviderOperation#apply} on each of them.
1068 * If all calls to {@link ContentProviderOperation#apply} succeed
1069 * then a {@link ContentProviderResult} array with as many
1070 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001071 * fail, it is up to the implementation how many of the others take effect.
1072 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001073 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1074 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001075 *
Fred Quintanace31b232009-05-04 16:01:15 -07001076 * @param operations the operations to apply
1077 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001078 * @throws OperationApplicationException thrown if any operation fails.
1079 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001080 */
Fred Quintana03d94902009-05-22 14:23:31 -07001081 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001082 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001083 final int numOperations = operations.size();
1084 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1085 for (int i = 0; i < numOperations; i++) {
1086 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001087 }
1088 return results;
1089 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001090
1091 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001092 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001093 * interfaces that are cheaper and/or unnatural for a table-like
1094 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001095 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001096 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1097 * @param arg provider-defined String argument. May be {@code null}.
1098 * @param extras provider-defined Bundle argument. May be {@code null}.
1099 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001100 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001101 */
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001102 public Bundle call(String method, String arg, Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001103 return null;
1104 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001105
1106 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001107 * Implement this to shut down the ContentProvider instance. You can then
1108 * invoke this method in unit tests.
1109 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001110 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001111 * Android normally handles ContentProvider startup and shutdown
1112 * automatically. You do not need to start up or shut down a
1113 * ContentProvider. When you invoke a test method on a ContentProvider,
1114 * however, a ContentProvider instance is started and keeps running after
1115 * the test finishes, even if a succeeding test instantiates another
1116 * ContentProvider. A conflict develops because the two instances are
1117 * usually running against the same underlying data source (for example, an
1118 * sqlite database).
1119 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001120 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001121 * Implementing shutDown() avoids this conflict by providing a way to
1122 * terminate the ContentProvider. This method can also prevent memory leaks
1123 * from multiple instantiations of the ContentProvider, and it can ensure
1124 * unit test isolation by allowing you to completely clean up the test
1125 * fixture before moving on to the next test.
1126 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001127 */
1128 public void shutdown() {
1129 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1130 "connections are gracefully shutdown");
1131 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001132
1133 /**
1134 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001135 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001136 *
1137 * @param prefix Desired prefix to prepend at each line of output.
1138 * @param fd The raw file descriptor that the dump is being sent to.
1139 * @param writer The PrintWriter to which you should dump your state. This will be
1140 * closed for you after you return.
1141 * @param args additional arguments to the dump request.
1142 * @hide
1143 */
1144 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1145 writer.println("nothing to dump");
1146 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001147}