blob: 4b977ab5fe1df46e79af44813b1a6b9185feb208 [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
Dianne Hackborn35654b62013-01-14 17:38:02 -080021import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070023import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.pm.ProviderInfo;
25import android.content.res.AssetFileDescriptor;
26import android.content.res.Configuration;
27import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.database.SQLException;
29import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070030import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080032import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070033import android.os.CancellationSignal;
34import android.os.ICancellationSignal;
35import android.os.OperationCanceledException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070037import android.os.Process;
Jeff Brown75ea64f2012-01-25 19:37:13 -080038import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070039import android.os.UserHandle;
Vasu Nori0c9e14a2010-08-04 13:31:48 -070040import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041
42import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080043import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070045import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080046import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070047import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048
49/**
50 * Content providers are one of the primary building blocks of Android applications, providing
51 * content to applications. They encapsulate data and provide it to applications through the single
52 * {@link ContentResolver} interface. A content provider is only required if you need to share
53 * data between multiple applications. For example, the contacts data is used by multiple
54 * applications and must be stored in a content provider. If you don't need to share data amongst
55 * multiple applications you can use a database directly via
56 * {@link android.database.sqlite.SQLiteDatabase}.
57 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058 * <p>When a request is made via
59 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
60 * request to the content provider registered with the authority. The content provider can interpret
61 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
62 * URIs.</p>
63 *
64 * <p>The primary methods that need to be implemented are:
65 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070066 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 * <li>{@link #query} which returns data to the caller</li>
68 * <li>{@link #insert} which inserts new data into the content provider</li>
69 * <li>{@link #update} which updates existing data in the content provider</li>
70 * <li>{@link #delete} which deletes data from the content provider</li>
71 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
72 * </ul></p>
73 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070074 * <p class="caution">Data access methods (such as {@link #insert} and
75 * {@link #update}) may be called from many threads at once, and must be thread-safe.
76 * Other methods (such as {@link #onCreate}) are only called from the application
77 * main thread, and must avoid performing lengthy operations. See the method
78 * descriptions for their expected thread behavior.</p>
79 *
80 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
81 * ContentProvider instance, so subclasses don't have to worry about the details of
82 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070083 *
84 * <div class="special reference">
85 * <h3>Developer Guides</h3>
86 * <p>For more information about using content providers, read the
87 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
88 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -070090public abstract class ContentProvider implements ComponentCallbacks2 {
Vasu Nori0c9e14a2010-08-04 13:31:48 -070091 private static final String TAG = "ContentProvider";
92
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +090093 /*
94 * Note: if you add methods to ContentProvider, you must add similar methods to
95 * MockContentProvider.
96 */
97
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070099 private int mMyUid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 private String mReadPermission;
101 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700102 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700103 private boolean mExported;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
105 private Transport mTransport = new Transport();
106
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700107 /**
108 * Construct a ContentProvider instance. Content providers must be
109 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
110 * in the manifest</a>, accessed with {@link ContentResolver}, and created
111 * automatically by the system, so applications usually do not create
112 * ContentProvider instances directly.
113 *
114 * <p>At construction time, the object is uninitialized, and most fields and
115 * methods are unavailable. Subclasses should initialize themselves in
116 * {@link #onCreate}, not the constructor.
117 *
118 * <p>Content providers are created on the application main thread at
119 * application launch time. The constructor must not perform lengthy
120 * operations, or application startup will be delayed.
121 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900122 public ContentProvider() {
123 }
124
125 /**
126 * Constructor just for mocking.
127 *
128 * @param context A Context object which should be some mock instance (like the
129 * instance of {@link android.test.mock.MockContext}).
130 * @param readPermission The read permision you want this instance should have in the
131 * test, which is available via {@link #getReadPermission()}.
132 * @param writePermission The write permission you want this instance should have
133 * in the test, which is available via {@link #getWritePermission()}.
134 * @param pathPermissions The PathPermissions you want this instance should have
135 * in the test, which is available via {@link #getPathPermissions()}.
136 * @hide
137 */
138 public ContentProvider(
139 Context context,
140 String readPermission,
141 String writePermission,
142 PathPermission[] pathPermissions) {
143 mContext = context;
144 mReadPermission = readPermission;
145 mWritePermission = writePermission;
146 mPathPermissions = pathPermissions;
147 }
148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 /**
150 * Given an IContentProvider, try to coerce it back to the real
151 * ContentProvider object if it is running in the local process. This can
152 * be used if you know you are running in the same process as a provider,
153 * and want to get direct access to its implementation details. Most
154 * clients should not nor have a reason to use it.
155 *
156 * @param abstractInterface The ContentProvider interface that is to be
157 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800158 * @return If the IContentProvider is non-{@code null} and local, returns its actual
159 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 * @hide
161 */
162 public static ContentProvider coerceToLocalContentProvider(
163 IContentProvider abstractInterface) {
164 if (abstractInterface instanceof Transport) {
165 return ((Transport)abstractInterface).getContentProvider();
166 }
167 return null;
168 }
169
170 /**
171 * Binder object that deals with remoting.
172 *
173 * @hide
174 */
175 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800176 AppOpsManager mAppOpsManager = null;
177 int mReadOp = -1;
178 int mWriteOp = -1;
179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 ContentProvider getContentProvider() {
181 return ContentProvider.this;
182 }
183
Jeff Brownd2183652011-10-09 12:39:53 -0700184 @Override
185 public String getProviderName() {
186 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 }
188
Jeff Brown75ea64f2012-01-25 19:37:13 -0800189 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800190 public Cursor query(String callingPkg, Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800191 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800192 ICancellationSignal cancellationSignal) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800193 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
194 // The read is not allowed... to fake it out, we replace the given
195 // selection statement with a dummy one that will always be false.
196 // This way we will get a cursor back that has the correct structure
197 // but contains no rows.
198 selection = "'A' = 'B'";
199 }
Jeff Brown75ea64f2012-01-25 19:37:13 -0800200 return ContentProvider.this.query(uri, projection, selection, selectionArgs, sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800201 CancellationSignal.fromTransport(cancellationSignal));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 }
203
Jeff Brown75ea64f2012-01-25 19:37:13 -0800204 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 public String getType(Uri uri) {
206 return ContentProvider.this.getType(uri);
207 }
208
Jeff Brown75ea64f2012-01-25 19:37:13 -0800209 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800210 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800211 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
212 // If not allowed, we need to return some reasonable URI. Maybe the
213 // content provider should be responsible for this, but for now we
214 // will just return the base URI with a dummy '0' tagged on to it.
215 // You shouldn't be able to read if you can't write, anyway, so it
216 // shouldn't matter much what is returned.
217 return uri.buildUpon().appendPath("0").build();
218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 return ContentProvider.this.insert(uri, initialValues);
220 }
221
Jeff Brown75ea64f2012-01-25 19:37:13 -0800222 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800223 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
224 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
225 return 0;
226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 return ContentProvider.this.bulkInsert(uri, initialValues);
228 }
229
Jeff Brown75ea64f2012-01-25 19:37:13 -0800230 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800231 public ContentProviderResult[] applyBatch(String callingPkg,
232 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700233 throws OperationApplicationException {
234 for (ContentProviderOperation operation : operations) {
235 if (operation.isReadOperation()) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800236 if (enforceReadPermission(callingPkg, operation.getUri())
237 != AppOpsManager.MODE_ALLOWED) {
238 throw new OperationApplicationException("App op not allowed", 0);
239 }
Fred Quintana89437372009-05-15 15:10:40 -0700240 }
241
242 if (operation.isWriteOperation()) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800243 if (enforceWritePermission(callingPkg, operation.getUri())
244 != AppOpsManager.MODE_ALLOWED) {
245 throw new OperationApplicationException("App op not allowed", 0);
246 }
Fred Quintana89437372009-05-15 15:10:40 -0700247 }
248 }
249 return ContentProvider.this.applyBatch(operations);
Fred Quintana6a8d5332009-05-07 17:35:38 -0700250 }
251
Jeff Brown75ea64f2012-01-25 19:37:13 -0800252 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800253 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
254 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
255 return 0;
256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 return ContentProvider.this.delete(uri, selection, selectionArgs);
258 }
259
Jeff Brown75ea64f2012-01-25 19:37:13 -0800260 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800261 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 String[] selectionArgs) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800263 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
264 return 0;
265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 return ContentProvider.this.update(uri, values, selection, selectionArgs);
267 }
268
Jeff Brown75ea64f2012-01-25 19:37:13 -0800269 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800270 public ParcelFileDescriptor openFile(String callingPkg, Uri uri, String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 throws FileNotFoundException {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800272 enforceFilePermission(callingPkg, uri, mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 return ContentProvider.this.openFile(uri, mode);
274 }
275
Jeff Brown75ea64f2012-01-25 19:37:13 -0800276 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800277 public AssetFileDescriptor openAssetFile(String callingPkg, Uri uri, String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 throws FileNotFoundException {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800279 enforceFilePermission(callingPkg, uri, mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 return ContentProvider.this.openAssetFile(uri, mode);
281 }
282
Jeff Brown75ea64f2012-01-25 19:37:13 -0800283 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800284 public Bundle call(String callingPkg, String method, String arg, Bundle extras) {
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -0800285 return ContentProvider.this.call(method, arg, extras);
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800286 }
287
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700288 @Override
289 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
290 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
291 }
292
293 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800294 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
295 Bundle opts) throws FileNotFoundException {
296 enforceFilePermission(callingPkg, uri, "r");
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700297 return ContentProvider.this.openTypedAssetFile(uri, mimeType, opts);
298 }
299
Jeff Brown75ea64f2012-01-25 19:37:13 -0800300 @Override
Jeff Brown4c1241d2012-02-02 17:05:00 -0800301 public ICancellationSignal createCancellationSignal() throws RemoteException {
302 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800303 }
304
Dianne Hackborn35654b62013-01-14 17:38:02 -0800305 private void enforceFilePermission(String callingPkg, Uri uri, String mode)
306 throws FileNotFoundException, SecurityException {
307 if (mode != null && mode.startsWith("rw")) {
308 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
309 throw new FileNotFoundException("App op not allowed");
310 }
311 } else {
312 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
313 throw new FileNotFoundException("App op not allowed");
314 }
315 }
316 }
317
318 private int enforceReadPermission(String callingPkg, Uri uri) throws SecurityException {
319 enforceReadPermissionInner(uri);
320 if (mAppOpsManager != null) {
321 return mAppOpsManager.noteOp(mReadOp, Binder.getCallingUid(), callingPkg);
322 }
323 return AppOpsManager.MODE_ALLOWED;
324 }
325
326 private void enforceReadPermissionInner(Uri uri) throws SecurityException {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700327 final Context context = getContext();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 final int pid = Binder.getCallingPid();
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700329 final int uid = Binder.getCallingUid();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700330 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700331
Dianne Hackborn0d8af782012-08-17 16:51:54 -0700332 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700333 return;
334 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700335
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700336 if (mExported) {
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700337 final String componentPerm = getReadPermission();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700338 if (componentPerm != null) {
339 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
340 return;
341 } else {
342 missingPerm = componentPerm;
343 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700344 }
345
346 // track if unprotected read is allowed; any denied
347 // <path-permission> below removes this ability
348 boolean allowDefaultRead = (componentPerm == null);
349
350 final PathPermission[] pps = getPathPermissions();
351 if (pps != null) {
352 final String path = uri.getPath();
353 for (PathPermission pp : pps) {
354 final String pathPerm = pp.getReadPermission();
355 if (pathPerm != null && pp.match(path)) {
356 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700357 return;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700358 } else {
359 // any denied <path-permission> means we lose
360 // default <provider> access.
361 allowDefaultRead = false;
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700362 missingPerm = pathPerm;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700363 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700364 }
365 }
366 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700367
368 // if we passed <path-permission> checks above, and no default
369 // <provider> permission, then allow access.
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700370 if (allowDefaultRead) return;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700371 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700372
373 // last chance, check against any uri grants
374 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION)
375 == PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 return;
377 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700378
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700379 final String failReason = mExported
380 ? " requires " + missingPerm + ", or grantUriPermission()"
381 : " requires the provider be exported, or grantUriPermission()";
382 throw new SecurityException("Permission Denial: reading "
383 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
384 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 }
386
Dianne Hackborn35654b62013-01-14 17:38:02 -0800387 private int enforceWritePermission(String callingPkg, Uri uri) throws SecurityException {
388 enforceWritePermissionInner(uri);
389 if (mAppOpsManager != null) {
390 return mAppOpsManager.noteOp(mWriteOp, Binder.getCallingUid(), callingPkg);
391 }
392 return AppOpsManager.MODE_ALLOWED;
393 }
394
395 private void enforceWritePermissionInner(Uri uri) throws SecurityException {
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700396 final Context context = getContext();
397 final int pid = Binder.getCallingPid();
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700398 final int uid = Binder.getCallingUid();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700399 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700400
Dianne Hackborn0d8af782012-08-17 16:51:54 -0700401 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700402 return;
403 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700404
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700405 if (mExported) {
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700406 final String componentPerm = getWritePermission();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700407 if (componentPerm != null) {
408 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
409 return;
410 } else {
411 missingPerm = componentPerm;
412 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700413 }
414
415 // track if unprotected write is allowed; any denied
416 // <path-permission> below removes this ability
417 boolean allowDefaultWrite = (componentPerm == null);
418
419 final PathPermission[] pps = getPathPermissions();
420 if (pps != null) {
421 final String path = uri.getPath();
422 for (PathPermission pp : pps) {
423 final String pathPerm = pp.getWritePermission();
424 if (pathPerm != null && pp.match(path)) {
425 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700426 return;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700427 } else {
428 // any denied <path-permission> means we lose
429 // default <provider> access.
430 allowDefaultWrite = false;
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700431 missingPerm = pathPerm;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700432 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700433 }
434 }
435 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700436
437 // if we passed <path-permission> checks above, and no default
438 // <provider> permission, then allow access.
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700439 if (allowDefaultWrite) return;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700440 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700441
442 // last chance, check against any uri grants
443 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
444 == PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 return;
446 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700447
448 final String failReason = mExported
449 ? " requires " + missingPerm + ", or grantUriPermission()"
450 : " requires the provider be exported, or grantUriPermission()";
451 throw new SecurityException("Permission Denial: writing "
452 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
453 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 }
455 }
456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700458 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800459 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 * constructor.
461 */
462 public final Context getContext() {
463 return mContext;
464 }
465
466 /**
467 * Change the permission required to read data from the content
468 * provider. This is normally set for you from its manifest information
469 * when the provider is first created.
470 *
471 * @param permission Name of the permission required for read-only access.
472 */
473 protected final void setReadPermission(String permission) {
474 mReadPermission = permission;
475 }
476
477 /**
478 * Return the name of the permission required for read-only access to
479 * this content provider. This method can be called from multiple
480 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800481 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
482 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 */
484 public final String getReadPermission() {
485 return mReadPermission;
486 }
487
488 /**
489 * Change the permission required to read and write data in the content
490 * provider. This is normally set for you from its manifest information
491 * when the provider is first created.
492 *
493 * @param permission Name of the permission required for read/write access.
494 */
495 protected final void setWritePermission(String permission) {
496 mWritePermission = permission;
497 }
498
499 /**
500 * Return the name of the permission required for read/write access to
501 * this content provider. This method can be called from multiple
502 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800503 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
504 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 */
506 public final String getWritePermission() {
507 return mWritePermission;
508 }
509
510 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700511 * Change the path-based permission required to read and/or write data in
512 * the content provider. This is normally set for you from its manifest
513 * information when the provider is first created.
514 *
515 * @param permissions Array of path permission descriptions.
516 */
517 protected final void setPathPermissions(PathPermission[] permissions) {
518 mPathPermissions = permissions;
519 }
520
521 /**
522 * Return the path-based permissions required for read and/or write access to
523 * this content provider. This method can be called from multiple
524 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800525 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
526 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700527 */
528 public final PathPermission[] getPathPermissions() {
529 return mPathPermissions;
530 }
531
Dianne Hackborn35654b62013-01-14 17:38:02 -0800532 /** @hide */
533 public final void setAppOps(int readOp, int writeOp) {
534 mTransport.mAppOpsManager = (AppOpsManager)mContext.getSystemService(
535 Context.APP_OPS_SERVICE);
536 mTransport.mReadOp = readOp;
537 mTransport.mWriteOp = writeOp;
538 }
539
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700540 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700541 * Implement this to initialize your content provider on startup.
542 * This method is called for all registered content providers on the
543 * application main thread at application launch time. It must not perform
544 * lengthy operations, or application startup will be delayed.
545 *
546 * <p>You should defer nontrivial initialization (such as opening,
547 * upgrading, and scanning databases) until the content provider is used
548 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
549 * keeps application startup fast, avoids unnecessary work if the provider
550 * turns out not to be needed, and stops database errors (such as a full
551 * disk) from halting application launch.
552 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700553 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700554 * is a helpful utility class that makes it easy to manage databases,
555 * and will automatically defer opening until first use. If you do use
556 * SQLiteOpenHelper, make sure to avoid calling
557 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
558 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
559 * from this method. (Instead, override
560 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
561 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 *
563 * @return true if the provider was successfully loaded, false otherwise
564 */
565 public abstract boolean onCreate();
566
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700567 /**
568 * {@inheritDoc}
569 * This method is always called on the application main thread, and must
570 * not perform lengthy operations.
571 *
572 * <p>The default content provider implementation does nothing.
573 * Override this method to take appropriate action.
574 * (Content providers do not usually care about things like screen
575 * orientation, but may want to know about locale changes.)
576 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 public void onConfigurationChanged(Configuration newConfig) {
578 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700579
580 /**
581 * {@inheritDoc}
582 * This method is always called on the application main thread, and must
583 * not perform lengthy operations.
584 *
585 * <p>The default content provider implementation does nothing.
586 * Subclasses may override this method to take appropriate action.
587 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 public void onLowMemory() {
589 }
590
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700591 public void onTrimMemory(int level) {
592 }
593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700595 * Implement this to handle query requests from clients.
596 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800597 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
598 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 * <p>
600 * Example client call:<p>
601 * <pre>// Request a specific record.
602 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000603 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 projection, // Which columns to return.
605 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000606 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 People.NAME + " ASC"); // Sort order.</pre>
608 * Example implementation:<p>
609 * <pre>// SQLiteQueryBuilder is a helper class that creates the
610 // proper SQL syntax for us.
611 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
612
613 // Set the table we're querying.
614 qBuilder.setTables(DATABASE_TABLE_NAME);
615
616 // If the query ends in a specific record number, we're
617 // being asked for a specific record, so set the
618 // WHERE clause in our query.
619 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
620 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
621 }
622
623 // Make the query.
624 Cursor c = qBuilder.query(mDb,
625 projection,
626 selection,
627 selectionArgs,
628 groupBy,
629 having,
630 sortOrder);
631 c.setNotificationUri(getContext().getContentResolver(), uri);
632 return c;</pre>
633 *
634 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000635 * if the client is requesting a specific record, the URI will end in a record number
636 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
637 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800639 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800641 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000642 * @param selectionArgs You may include ?s in selection, which will be replaced by
643 * the values from selectionArgs, in order that they appear in the selection.
644 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800646 * If {@code null} then the provider is free to define the sort order.
647 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 */
649 public abstract Cursor query(Uri uri, String[] projection,
650 String selection, String[] selectionArgs, String sortOrder);
651
Fred Quintana5bba6322009-10-05 14:21:12 -0700652 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800653 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800654 * This method can be called from multiple threads, as described in
655 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
656 * and Threads</a>.
657 * <p>
658 * Example client call:<p>
659 * <pre>// Request a specific record.
660 * Cursor managedCursor = managedQuery(
661 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
662 projection, // Which columns to return.
663 null, // WHERE clause.
664 null, // WHERE clause value substitution
665 People.NAME + " ASC"); // Sort order.</pre>
666 * Example implementation:<p>
667 * <pre>// SQLiteQueryBuilder is a helper class that creates the
668 // proper SQL syntax for us.
669 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
670
671 // Set the table we're querying.
672 qBuilder.setTables(DATABASE_TABLE_NAME);
673
674 // If the query ends in a specific record number, we're
675 // being asked for a specific record, so set the
676 // WHERE clause in our query.
677 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
678 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
679 }
680
681 // Make the query.
682 Cursor c = qBuilder.query(mDb,
683 projection,
684 selection,
685 selectionArgs,
686 groupBy,
687 having,
688 sortOrder);
689 c.setNotificationUri(getContext().getContentResolver(), uri);
690 return c;</pre>
691 * <p>
692 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800693 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
694 * signal to ensure correct operation on older versions of the Android Framework in
695 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800696 *
697 * @param uri The URI to query. This will be the full URI sent by the client;
698 * if the client is requesting a specific record, the URI will end in a record number
699 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
700 * that _id value.
701 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800702 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800703 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800704 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800705 * @param selectionArgs You may include ?s in selection, which will be replaced by
706 * the values from selectionArgs, in order that they appear in the selection.
707 * The values will be bound as Strings.
708 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800709 * If {@code null} then the provider is free to define the sort order.
710 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800711 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
712 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800713 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800714 */
715 public Cursor query(Uri uri, String[] projection,
716 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800717 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800718 return query(uri, projection, selection, selectionArgs, sortOrder);
719 }
720
721 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700722 * Implement this to handle requests for the MIME type of the data at the
723 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 * <code>vnd.android.cursor.item</code> for a single record,
725 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700726 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800727 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
728 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700730 * <p>Note that there are no permissions needed for an application to
731 * access this information; if your content provider requires read and/or
732 * write permissions, or is not exported, all applications can still call
733 * this method regardless of their access permissions. This allows them
734 * to retrieve the MIME type for a URI when dispatching intents.
735 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800737 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 */
739 public abstract String getType(Uri uri);
740
741 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700742 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
744 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700745 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800746 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
747 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800748 * @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 -0800749 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800750 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 * @return The URI for the newly inserted item.
752 */
753 public abstract Uri insert(Uri uri, ContentValues values);
754
755 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700756 * Override this to handle requests to insert a set of new rows, or the
757 * default implementation will iterate over the values and call
758 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
760 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700761 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800762 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
763 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 *
765 * @param uri The content:// URI of the insertion request.
766 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800767 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 * @return The number of values that were inserted.
769 */
770 public int bulkInsert(Uri uri, ContentValues[] values) {
771 int numValues = values.length;
772 for (int i = 0; i < numValues; i++) {
773 insert(uri, values[i]);
774 }
775 return numValues;
776 }
777
778 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700779 * Implement this to handle requests to delete one or more rows.
780 * The implementation should apply the selection clause when performing
781 * deletion, allowing the operation to affect multiple rows in a directory.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyDelete()}
783 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700784 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800785 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
786 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 *
788 * <p>The implementation is responsible for parsing out a row ID at the end
789 * of the URI, if a specific row is being deleted. That is, the client would
790 * pass in <code>content://contacts/people/22</code> and the implementation is
791 * responsible for parsing the record number (22) when creating a SQL statement.
792 *
793 * @param uri The full URI to query, including a row ID (if a specific record is requested).
794 * @param selection An optional restriction to apply to rows when deleting.
795 * @return The number of rows affected.
796 * @throws SQLException
797 */
798 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
799
800 /**
Dan Egnor17876aa2010-07-28 12:28:04 -0700801 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700802 * The implementation should update all rows matching the selection
803 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
805 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700806 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800807 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
808 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 *
810 * @param uri The URI to query. This can potentially have a record ID if this
811 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800812 * @param values A set of column_name/value pairs to update in the database.
813 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 * @param selection An optional filter to match rows to update.
815 * @return the number of rows affected.
816 */
817 public abstract int update(Uri uri, ContentValues values, String selection,
818 String[] selectionArgs);
819
820 /**
Dan Egnor17876aa2010-07-28 12:28:04 -0700821 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700822 * The default implementation always throws {@link FileNotFoundException}.
823 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800824 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
825 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700826 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700827 * <p>This method returns a ParcelFileDescriptor, which is returned directly
828 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700829 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 *
831 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
832 * their responsibility to close it when done. That is, the implementation
833 * of this method should create a new ParcelFileDescriptor for each call.
834 *
835 * @param uri The URI whose file is to be opened.
836 * @param mode Access mode for the file. May be "r" for read-only access,
837 * "rw" for read and write access, or "rwt" for read and write access
838 * that truncates any existing file.
839 *
840 * @return Returns a new ParcelFileDescriptor which you can use to access
841 * the file.
842 *
843 * @throws FileNotFoundException Throws FileNotFoundException if there is
844 * no file associated with the given URI or the mode is invalid.
845 * @throws SecurityException Throws SecurityException if the caller does
846 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700847 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 * @see #openAssetFile(Uri, String)
849 * @see #openFileHelper(Uri, String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700850 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 public ParcelFileDescriptor openFile(Uri uri, String mode)
852 throws FileNotFoundException {
853 throw new FileNotFoundException("No files supported by provider at "
854 + uri);
855 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 /**
858 * This is like {@link #openFile}, but can be implemented by providers
859 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700860 * inside of their .apk.
861 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800862 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
863 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700864 *
865 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -0700866 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700867 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
869 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
870 * methods.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700871 *
872 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 * should create the AssetFileDescriptor with
874 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700875 * applications that can not handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 *
877 * @param uri The URI whose file is to be opened.
878 * @param mode Access mode for the file. May be "r" for read-only access,
879 * "w" for write-only access (erasing whatever data is currently in
880 * the file), "wa" for write-only access to append to any existing data,
881 * "rw" for read and write access on any existing data, and "rwt" for read
882 * and write access that truncates any existing file.
883 *
884 * @return Returns a new AssetFileDescriptor which you can use to access
885 * the file.
886 *
887 * @throws FileNotFoundException Throws FileNotFoundException if there is
888 * no file associated with the given URI or the mode is invalid.
889 * @throws SecurityException Throws SecurityException if the caller does
890 * not have permission to access the file.
891 *
892 * @see #openFile(Uri, String)
893 * @see #openFileHelper(Uri, String)
894 */
895 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
896 throws FileNotFoundException {
897 ParcelFileDescriptor fd = openFile(uri, mode);
898 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
899 }
900
901 /**
902 * Convenience for subclasses that wish to implement {@link #openFile}
903 * by looking up a column named "_data" at the given URI.
904 *
905 * @param uri The URI to be opened.
906 * @param mode The file mode. May be "r" for read-only access,
907 * "w" for write-only access (erasing whatever data is currently in
908 * the file), "wa" for write-only access to append to any existing data,
909 * "rw" for read and write access on any existing data, and "rwt" for read
910 * and write access that truncates any existing file.
911 *
912 * @return Returns a new ParcelFileDescriptor that can be used by the
913 * client to access the file.
914 */
915 protected final ParcelFileDescriptor openFileHelper(Uri uri,
916 String mode) throws FileNotFoundException {
917 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
918 int count = (c != null) ? c.getCount() : 0;
919 if (count != 1) {
920 // If there is not exactly one result, throw an appropriate
921 // exception.
922 if (c != null) {
923 c.close();
924 }
925 if (count == 0) {
926 throw new FileNotFoundException("No entry for " + uri);
927 }
928 throw new FileNotFoundException("Multiple items at " + uri);
929 }
930
931 c.moveToFirst();
932 int i = c.getColumnIndex("_data");
933 String path = (i >= 0 ? c.getString(i) : null);
934 c.close();
935 if (path == null) {
936 throw new FileNotFoundException("Column _data not found.");
937 }
938
939 int modeBits = ContentResolver.modeToMode(uri, mode);
940 return ParcelFileDescriptor.open(new File(path), modeBits);
941 }
942
943 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700944 * Called by a client to determine the types of data streams that this
945 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800946 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700947 * of a particular type, return that MIME type if it matches the given
948 * mimeTypeFilter. If it can perform type conversions, return an array
949 * of all supported MIME types that match mimeTypeFilter.
950 *
951 * @param uri The data in the content provider being queried.
952 * @param mimeTypeFilter The type of data the client desires. May be
953 * a pattern, such as *\/* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800954 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700955 * given mimeTypeFilter. Otherwise returns an array of all available
956 * concrete MIME types.
957 *
958 * @see #getType(Uri)
959 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700960 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700961 */
962 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
963 return null;
964 }
965
966 /**
967 * Called by a client to open a read-only stream containing data of a
968 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
969 * except the file can only be read-only and the content provider may
970 * perform data conversions to generate data of the desired type.
971 *
972 * <p>The default implementation compares the given mimeType against the
973 * result of {@link #getType(Uri)} and, if the match, simple calls
974 * {@link #openAssetFile(Uri, String)}.
975 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700976 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700977 * of this method.
978 *
979 * @param uri The data in the content provider being queried.
980 * @param mimeTypeFilter The type of data the client desires. May be
981 * a pattern, such as *\/*, if the caller does not have specific type
982 * requirements; in this case the content provider will pick its best
983 * type matching the pattern.
984 * @param opts Additional options from the client. The definitions of
985 * these are specific to the content provider being called.
986 *
987 * @return Returns a new AssetFileDescriptor from which the client can
988 * read data of the desired type.
989 *
990 * @throws FileNotFoundException Throws FileNotFoundException if there is
991 * no file associated with the given URI or the mode is invalid.
992 * @throws SecurityException Throws SecurityException if the caller does
993 * not have permission to access the data.
994 * @throws IllegalArgumentException Throws IllegalArgumentException if the
995 * content provider does not support the requested MIME type.
996 *
997 * @see #getStreamTypes(Uri, String)
998 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -0700999 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001000 */
1001 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
1002 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001003 if ("*/*".equals(mimeTypeFilter)) {
1004 // If they can take anything, the untyped open call is good enough.
1005 return openAssetFile(uri, "r");
1006 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001007 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001008 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001009 // Use old untyped open call if this provider has a type for this
1010 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001011 return openAssetFile(uri, "r");
1012 }
1013 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1014 }
1015
1016 /**
1017 * Interface to write a stream of data to a pipe. Use with
1018 * {@link ContentProvider#openPipeHelper}.
1019 */
1020 public interface PipeDataWriter<T> {
1021 /**
1022 * Called from a background thread to stream data out to a pipe.
1023 * Note that the pipe is blocking, so this thread can block on
1024 * writes for an arbitrary amount of time if the client is slow
1025 * at reading.
1026 *
1027 * @param output The pipe where data should be written. This will be
1028 * closed for you upon returning from this function.
1029 * @param uri The URI whose data is to be written.
1030 * @param mimeType The desired type of data to be written.
1031 * @param opts Options supplied by caller.
1032 * @param args Your own custom arguments.
1033 */
1034 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
1035 Bundle opts, T args);
1036 }
1037
1038 /**
1039 * A helper function for implementing {@link #openTypedAssetFile}, for
1040 * creating a data pipe and background thread allowing you to stream
1041 * generated data back to the client. This function returns a new
1042 * ParcelFileDescriptor that should be returned to the caller (the caller
1043 * is responsible for closing it).
1044 *
1045 * @param uri The URI whose data is to be written.
1046 * @param mimeType The desired type of data to be written.
1047 * @param opts Options supplied by caller.
1048 * @param args Your own custom arguments.
1049 * @param func Interface implementing the function that will actually
1050 * stream the data.
1051 * @return Returns a new ParcelFileDescriptor holding the read side of
1052 * the pipe. This should be returned to the caller for reading; the caller
1053 * is responsible for closing it when done.
1054 */
1055 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
1056 final Bundle opts, final T args, final PipeDataWriter<T> func)
1057 throws FileNotFoundException {
1058 try {
1059 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1060
1061 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1062 @Override
1063 protected Object doInBackground(Object... params) {
1064 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1065 try {
1066 fds[1].close();
1067 } catch (IOException e) {
1068 Log.w(TAG, "Failure closing pipe", e);
1069 }
1070 return null;
1071 }
1072 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001073 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001074
1075 return fds[0];
1076 } catch (IOException e) {
1077 throw new FileNotFoundException("failure making pipe");
1078 }
1079 }
1080
1081 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 * Returns true if this instance is a temporary content provider.
1083 * @return true if this instance is a temporary content provider
1084 */
1085 protected boolean isTemporary() {
1086 return false;
1087 }
1088
1089 /**
1090 * Returns the Binder object for this provider.
1091 *
1092 * @return the Binder object for this provider
1093 * @hide
1094 */
1095 public IContentProvider getIContentProvider() {
1096 return mTransport;
1097 }
1098
1099 /**
1100 * After being instantiated, this is called to tell the content provider
1101 * about itself.
1102 *
1103 * @param context The context this provider is running in
1104 * @param info Registered information about this content provider
1105 */
1106 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001107 /*
1108 * We may be using AsyncTask from binder threads. Make it init here
1109 * so its static handler is on the main thread.
1110 */
1111 AsyncTask.init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112
1113 /*
1114 * Only allow it to be set once, so after the content service gives
1115 * this to us clients can't change it.
1116 */
1117 if (mContext == null) {
1118 mContext = context;
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001119 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 if (info != null) {
1121 setReadPermission(info.readPermission);
1122 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001123 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001124 mExported = info.exported;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 }
1126 ContentProvider.this.onCreate();
1127 }
1128 }
Fred Quintanace31b232009-05-04 16:01:15 -07001129
1130 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001131 * Override this to handle requests to perform a batch of operations, or the
1132 * default implementation will iterate over the operations and call
1133 * {@link ContentProviderOperation#apply} on each of them.
1134 * If all calls to {@link ContentProviderOperation#apply} succeed
1135 * then a {@link ContentProviderResult} array with as many
1136 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001137 * fail, it is up to the implementation how many of the others take effect.
1138 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001139 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1140 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001141 *
Fred Quintanace31b232009-05-04 16:01:15 -07001142 * @param operations the operations to apply
1143 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001144 * @throws OperationApplicationException thrown if any operation fails.
1145 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001146 */
Fred Quintana03d94902009-05-22 14:23:31 -07001147 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001148 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001149 final int numOperations = operations.size();
1150 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1151 for (int i = 0; i < numOperations; i++) {
1152 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001153 }
1154 return results;
1155 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001156
1157 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001158 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001159 * interfaces that are cheaper and/or unnatural for a table-like
1160 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001161 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001162 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1163 * @param arg provider-defined String argument. May be {@code null}.
1164 * @param extras provider-defined Bundle argument. May be {@code null}.
1165 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001166 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001167 */
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001168 public Bundle call(String method, String arg, Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001169 return null;
1170 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001171
1172 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001173 * Implement this to shut down the ContentProvider instance. You can then
1174 * invoke this method in unit tests.
1175 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001176 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001177 * Android normally handles ContentProvider startup and shutdown
1178 * automatically. You do not need to start up or shut down a
1179 * ContentProvider. When you invoke a test method on a ContentProvider,
1180 * however, a ContentProvider instance is started and keeps running after
1181 * the test finishes, even if a succeeding test instantiates another
1182 * ContentProvider. A conflict develops because the two instances are
1183 * usually running against the same underlying data source (for example, an
1184 * sqlite database).
1185 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001186 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001187 * Implementing shutDown() avoids this conflict by providing a way to
1188 * terminate the ContentProvider. This method can also prevent memory leaks
1189 * from multiple instantiations of the ContentProvider, and it can ensure
1190 * unit test isolation by allowing you to completely clean up the test
1191 * fixture before moving on to the next test.
1192 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001193 */
1194 public void shutdown() {
1195 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1196 "connections are gracefully shutdown");
1197 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001198
1199 /**
1200 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001201 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001202 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001203 * @param fd The raw file descriptor that the dump is being sent to.
1204 * @param writer The PrintWriter to which you should dump your state. This will be
1205 * closed for you after you return.
1206 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001207 */
1208 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1209 writer.println("nothing to dump");
1210 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001211}