blob: 343841934223be0ec32c381b4fa8677a55a73c30 [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;
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;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070037import android.os.UserHandle;
Vasu Nori0c9e14a2010-08-04 13:31:48 -070038import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039
40import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080041import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070043import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080044import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070045import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046
47/**
48 * Content providers are one of the primary building blocks of Android applications, providing
49 * content to applications. They encapsulate data and provide it to applications through the single
50 * {@link ContentResolver} interface. A content provider is only required if you need to share
51 * data between multiple applications. For example, the contacts data is used by multiple
52 * applications and must be stored in a content provider. If you don't need to share data amongst
53 * multiple applications you can use a database directly via
54 * {@link android.database.sqlite.SQLiteDatabase}.
55 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056 * <p>When a request is made via
57 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
58 * request to the content provider registered with the authority. The content provider can interpret
59 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
60 * URIs.</p>
61 *
62 * <p>The primary methods that need to be implemented are:
63 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070064 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065 * <li>{@link #query} which returns data to the caller</li>
66 * <li>{@link #insert} which inserts new data into the content provider</li>
67 * <li>{@link #update} which updates existing data in the content provider</li>
68 * <li>{@link #delete} which deletes data from the content provider</li>
69 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
70 * </ul></p>
71 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070072 * <p class="caution">Data access methods (such as {@link #insert} and
73 * {@link #update}) may be called from many threads at once, and must be thread-safe.
74 * Other methods (such as {@link #onCreate}) are only called from the application
75 * main thread, and must avoid performing lengthy operations. See the method
76 * descriptions for their expected thread behavior.</p>
77 *
78 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
79 * ContentProvider instance, so subclasses don't have to worry about the details of
80 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070081 *
82 * <div class="special reference">
83 * <h3>Developer Guides</h3>
84 * <p>For more information about using content providers, read the
85 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
86 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -070088public abstract class ContentProvider implements ComponentCallbacks2 {
Vasu Nori0c9e14a2010-08-04 13:31:48 -070089 private static final String TAG = "ContentProvider";
90
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +090091 /*
92 * Note: if you add methods to ContentProvider, you must add similar methods to
93 * MockContentProvider.
94 */
95
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070097 private int mMyUid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 private String mReadPermission;
99 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700100 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700101 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800102 private boolean mNoPerms;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700104 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<String>();
105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 private Transport mTransport = new Transport();
107
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700108 /**
109 * Construct a ContentProvider instance. Content providers must be
110 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
111 * in the manifest</a>, accessed with {@link ContentResolver}, and created
112 * automatically by the system, so applications usually do not create
113 * ContentProvider instances directly.
114 *
115 * <p>At construction time, the object is uninitialized, and most fields and
116 * methods are unavailable. Subclasses should initialize themselves in
117 * {@link #onCreate}, not the constructor.
118 *
119 * <p>Content providers are created on the application main thread at
120 * application launch time. The constructor must not perform lengthy
121 * operations, or application startup will be delayed.
122 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900123 public ContentProvider() {
124 }
125
126 /**
127 * Constructor just for mocking.
128 *
129 * @param context A Context object which should be some mock instance (like the
130 * instance of {@link android.test.mock.MockContext}).
131 * @param readPermission The read permision you want this instance should have in the
132 * test, which is available via {@link #getReadPermission()}.
133 * @param writePermission The write permission you want this instance should have
134 * in the test, which is available via {@link #getWritePermission()}.
135 * @param pathPermissions The PathPermissions you want this instance should have
136 * in the test, which is available via {@link #getPathPermissions()}.
137 * @hide
138 */
139 public ContentProvider(
140 Context context,
141 String readPermission,
142 String writePermission,
143 PathPermission[] pathPermissions) {
144 mContext = context;
145 mReadPermission = readPermission;
146 mWritePermission = writePermission;
147 mPathPermissions = pathPermissions;
148 }
149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 /**
151 * Given an IContentProvider, try to coerce it back to the real
152 * ContentProvider object if it is running in the local process. This can
153 * be used if you know you are running in the same process as a provider,
154 * and want to get direct access to its implementation details. Most
155 * clients should not nor have a reason to use it.
156 *
157 * @param abstractInterface The ContentProvider interface that is to be
158 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800159 * @return If the IContentProvider is non-{@code null} and local, returns its actual
160 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 * @hide
162 */
163 public static ContentProvider coerceToLocalContentProvider(
164 IContentProvider abstractInterface) {
165 if (abstractInterface instanceof Transport) {
166 return ((Transport)abstractInterface).getContentProvider();
167 }
168 return null;
169 }
170
171 /**
172 * Binder object that deals with remoting.
173 *
174 * @hide
175 */
176 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800177 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800178 int mReadOp = AppOpsManager.OP_NONE;
179 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 ContentProvider getContentProvider() {
182 return ContentProvider.this;
183 }
184
Jeff Brownd2183652011-10-09 12:39:53 -0700185 @Override
186 public String getProviderName() {
187 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 }
189
Jeff Brown75ea64f2012-01-25 19:37:13 -0800190 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800191 public Cursor query(String callingPkg, Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800192 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800193 ICancellationSignal cancellationSignal) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800194 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800195 return rejectQuery(uri, projection, selection, selectionArgs, sortOrder,
196 CancellationSignal.fromTransport(cancellationSignal));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800197 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700198 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700199 try {
200 return ContentProvider.this.query(
201 uri, projection, selection, selectionArgs, sortOrder,
202 CancellationSignal.fromTransport(cancellationSignal));
203 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700204 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 }
207
Jeff Brown75ea64f2012-01-25 19:37:13 -0800208 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 public String getType(Uri uri) {
210 return ContentProvider.this.getType(uri);
211 }
212
Jeff Brown75ea64f2012-01-25 19:37:13 -0800213 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800214 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800215 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800216 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800217 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700218 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700219 try {
220 return ContentProvider.this.insert(uri, initialValues);
221 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700222 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 }
225
Jeff Brown75ea64f2012-01-25 19:37:13 -0800226 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800227 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
228 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
229 return 0;
230 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700231 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700232 try {
233 return ContentProvider.this.bulkInsert(uri, initialValues);
234 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700235 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 }
238
Jeff Brown75ea64f2012-01-25 19:37:13 -0800239 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800240 public ContentProviderResult[] applyBatch(String callingPkg,
241 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700242 throws OperationApplicationException {
243 for (ContentProviderOperation operation : operations) {
244 if (operation.isReadOperation()) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800245 if (enforceReadPermission(callingPkg, operation.getUri())
246 != AppOpsManager.MODE_ALLOWED) {
247 throw new OperationApplicationException("App op not allowed", 0);
248 }
Fred Quintana89437372009-05-15 15:10:40 -0700249 }
250
251 if (operation.isWriteOperation()) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800252 if (enforceWritePermission(callingPkg, operation.getUri())
253 != AppOpsManager.MODE_ALLOWED) {
254 throw new OperationApplicationException("App op not allowed", 0);
255 }
Fred Quintana89437372009-05-15 15:10:40 -0700256 }
257 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700258 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700259 try {
260 return ContentProvider.this.applyBatch(operations);
261 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700262 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700263 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700264 }
265
Jeff Brown75ea64f2012-01-25 19:37:13 -0800266 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800267 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
268 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
269 return 0;
270 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700271 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700272 try {
273 return ContentProvider.this.delete(uri, selection, selectionArgs);
274 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700275 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 }
278
Jeff Brown75ea64f2012-01-25 19:37:13 -0800279 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800280 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 String[] selectionArgs) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800282 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
283 return 0;
284 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700285 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700286 try {
287 return ContentProvider.this.update(uri, values, selection, selectionArgs);
288 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700289 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 }
292
Jeff Brown75ea64f2012-01-25 19:37:13 -0800293 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700294 public ParcelFileDescriptor openFile(
295 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296 throws FileNotFoundException {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800297 enforceFilePermission(callingPkg, uri, mode);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700298 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700299 try {
300 return ContentProvider.this.openFile(
301 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
302 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700303 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 }
306
Jeff Brown75ea64f2012-01-25 19:37:13 -0800307 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700308 public AssetFileDescriptor openAssetFile(
309 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 throws FileNotFoundException {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800311 enforceFilePermission(callingPkg, uri, mode);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700312 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700313 try {
314 return ContentProvider.this.openAssetFile(
315 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
316 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700317 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 }
320
Jeff Brown75ea64f2012-01-25 19:37:13 -0800321 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800322 public Bundle call(String callingPkg, String method, String arg, Bundle extras) {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700323 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700324 try {
325 return ContentProvider.this.call(method, arg, extras);
326 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700327 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700328 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800329 }
330
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700331 @Override
332 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
333 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
334 }
335
336 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800337 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700338 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800339 enforceFilePermission(callingPkg, uri, "r");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700340 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700341 try {
342 return ContentProvider.this.openTypedAssetFile(
343 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
344 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700345 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700346 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700347 }
348
Jeff Brown75ea64f2012-01-25 19:37:13 -0800349 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700350 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800351 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800352 }
353
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700354 @Override
355 public Uri canonicalize(String callingPkg, Uri uri) {
356 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
357 return null;
358 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700359 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700360 try {
361 return ContentProvider.this.canonicalize(uri);
362 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700363 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700364 }
365 }
366
367 @Override
368 public Uri uncanonicalize(String callingPkg, Uri uri) {
369 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
370 return null;
371 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700372 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700373 try {
374 return ContentProvider.this.uncanonicalize(uri);
375 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700376 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700377 }
378 }
379
Dianne Hackborn35654b62013-01-14 17:38:02 -0800380 private void enforceFilePermission(String callingPkg, Uri uri, String mode)
381 throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800382 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800383 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
384 throw new FileNotFoundException("App op not allowed");
385 }
386 } else {
387 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
388 throw new FileNotFoundException("App op not allowed");
389 }
390 }
391 }
392
393 private int enforceReadPermission(String callingPkg, Uri uri) throws SecurityException {
394 enforceReadPermissionInner(uri);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800395 if (mReadOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800396 return mAppOpsManager.noteOp(mReadOp, Binder.getCallingUid(), callingPkg);
397 }
398 return AppOpsManager.MODE_ALLOWED;
399 }
400
401 private void enforceReadPermissionInner(Uri uri) throws SecurityException {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700402 final Context context = getContext();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800403 final int pid = Binder.getCallingPid();
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700404 final int uid = Binder.getCallingUid();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700405 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700406
Dianne Hackborn0d8af782012-08-17 16:51:54 -0700407 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700408 return;
409 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700410
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700411 if (mExported) {
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700412 final String componentPerm = getReadPermission();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700413 if (componentPerm != null) {
414 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
415 return;
416 } else {
417 missingPerm = componentPerm;
418 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700419 }
420
421 // track if unprotected read is allowed; any denied
422 // <path-permission> below removes this ability
423 boolean allowDefaultRead = (componentPerm == null);
424
425 final PathPermission[] pps = getPathPermissions();
426 if (pps != null) {
427 final String path = uri.getPath();
428 for (PathPermission pp : pps) {
429 final String pathPerm = pp.getReadPermission();
430 if (pathPerm != null && pp.match(path)) {
431 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700432 return;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700433 } else {
434 // any denied <path-permission> means we lose
435 // default <provider> access.
436 allowDefaultRead = false;
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700437 missingPerm = pathPerm;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700438 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700439 }
440 }
441 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700442
443 // if we passed <path-permission> checks above, and no default
444 // <provider> permission, then allow access.
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700445 if (allowDefaultRead) return;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700446 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700447
448 // last chance, check against any uri grants
449 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION)
450 == PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 return;
452 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700453
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700454 final String failReason = mExported
455 ? " requires " + missingPerm + ", or grantUriPermission()"
456 : " requires the provider be exported, or grantUriPermission()";
457 throw new SecurityException("Permission Denial: reading "
458 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
459 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 }
461
Dianne Hackborn35654b62013-01-14 17:38:02 -0800462 private int enforceWritePermission(String callingPkg, Uri uri) throws SecurityException {
463 enforceWritePermissionInner(uri);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800464 if (mWriteOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800465 return mAppOpsManager.noteOp(mWriteOp, Binder.getCallingUid(), callingPkg);
466 }
467 return AppOpsManager.MODE_ALLOWED;
468 }
469
470 private void enforceWritePermissionInner(Uri uri) throws SecurityException {
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700471 final Context context = getContext();
472 final int pid = Binder.getCallingPid();
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700473 final int uid = Binder.getCallingUid();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700474 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700475
Dianne Hackborn0d8af782012-08-17 16:51:54 -0700476 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700477 return;
478 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700479
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700480 if (mExported) {
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700481 final String componentPerm = getWritePermission();
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700482 if (componentPerm != null) {
483 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
484 return;
485 } else {
486 missingPerm = componentPerm;
487 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700488 }
489
490 // track if unprotected write is allowed; any denied
491 // <path-permission> below removes this ability
492 boolean allowDefaultWrite = (componentPerm == null);
493
494 final PathPermission[] pps = getPathPermissions();
495 if (pps != null) {
496 final String path = uri.getPath();
497 for (PathPermission pp : pps) {
498 final String pathPerm = pp.getWritePermission();
499 if (pathPerm != null && pp.match(path)) {
500 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700501 return;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700502 } else {
503 // any denied <path-permission> means we lose
504 // default <provider> access.
505 allowDefaultWrite = false;
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700506 missingPerm = pathPerm;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700507 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700508 }
509 }
510 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700511
512 // if we passed <path-permission> checks above, and no default
513 // <provider> permission, then allow access.
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700514 if (allowDefaultWrite) return;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700515 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700516
517 // last chance, check against any uri grants
518 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
519 == PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 return;
521 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700522
523 final String failReason = mExported
524 ? " requires " + missingPerm + ", or grantUriPermission()"
525 : " requires the provider be exported, or grantUriPermission()";
526 throw new SecurityException("Permission Denial: writing "
527 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
528 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529 }
530 }
531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700533 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800534 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 * constructor.
536 */
537 public final Context getContext() {
538 return mContext;
539 }
540
541 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700542 * Set the calling package, returning the current value (or {@code null})
543 * which can be used later to restore the previous state.
544 */
545 private String setCallingPackage(String callingPackage) {
546 final String original = mCallingPackage.get();
547 mCallingPackage.set(callingPackage);
548 return original;
549 }
550
551 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700552 * Return the package name of the caller that initiated the request being
553 * processed on the current thread. The returned package will have been
554 * verified to belong to the calling UID. Returns {@code null} if not
555 * currently processing a request.
556 * <p>
557 * This will always return {@code null} when processing
558 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
559 *
560 * @see Binder#getCallingUid()
561 * @see Context#grantUriPermission(String, Uri, int)
562 * @throws SecurityException if the calling package doesn't belong to the
563 * calling UID.
564 */
565 public final String getCallingPackage() {
566 final String pkg = mCallingPackage.get();
567 if (pkg != null) {
568 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
569 }
570 return pkg;
571 }
572
573 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 * Change the permission required to read data from the content
575 * provider. This is normally set for you from its manifest information
576 * when the provider is first created.
577 *
578 * @param permission Name of the permission required for read-only access.
579 */
580 protected final void setReadPermission(String permission) {
581 mReadPermission = permission;
582 }
583
584 /**
585 * Return the name of the permission required for read-only access to
586 * this content provider. This method can be called from multiple
587 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800588 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
589 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 */
591 public final String getReadPermission() {
592 return mReadPermission;
593 }
594
595 /**
596 * Change the permission required to read and write data in the content
597 * provider. This is normally set for you from its manifest information
598 * when the provider is first created.
599 *
600 * @param permission Name of the permission required for read/write access.
601 */
602 protected final void setWritePermission(String permission) {
603 mWritePermission = permission;
604 }
605
606 /**
607 * Return the name of the permission required for read/write access to
608 * this content provider. This method can be called from multiple
609 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800610 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
611 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 */
613 public final String getWritePermission() {
614 return mWritePermission;
615 }
616
617 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700618 * Change the path-based permission required to read and/or write data in
619 * the content provider. This is normally set for you from its manifest
620 * information when the provider is first created.
621 *
622 * @param permissions Array of path permission descriptions.
623 */
624 protected final void setPathPermissions(PathPermission[] permissions) {
625 mPathPermissions = permissions;
626 }
627
628 /**
629 * Return the path-based permissions required for read and/or write access to
630 * this content provider. This method can be called from multiple
631 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800632 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
633 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700634 */
635 public final PathPermission[] getPathPermissions() {
636 return mPathPermissions;
637 }
638
Dianne Hackborn35654b62013-01-14 17:38:02 -0800639 /** @hide */
640 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800641 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800642 mTransport.mReadOp = readOp;
643 mTransport.mWriteOp = writeOp;
644 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800645 }
646
Dianne Hackborn961321f2013-02-05 17:22:41 -0800647 /** @hide */
648 public AppOpsManager getAppOpsManager() {
649 return mTransport.mAppOpsManager;
650 }
651
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700652 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700653 * Implement this to initialize your content provider on startup.
654 * This method is called for all registered content providers on the
655 * application main thread at application launch time. It must not perform
656 * lengthy operations, or application startup will be delayed.
657 *
658 * <p>You should defer nontrivial initialization (such as opening,
659 * upgrading, and scanning databases) until the content provider is used
660 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
661 * keeps application startup fast, avoids unnecessary work if the provider
662 * turns out not to be needed, and stops database errors (such as a full
663 * disk) from halting application launch.
664 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700665 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700666 * is a helpful utility class that makes it easy to manage databases,
667 * and will automatically defer opening until first use. If you do use
668 * SQLiteOpenHelper, make sure to avoid calling
669 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
670 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
671 * from this method. (Instead, override
672 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
673 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 *
675 * @return true if the provider was successfully loaded, false otherwise
676 */
677 public abstract boolean onCreate();
678
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700679 /**
680 * {@inheritDoc}
681 * This method is always called on the application main thread, and must
682 * not perform lengthy operations.
683 *
684 * <p>The default content provider implementation does nothing.
685 * Override this method to take appropriate action.
686 * (Content providers do not usually care about things like screen
687 * orientation, but may want to know about locale changes.)
688 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 public void onConfigurationChanged(Configuration newConfig) {
690 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700691
692 /**
693 * {@inheritDoc}
694 * This method is always called on the application main thread, and must
695 * not perform lengthy operations.
696 *
697 * <p>The default content provider implementation does nothing.
698 * Subclasses may override this method to take appropriate action.
699 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 public void onLowMemory() {
701 }
702
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700703 public void onTrimMemory(int level) {
704 }
705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800707 * @hide
708 * Implementation when a caller has performed a query on the content
709 * provider, but that call has been rejected for the operation given
710 * to {@link #setAppOps(int, int)}. The default implementation
711 * rewrites the <var>selection</var> argument to include a condition
712 * that is never true (so will always result in an empty cursor)
713 * and calls through to {@link #query(android.net.Uri, String[], String, String[],
714 * String, android.os.CancellationSignal)} with that.
715 */
716 public Cursor rejectQuery(Uri uri, String[] projection,
717 String selection, String[] selectionArgs, String sortOrder,
718 CancellationSignal cancellationSignal) {
719 // The read is not allowed... to fake it out, we replace the given
720 // selection statement with a dummy one that will always be false.
721 // This way we will get a cursor back that has the correct structure
722 // but contains no rows.
Dianne Hackborn9fa39bd2013-03-22 18:42:14 -0700723 if (selection == null || selection.isEmpty()) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800724 selection = "'A' = 'B'";
725 } else {
726 selection = "'A' = 'B' AND (" + selection + ")";
727 }
728 return query(uri, projection, selection, selectionArgs, sortOrder, cancellationSignal);
729 }
730
731 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700732 * Implement this to handle query requests from clients.
733 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800734 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
735 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736 * <p>
737 * Example client call:<p>
738 * <pre>// Request a specific record.
739 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000740 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 projection, // Which columns to return.
742 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000743 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 People.NAME + " ASC"); // Sort order.</pre>
745 * Example implementation:<p>
746 * <pre>// SQLiteQueryBuilder is a helper class that creates the
747 // proper SQL syntax for us.
748 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
749
750 // Set the table we're querying.
751 qBuilder.setTables(DATABASE_TABLE_NAME);
752
753 // If the query ends in a specific record number, we're
754 // being asked for a specific record, so set the
755 // WHERE clause in our query.
756 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
757 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
758 }
759
760 // Make the query.
761 Cursor c = qBuilder.query(mDb,
762 projection,
763 selection,
764 selectionArgs,
765 groupBy,
766 having,
767 sortOrder);
768 c.setNotificationUri(getContext().getContentResolver(), uri);
769 return c;</pre>
770 *
771 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000772 * if the client is requesting a specific record, the URI will end in a record number
773 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
774 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800776 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800778 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000779 * @param selectionArgs You may include ?s in selection, which will be replaced by
780 * the values from selectionArgs, in order that they appear in the selection.
781 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800783 * If {@code null} then the provider is free to define the sort order.
784 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 */
786 public abstract Cursor query(Uri uri, String[] projection,
787 String selection, String[] selectionArgs, String sortOrder);
788
Fred Quintana5bba6322009-10-05 14:21:12 -0700789 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800790 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800791 * This method can be called from multiple threads, as described in
792 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
793 * and Threads</a>.
794 * <p>
795 * Example client call:<p>
796 * <pre>// Request a specific record.
797 * Cursor managedCursor = managedQuery(
798 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
799 projection, // Which columns to return.
800 null, // WHERE clause.
801 null, // WHERE clause value substitution
802 People.NAME + " ASC"); // Sort order.</pre>
803 * Example implementation:<p>
804 * <pre>// SQLiteQueryBuilder is a helper class that creates the
805 // proper SQL syntax for us.
806 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
807
808 // Set the table we're querying.
809 qBuilder.setTables(DATABASE_TABLE_NAME);
810
811 // If the query ends in a specific record number, we're
812 // being asked for a specific record, so set the
813 // WHERE clause in our query.
814 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
815 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
816 }
817
818 // Make the query.
819 Cursor c = qBuilder.query(mDb,
820 projection,
821 selection,
822 selectionArgs,
823 groupBy,
824 having,
825 sortOrder);
826 c.setNotificationUri(getContext().getContentResolver(), uri);
827 return c;</pre>
828 * <p>
829 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800830 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
831 * signal to ensure correct operation on older versions of the Android Framework in
832 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800833 *
834 * @param uri The URI to query. This will be the full URI sent by the client;
835 * if the client is requesting a specific record, the URI will end in a record number
836 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
837 * that _id value.
838 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800839 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800840 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800841 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800842 * @param selectionArgs You may include ?s in selection, which will be replaced by
843 * the values from selectionArgs, in order that they appear in the selection.
844 * The values will be bound as Strings.
845 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800846 * If {@code null} then the provider is free to define the sort order.
847 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800848 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
849 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800850 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800851 */
852 public Cursor query(Uri uri, String[] projection,
853 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800854 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800855 return query(uri, projection, selection, selectionArgs, sortOrder);
856 }
857
858 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700859 * Implement this to handle requests for the MIME type of the data at the
860 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 * <code>vnd.android.cursor.item</code> for a single record,
862 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700863 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800864 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
865 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700867 * <p>Note that there are no permissions needed for an application to
868 * access this information; if your content provider requires read and/or
869 * write permissions, or is not exported, all applications can still call
870 * this method regardless of their access permissions. This allows them
871 * to retrieve the MIME type for a URI when dispatching intents.
872 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800874 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 */
876 public abstract String getType(Uri uri);
877
878 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700879 * Implement this to support canonicalization of URIs that refer to your
880 * content provider. A canonical URI is one that can be transported across
881 * devices, backup/restore, and other contexts, and still be able to refer
882 * to the same data item. Typically this is implemented by adding query
883 * params to the URI allowing the content provider to verify that an incoming
884 * canonical URI references the same data as it was originally intended for and,
885 * if it doesn't, to find that data (if it exists) in the current environment.
886 *
887 * <p>For example, if the content provider holds people and a normal URI in it
888 * is created with a row index into that people database, the cananical representation
889 * may have an additional query param at the end which specifies the name of the
890 * person it is intended for. Later calls into the provider with that URI will look
891 * up the row of that URI's base index and, if it doesn't match or its entry's
892 * name doesn't match the name in the query param, perform a query on its database
893 * to find the correct row to operate on.</p>
894 *
895 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
896 * URIs (including this one) must perform this verification and recovery of any
897 * canonical URIs they receive. In addition, you must also implement
898 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
899 *
900 * <p>The default implementation of this method returns null, indicating that
901 * canonical URIs are not supported.</p>
902 *
903 * @param url The Uri to canonicalize.
904 *
905 * @return Return the canonical representation of <var>url</var>, or null if
906 * canonicalization of that Uri is not supported.
907 */
908 public Uri canonicalize(Uri url) {
909 return null;
910 }
911
912 /**
913 * Remove canonicalization from canonical URIs previously returned by
914 * {@link #canonicalize}. For example, if your implementation is to add
915 * a query param to canonicalize a URI, this method can simply trip any
916 * query params on the URI. The default implementation always returns the
917 * same <var>url</var> that was passed in.
918 *
919 * @param url The Uri to remove any canonicalization from.
920 *
921 * @return Return the non-canonical representation of <var>url</var>, or return
922 * the <var>url</var> as-is if there is nothing to do. Never return null.
923 */
924 public Uri uncanonicalize(Uri url) {
925 return url;
926 }
927
928 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800929 * @hide
930 * Implementation when a caller has performed an insert on the content
931 * provider, but that call has been rejected for the operation given
932 * to {@link #setAppOps(int, int)}. The default implementation simply
933 * returns a dummy URI that is the base URI with a 0 path element
934 * appended.
935 */
936 public Uri rejectInsert(Uri uri, ContentValues values) {
937 // If not allowed, we need to return some reasonable URI. Maybe the
938 // content provider should be responsible for this, but for now we
939 // will just return the base URI with a dummy '0' tagged on to it.
940 // You shouldn't be able to read if you can't write, anyway, so it
941 // shouldn't matter much what is returned.
942 return uri.buildUpon().appendPath("0").build();
943 }
944
945 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700946 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
948 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700949 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800950 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
951 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800952 * @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 -0800953 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800954 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 * @return The URI for the newly inserted item.
956 */
957 public abstract Uri insert(Uri uri, ContentValues values);
958
959 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700960 * Override this to handle requests to insert a set of new rows, or the
961 * default implementation will iterate over the values and call
962 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
964 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700965 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800966 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
967 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 *
969 * @param uri The content:// URI of the insertion request.
970 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800971 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 * @return The number of values that were inserted.
973 */
974 public int bulkInsert(Uri uri, ContentValues[] values) {
975 int numValues = values.length;
976 for (int i = 0; i < numValues; i++) {
977 insert(uri, values[i]);
978 }
979 return numValues;
980 }
981
982 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700983 * Implement this to handle requests to delete one or more rows.
984 * The implementation should apply the selection clause when performing
985 * deletion, allowing the operation to affect multiple rows in a directory.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyDelete()}
987 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700988 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800989 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
990 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 *
992 * <p>The implementation is responsible for parsing out a row ID at the end
993 * of the URI, if a specific row is being deleted. That is, the client would
994 * pass in <code>content://contacts/people/22</code> and the implementation is
995 * responsible for parsing the record number (22) when creating a SQL statement.
996 *
997 * @param uri The full URI to query, including a row ID (if a specific record is requested).
998 * @param selection An optional restriction to apply to rows when deleting.
999 * @return The number of rows affected.
1000 * @throws SQLException
1001 */
1002 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
1003
1004 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001005 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001006 * The implementation should update all rows matching the selection
1007 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1009 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001010 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001011 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1012 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 *
1014 * @param uri The URI to query. This can potentially have a record ID if this
1015 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001016 * @param values A set of column_name/value pairs to update in the database.
1017 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 * @param selection An optional filter to match rows to update.
1019 * @return the number of rows affected.
1020 */
1021 public abstract int update(Uri uri, ContentValues values, String selection,
1022 String[] selectionArgs);
1023
1024 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001025 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001026 * The default implementation always throws {@link FileNotFoundException}.
1027 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001028 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1029 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001030 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001031 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1032 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001033 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 *
1035 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1036 * their responsibility to close it when done. That is, the implementation
1037 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001038 * <p>
1039 * If opened with the exclusive "r" or "w" modes, the returned
1040 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1041 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1042 * supports seeking.
1043 * <p>
1044 * If you need to detect when the returned ParcelFileDescriptor has been
1045 * closed, or if the remote process has crashed or encountered some other
1046 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1047 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1048 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1049 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001051 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1052 * to return the appropriate MIME type for the data returned here with
1053 * the same URI. This will allow intent resolution to automatically determine the data MIME
1054 * type and select the appropriate matching targets as part of its operation.</p>
1055 *
1056 * <p class="note">For better interoperability with other applications, it is recommended
1057 * that for any URIs that can be opened, you also support queries on them
1058 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1059 * You may also want to support other common columns if you have additional meta-data
1060 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1061 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1062 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 * @param uri The URI whose file is to be opened.
1064 * @param mode Access mode for the file. May be "r" for read-only access,
1065 * "rw" for read and write access, or "rwt" for read and write access
1066 * that truncates any existing file.
1067 *
1068 * @return Returns a new ParcelFileDescriptor which you can use to access
1069 * the file.
1070 *
1071 * @throws FileNotFoundException Throws FileNotFoundException if there is
1072 * no file associated with the given URI or the mode is invalid.
1073 * @throws SecurityException Throws SecurityException if the caller does
1074 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001075 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 * @see #openAssetFile(Uri, String)
1077 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001078 * @see #getType(android.net.Uri)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001079 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 public ParcelFileDescriptor openFile(Uri uri, String mode)
1081 throws FileNotFoundException {
1082 throw new FileNotFoundException("No files supported by provider at "
1083 + uri);
1084 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001087 * Override this to handle requests to open a file blob.
1088 * The default implementation always throws {@link FileNotFoundException}.
1089 * This method can be called from multiple threads, as described in
1090 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1091 * and Threads</a>.
1092 *
1093 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1094 * to the caller. This way large data (such as images and documents) can be
1095 * returned without copying the content.
1096 *
1097 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1098 * their responsibility to close it when done. That is, the implementation
1099 * of this method should create a new ParcelFileDescriptor for each call.
1100 * <p>
1101 * If opened with the exclusive "r" or "w" modes, the returned
1102 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1103 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1104 * supports seeking.
1105 * <p>
1106 * If you need to detect when the returned ParcelFileDescriptor has been
1107 * closed, or if the remote process has crashed or encountered some other
1108 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1109 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1110 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1111 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1112 *
1113 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1114 * to return the appropriate MIME type for the data returned here with
1115 * the same URI. This will allow intent resolution to automatically determine the data MIME
1116 * type and select the appropriate matching targets as part of its operation.</p>
1117 *
1118 * <p class="note">For better interoperability with other applications, it is recommended
1119 * that for any URIs that can be opened, you also support queries on them
1120 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1121 * You may also want to support other common columns if you have additional meta-data
1122 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1123 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1124 *
1125 * @param uri The URI whose file is to be opened.
1126 * @param mode Access mode for the file. May be "r" for read-only access,
1127 * "w" for write-only access, "rw" for read and write access, or
1128 * "rwt" for read and write access that truncates any existing
1129 * file.
1130 * @param signal A signal to cancel the operation in progress, or
1131 * {@code null} if none. For example, if you are downloading a
1132 * file from the network to service a "rw" mode request, you
1133 * should periodically call
1134 * {@link CancellationSignal#throwIfCanceled()} to check whether
1135 * the client has canceled the request and abort the download.
1136 *
1137 * @return Returns a new ParcelFileDescriptor which you can use to access
1138 * the file.
1139 *
1140 * @throws FileNotFoundException Throws FileNotFoundException if there is
1141 * no file associated with the given URI or the mode is invalid.
1142 * @throws SecurityException Throws SecurityException if the caller does
1143 * not have permission to access the file.
1144 *
1145 * @see #openAssetFile(Uri, String)
1146 * @see #openFileHelper(Uri, String)
1147 * @see #getType(android.net.Uri)
1148 */
1149 public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
1150 throws FileNotFoundException {
1151 return openFile(uri, mode);
1152 }
1153
1154 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 * This is like {@link #openFile}, but can be implemented by providers
1156 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001157 * inside of their .apk.
1158 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001159 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1160 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001161 *
1162 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001163 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001164 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1166 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1167 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001168 * <p>
1169 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1170 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001171 *
1172 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 * should create the AssetFileDescriptor with
1174 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001175 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001177 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1178 * to return the appropriate MIME type for the data returned here with
1179 * the same URI. This will allow intent resolution to automatically determine the data MIME
1180 * type and select the appropriate matching targets as part of its operation.</p>
1181 *
1182 * <p class="note">For better interoperability with other applications, it is recommended
1183 * that for any URIs that can be opened, you also support queries on them
1184 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1185 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 * @param uri The URI whose file is to be opened.
1187 * @param mode Access mode for the file. May be "r" for read-only access,
1188 * "w" for write-only access (erasing whatever data is currently in
1189 * the file), "wa" for write-only access to append to any existing data,
1190 * "rw" for read and write access on any existing data, and "rwt" for read
1191 * and write access that truncates any existing file.
1192 *
1193 * @return Returns a new AssetFileDescriptor which you can use to access
1194 * the file.
1195 *
1196 * @throws FileNotFoundException Throws FileNotFoundException if there is
1197 * no file associated with the given URI or the mode is invalid.
1198 * @throws SecurityException Throws SecurityException if the caller does
1199 * not have permission to access the file.
1200 *
1201 * @see #openFile(Uri, String)
1202 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001203 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 */
1205 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
1206 throws FileNotFoundException {
1207 ParcelFileDescriptor fd = openFile(uri, mode);
1208 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1209 }
1210
1211 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001212 * This is like {@link #openFile}, but can be implemented by providers
1213 * that need to be able to return sub-sections of files, often assets
1214 * inside of their .apk.
1215 * This method can be called from multiple threads, as described in
1216 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1217 * and Threads</a>.
1218 *
1219 * <p>If you implement this, your clients must be able to deal with such
1220 * file slices, either directly with
1221 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1222 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1223 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1224 * methods.
1225 * <p>
1226 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1227 * streaming of data.
1228 *
1229 * <p class="note">If you are implementing this to return a full file, you
1230 * should create the AssetFileDescriptor with
1231 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1232 * applications that cannot handle sub-sections of files.</p>
1233 *
1234 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1235 * to return the appropriate MIME type for the data returned here with
1236 * the same URI. This will allow intent resolution to automatically determine the data MIME
1237 * type and select the appropriate matching targets as part of its operation.</p>
1238 *
1239 * <p class="note">For better interoperability with other applications, it is recommended
1240 * that for any URIs that can be opened, you also support queries on them
1241 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1242 *
1243 * @param uri The URI whose file is to be opened.
1244 * @param mode Access mode for the file. May be "r" for read-only access,
1245 * "w" for write-only access (erasing whatever data is currently in
1246 * the file), "wa" for write-only access to append to any existing data,
1247 * "rw" for read and write access on any existing data, and "rwt" for read
1248 * and write access that truncates any existing file.
1249 * @param signal A signal to cancel the operation in progress, or
1250 * {@code null} if none. For example, if you are downloading a
1251 * file from the network to service a "rw" mode request, you
1252 * should periodically call
1253 * {@link CancellationSignal#throwIfCanceled()} to check whether
1254 * the client has canceled the request and abort the download.
1255 *
1256 * @return Returns a new AssetFileDescriptor which you can use to access
1257 * the file.
1258 *
1259 * @throws FileNotFoundException Throws FileNotFoundException if there is
1260 * no file associated with the given URI or the mode is invalid.
1261 * @throws SecurityException Throws SecurityException if the caller does
1262 * not have permission to access the file.
1263 *
1264 * @see #openFile(Uri, String)
1265 * @see #openFileHelper(Uri, String)
1266 * @see #getType(android.net.Uri)
1267 */
1268 public AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)
1269 throws FileNotFoundException {
1270 return openAssetFile(uri, mode);
1271 }
1272
1273 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 * Convenience for subclasses that wish to implement {@link #openFile}
1275 * by looking up a column named "_data" at the given URI.
1276 *
1277 * @param uri The URI to be opened.
1278 * @param mode The file mode. May be "r" for read-only access,
1279 * "w" for write-only access (erasing whatever data is currently in
1280 * the file), "wa" for write-only access to append to any existing data,
1281 * "rw" for read and write access on any existing data, and "rwt" for read
1282 * and write access that truncates any existing file.
1283 *
1284 * @return Returns a new ParcelFileDescriptor that can be used by the
1285 * client to access the file.
1286 */
1287 protected final ParcelFileDescriptor openFileHelper(Uri uri,
1288 String mode) throws FileNotFoundException {
1289 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1290 int count = (c != null) ? c.getCount() : 0;
1291 if (count != 1) {
1292 // If there is not exactly one result, throw an appropriate
1293 // exception.
1294 if (c != null) {
1295 c.close();
1296 }
1297 if (count == 0) {
1298 throw new FileNotFoundException("No entry for " + uri);
1299 }
1300 throw new FileNotFoundException("Multiple items at " + uri);
1301 }
1302
1303 c.moveToFirst();
1304 int i = c.getColumnIndex("_data");
1305 String path = (i >= 0 ? c.getString(i) : null);
1306 c.close();
1307 if (path == null) {
1308 throw new FileNotFoundException("Column _data not found.");
1309 }
1310
1311 int modeBits = ContentResolver.modeToMode(uri, mode);
1312 return ParcelFileDescriptor.open(new File(path), modeBits);
1313 }
1314
1315 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001316 * Called by a client to determine the types of data streams that this
1317 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001318 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001319 * of a particular type, return that MIME type if it matches the given
1320 * mimeTypeFilter. If it can perform type conversions, return an array
1321 * of all supported MIME types that match mimeTypeFilter.
1322 *
1323 * @param uri The data in the content provider being queried.
1324 * @param mimeTypeFilter The type of data the client desires. May be
1325 * a pattern, such as *\/* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001326 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001327 * given mimeTypeFilter. Otherwise returns an array of all available
1328 * concrete MIME types.
1329 *
1330 * @see #getType(Uri)
1331 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001332 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001333 */
1334 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
1335 return null;
1336 }
1337
1338 /**
1339 * Called by a client to open a read-only stream containing data of a
1340 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1341 * except the file can only be read-only and the content provider may
1342 * perform data conversions to generate data of the desired type.
1343 *
1344 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001345 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001346 * {@link #openAssetFile(Uri, String)}.
1347 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001348 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001349 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001350 * <p>
1351 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1352 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001353 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001354 * <p class="note">For better interoperability with other applications, it is recommended
1355 * that for any URIs that can be opened, you also support queries on them
1356 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1357 * You may also want to support other common columns if you have additional meta-data
1358 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1359 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1360 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001361 * @param uri The data in the content provider being queried.
1362 * @param mimeTypeFilter The type of data the client desires. May be
1363 * a pattern, such as *\/*, if the caller does not have specific type
1364 * requirements; in this case the content provider will pick its best
1365 * type matching the pattern.
1366 * @param opts Additional options from the client. The definitions of
1367 * these are specific to the content provider being called.
1368 *
1369 * @return Returns a new AssetFileDescriptor from which the client can
1370 * read data of the desired type.
1371 *
1372 * @throws FileNotFoundException Throws FileNotFoundException if there is
1373 * no file associated with the given URI or the mode is invalid.
1374 * @throws SecurityException Throws SecurityException if the caller does
1375 * not have permission to access the data.
1376 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1377 * content provider does not support the requested MIME type.
1378 *
1379 * @see #getStreamTypes(Uri, String)
1380 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001381 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001382 */
1383 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
1384 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001385 if ("*/*".equals(mimeTypeFilter)) {
1386 // If they can take anything, the untyped open call is good enough.
1387 return openAssetFile(uri, "r");
1388 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001389 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001390 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001391 // Use old untyped open call if this provider has a type for this
1392 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001393 return openAssetFile(uri, "r");
1394 }
1395 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1396 }
1397
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001398
1399 /**
1400 * Called by a client to open a read-only stream containing data of a
1401 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1402 * except the file can only be read-only and the content provider may
1403 * perform data conversions to generate data of the desired type.
1404 *
1405 * <p>The default implementation compares the given mimeType against the
1406 * result of {@link #getType(Uri)} and, if they match, simply calls
1407 * {@link #openAssetFile(Uri, String)}.
1408 *
1409 * <p>See {@link ClipData} for examples of the use and implementation
1410 * of this method.
1411 * <p>
1412 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1413 * streaming of data.
1414 *
1415 * <p class="note">For better interoperability with other applications, it is recommended
1416 * that for any URIs that can be opened, you also support queries on them
1417 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1418 * You may also want to support other common columns if you have additional meta-data
1419 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1420 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1421 *
1422 * @param uri The data in the content provider being queried.
1423 * @param mimeTypeFilter The type of data the client desires. May be
1424 * a pattern, such as *\/*, if the caller does not have specific type
1425 * requirements; in this case the content provider will pick its best
1426 * type matching the pattern.
1427 * @param opts Additional options from the client. The definitions of
1428 * these are specific to the content provider being called.
1429 * @param signal A signal to cancel the operation in progress, or
1430 * {@code null} if none. For example, if you are downloading a
1431 * file from the network to service a "rw" mode request, you
1432 * should periodically call
1433 * {@link CancellationSignal#throwIfCanceled()} to check whether
1434 * the client has canceled the request and abort the download.
1435 *
1436 * @return Returns a new AssetFileDescriptor from which the client can
1437 * read data of the desired type.
1438 *
1439 * @throws FileNotFoundException Throws FileNotFoundException if there is
1440 * no file associated with the given URI or the mode is invalid.
1441 * @throws SecurityException Throws SecurityException if the caller does
1442 * not have permission to access the data.
1443 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1444 * content provider does not support the requested MIME type.
1445 *
1446 * @see #getStreamTypes(Uri, String)
1447 * @see #openAssetFile(Uri, String)
1448 * @see ClipDescription#compareMimeTypes(String, String)
1449 */
1450 public AssetFileDescriptor openTypedAssetFile(
1451 Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)
1452 throws FileNotFoundException {
1453 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1454 }
1455
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001456 /**
1457 * Interface to write a stream of data to a pipe. Use with
1458 * {@link ContentProvider#openPipeHelper}.
1459 */
1460 public interface PipeDataWriter<T> {
1461 /**
1462 * Called from a background thread to stream data out to a pipe.
1463 * Note that the pipe is blocking, so this thread can block on
1464 * writes for an arbitrary amount of time if the client is slow
1465 * at reading.
1466 *
1467 * @param output The pipe where data should be written. This will be
1468 * closed for you upon returning from this function.
1469 * @param uri The URI whose data is to be written.
1470 * @param mimeType The desired type of data to be written.
1471 * @param opts Options supplied by caller.
1472 * @param args Your own custom arguments.
1473 */
1474 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
1475 Bundle opts, T args);
1476 }
1477
1478 /**
1479 * A helper function for implementing {@link #openTypedAssetFile}, for
1480 * creating a data pipe and background thread allowing you to stream
1481 * generated data back to the client. This function returns a new
1482 * ParcelFileDescriptor that should be returned to the caller (the caller
1483 * is responsible for closing it).
1484 *
1485 * @param uri The URI whose data is to be written.
1486 * @param mimeType The desired type of data to be written.
1487 * @param opts Options supplied by caller.
1488 * @param args Your own custom arguments.
1489 * @param func Interface implementing the function that will actually
1490 * stream the data.
1491 * @return Returns a new ParcelFileDescriptor holding the read side of
1492 * the pipe. This should be returned to the caller for reading; the caller
1493 * is responsible for closing it when done.
1494 */
1495 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
1496 final Bundle opts, final T args, final PipeDataWriter<T> func)
1497 throws FileNotFoundException {
1498 try {
1499 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1500
1501 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1502 @Override
1503 protected Object doInBackground(Object... params) {
1504 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1505 try {
1506 fds[1].close();
1507 } catch (IOException e) {
1508 Log.w(TAG, "Failure closing pipe", e);
1509 }
1510 return null;
1511 }
1512 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001513 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001514
1515 return fds[0];
1516 } catch (IOException e) {
1517 throw new FileNotFoundException("failure making pipe");
1518 }
1519 }
1520
1521 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 * Returns true if this instance is a temporary content provider.
1523 * @return true if this instance is a temporary content provider
1524 */
1525 protected boolean isTemporary() {
1526 return false;
1527 }
1528
1529 /**
1530 * Returns the Binder object for this provider.
1531 *
1532 * @return the Binder object for this provider
1533 * @hide
1534 */
1535 public IContentProvider getIContentProvider() {
1536 return mTransport;
1537 }
1538
1539 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001540 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1541 * when directly instantiating the provider for testing.
1542 * @hide
1543 */
1544 public void attachInfoForTesting(Context context, ProviderInfo info) {
1545 attachInfo(context, info, true);
1546 }
1547
1548 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 * After being instantiated, this is called to tell the content provider
1550 * about itself.
1551 *
1552 * @param context The context this provider is running in
1553 * @param info Registered information about this content provider
1554 */
1555 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001556 attachInfo(context, info, false);
1557 }
1558
1559 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001560 /*
1561 * We may be using AsyncTask from binder threads. Make it init here
1562 * so its static handler is on the main thread.
1563 */
1564 AsyncTask.init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001566 mNoPerms = testing;
1567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 /*
1569 * Only allow it to be set once, so after the content service gives
1570 * this to us clients can't change it.
1571 */
1572 if (mContext == null) {
1573 mContext = context;
Jeff Sharkey911d7f42013-09-05 18:11:45 -07001574 mTransport.mAppOpsManager = (AppOpsManager) mContext.getSystemService(
1575 Context.APP_OPS_SERVICE);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001576 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 if (info != null) {
1578 setReadPermission(info.readPermission);
1579 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001580 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001581 mExported = info.exported;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 }
1583 ContentProvider.this.onCreate();
1584 }
1585 }
Fred Quintanace31b232009-05-04 16:01:15 -07001586
1587 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001588 * Override this to handle requests to perform a batch of operations, or the
1589 * default implementation will iterate over the operations and call
1590 * {@link ContentProviderOperation#apply} on each of them.
1591 * If all calls to {@link ContentProviderOperation#apply} succeed
1592 * then a {@link ContentProviderResult} array with as many
1593 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001594 * fail, it is up to the implementation how many of the others take effect.
1595 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001596 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1597 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001598 *
Fred Quintanace31b232009-05-04 16:01:15 -07001599 * @param operations the operations to apply
1600 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001601 * @throws OperationApplicationException thrown if any operation fails.
1602 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001603 */
Fred Quintana03d94902009-05-22 14:23:31 -07001604 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001605 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001606 final int numOperations = operations.size();
1607 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1608 for (int i = 0; i < numOperations; i++) {
1609 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001610 }
1611 return results;
1612 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001613
1614 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001615 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001616 * interfaces that are cheaper and/or unnatural for a table-like
1617 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001618 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001619 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1620 * on this entry into the content provider besides the basic ability for the application
1621 * to get access to the provider at all. For example, it has no idea whether the call
1622 * being executed may read or write data in the provider, so can't enforce those
1623 * individual permissions. Any implementation of this method <strong>must</strong>
1624 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1625 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001626 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1627 * @param arg provider-defined String argument. May be {@code null}.
1628 * @param extras provider-defined Bundle argument. May be {@code null}.
1629 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001630 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001631 */
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001632 public Bundle call(String method, String arg, Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001633 return null;
1634 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001635
1636 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001637 * Implement this to shut down the ContentProvider instance. You can then
1638 * invoke this method in unit tests.
1639 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001640 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001641 * Android normally handles ContentProvider startup and shutdown
1642 * automatically. You do not need to start up or shut down a
1643 * ContentProvider. When you invoke a test method on a ContentProvider,
1644 * however, a ContentProvider instance is started and keeps running after
1645 * the test finishes, even if a succeeding test instantiates another
1646 * ContentProvider. A conflict develops because the two instances are
1647 * usually running against the same underlying data source (for example, an
1648 * sqlite database).
1649 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001650 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001651 * Implementing shutDown() avoids this conflict by providing a way to
1652 * terminate the ContentProvider. This method can also prevent memory leaks
1653 * from multiple instantiations of the ContentProvider, and it can ensure
1654 * unit test isolation by allowing you to completely clean up the test
1655 * fixture before moving on to the next test.
1656 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001657 */
1658 public void shutdown() {
1659 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1660 "connections are gracefully shutdown");
1661 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001662
1663 /**
1664 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001665 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001666 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001667 * @param fd The raw file descriptor that the dump is being sent to.
1668 * @param writer The PrintWriter to which you should dump your state. This will be
1669 * closed for you after you return.
1670 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001671 */
1672 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1673 writer.println("nothing to dump");
1674 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001675}