blob: bc2d788bf4c80d7bc1487c20d29ee7c4d178e1c6 [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
Nicolas Prevot504d78e2014-06-26 10:07:33 +010019import static android.Manifest.permission.INTERACT_ACROSS_USERS;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070020import static android.app.AppOpsManager.MODE_ALLOWED;
21import static android.app.AppOpsManager.MODE_ERRORED;
22import static android.app.AppOpsManager.MODE_IGNORED;
23import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070024
Jeff Sharkey673db442015-06-11 19:30:57 -070025import android.annotation.NonNull;
Scott Kennedy9f78f652015-03-01 15:29:25 -080026import android.annotation.Nullable;
Dianne Hackborn35654b62013-01-14 17:38:02 -080027import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070028import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.pm.ProviderInfo;
30import android.content.res.AssetFileDescriptor;
31import android.content.res.Configuration;
32import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070033import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.database.SQLException;
35import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070036import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080038import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070039import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080040import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070041import android.os.ICancellationSignal;
42import android.os.OperationCanceledException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070044import android.os.Process;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070045import android.os.UserHandle;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010046import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070047import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048
49import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080050import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070052import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080053import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070054import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080055import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056
57/**
58 * Content providers are one of the primary building blocks of Android applications, providing
59 * content to applications. They encapsulate data and provide it to applications through the single
60 * {@link ContentResolver} interface. A content provider is only required if you need to share
61 * data between multiple applications. For example, the contacts data is used by multiple
62 * applications and must be stored in a content provider. If you don't need to share data amongst
63 * multiple applications you can use a database directly via
64 * {@link android.database.sqlite.SQLiteDatabase}.
65 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 * <p>When a request is made via
67 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
68 * request to the content provider registered with the authority. The content provider can interpret
69 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
70 * URIs.</p>
71 *
72 * <p>The primary methods that need to be implemented are:
73 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070074 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 * <li>{@link #query} which returns data to the caller</li>
76 * <li>{@link #insert} which inserts new data into the content provider</li>
77 * <li>{@link #update} which updates existing data in the content provider</li>
78 * <li>{@link #delete} which deletes data from the content provider</li>
79 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
80 * </ul></p>
81 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070082 * <p class="caution">Data access methods (such as {@link #insert} and
83 * {@link #update}) may be called from many threads at once, and must be thread-safe.
84 * Other methods (such as {@link #onCreate}) are only called from the application
85 * main thread, and must avoid performing lengthy operations. See the method
86 * descriptions for their expected thread behavior.</p>
87 *
88 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
89 * ContentProvider instance, so subclasses don't have to worry about the details of
90 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070091 *
92 * <div class="special reference">
93 * <h3>Developer Guides</h3>
94 * <p>For more information about using content providers, read the
95 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
96 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -070098public abstract class ContentProvider implements ComponentCallbacks2 {
Vasu Nori0c9e14a2010-08-04 13:31:48 -070099 private static final String TAG = "ContentProvider";
100
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900101 /*
102 * Note: if you add methods to ContentProvider, you must add similar methods to
103 * MockContentProvider.
104 */
105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700107 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100108
109 // Since most Providers have only one authority, we keep both a String and a String[] to improve
110 // performance.
111 private String mAuthority;
112 private String[] mAuthorities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 private String mReadPermission;
114 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700115 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700116 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800117 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700118 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700120 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<String>();
121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 private Transport mTransport = new Transport();
123
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700124 /**
125 * Construct a ContentProvider instance. Content providers must be
126 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
127 * in the manifest</a>, accessed with {@link ContentResolver}, and created
128 * automatically by the system, so applications usually do not create
129 * ContentProvider instances directly.
130 *
131 * <p>At construction time, the object is uninitialized, and most fields and
132 * methods are unavailable. Subclasses should initialize themselves in
133 * {@link #onCreate}, not the constructor.
134 *
135 * <p>Content providers are created on the application main thread at
136 * application launch time. The constructor must not perform lengthy
137 * operations, or application startup will be delayed.
138 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900139 public ContentProvider() {
140 }
141
142 /**
143 * Constructor just for mocking.
144 *
145 * @param context A Context object which should be some mock instance (like the
146 * instance of {@link android.test.mock.MockContext}).
147 * @param readPermission The read permision you want this instance should have in the
148 * test, which is available via {@link #getReadPermission()}.
149 * @param writePermission The write permission you want this instance should have
150 * in the test, which is available via {@link #getWritePermission()}.
151 * @param pathPermissions The PathPermissions you want this instance should have
152 * in the test, which is available via {@link #getPathPermissions()}.
153 * @hide
154 */
155 public ContentProvider(
156 Context context,
157 String readPermission,
158 String writePermission,
159 PathPermission[] pathPermissions) {
160 mContext = context;
161 mReadPermission = readPermission;
162 mWritePermission = writePermission;
163 mPathPermissions = pathPermissions;
164 }
165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 /**
167 * Given an IContentProvider, try to coerce it back to the real
168 * ContentProvider object if it is running in the local process. This can
169 * be used if you know you are running in the same process as a provider,
170 * and want to get direct access to its implementation details. Most
171 * clients should not nor have a reason to use it.
172 *
173 * @param abstractInterface The ContentProvider interface that is to be
174 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800175 * @return If the IContentProvider is non-{@code null} and local, returns its actual
176 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 * @hide
178 */
179 public static ContentProvider coerceToLocalContentProvider(
180 IContentProvider abstractInterface) {
181 if (abstractInterface instanceof Transport) {
182 return ((Transport)abstractInterface).getContentProvider();
183 }
184 return null;
185 }
186
187 /**
188 * Binder object that deals with remoting.
189 *
190 * @hide
191 */
192 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800193 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800194 int mReadOp = AppOpsManager.OP_NONE;
195 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 ContentProvider getContentProvider() {
198 return ContentProvider.this;
199 }
200
Jeff Brownd2183652011-10-09 12:39:53 -0700201 @Override
202 public String getProviderName() {
203 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 }
205
Jeff Brown75ea64f2012-01-25 19:37:13 -0800206 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800207 public Cursor query(String callingPkg, Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800208 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800209 ICancellationSignal cancellationSignal) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100210 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100211 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800212 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700213 // The caller has no access to the data, so return an empty cursor with
214 // the columns in the requested order. The caller may ask for an invalid
215 // column and we would not catch that but this is not a problem in practice.
216 // We do not call ContentProvider#query with a modified where clause since
217 // the implementation is not guaranteed to be backed by a SQL database, hence
218 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700219 if (projection != null) {
220 return new MatrixCursor(projection, 0);
221 }
222
223 // Null projection means all columns but we have no idea which they are.
224 // However, the caller may be expecting to access them my index. Hence,
225 // we have to execute the query as if allowed to get a cursor with the
226 // columns. We then use the column names to return an empty cursor.
227 Cursor cursor = ContentProvider.this.query(uri, projection, selection,
228 selectionArgs, sortOrder, CancellationSignal.fromTransport(
229 cancellationSignal));
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700230 if (cursor == null) {
231 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700232 }
233
234 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700235 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800236 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700237 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700238 try {
239 return ContentProvider.this.query(
240 uri, projection, selection, selectionArgs, sortOrder,
241 CancellationSignal.fromTransport(cancellationSignal));
242 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700243 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 }
246
Jeff Brown75ea64f2012-01-25 19:37:13 -0800247 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100249 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100250 uri = getUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 return ContentProvider.this.getType(uri);
252 }
253
Jeff Brown75ea64f2012-01-25 19:37:13 -0800254 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800255 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100256 validateIncomingUri(uri);
257 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100258 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800259 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800260 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800261 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700262 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700263 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100264 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700265 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700266 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 }
269
Jeff Brown75ea64f2012-01-25 19:37:13 -0800270 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800271 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100272 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100273 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800274 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800275 return 0;
276 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700277 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700278 try {
279 return ContentProvider.this.bulkInsert(uri, initialValues);
280 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700281 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 }
284
Jeff Brown75ea64f2012-01-25 19:37:13 -0800285 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800286 public ContentProviderResult[] applyBatch(String callingPkg,
287 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700288 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100289 int numOperations = operations.size();
290 final int[] userIds = new int[numOperations];
291 for (int i = 0; i < numOperations; i++) {
292 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100293 Uri uri = operation.getUri();
294 validateIncomingUri(uri);
295 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100296 if (userIds[i] != UserHandle.USER_CURRENT) {
297 // Removing the user id from the uri.
298 operation = new ContentProviderOperation(operation, true);
299 operations.set(i, operation);
300 }
Fred Quintana89437372009-05-15 15:10:40 -0700301 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800302 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800303 != AppOpsManager.MODE_ALLOWED) {
304 throw new OperationApplicationException("App op not allowed", 0);
305 }
Fred Quintana89437372009-05-15 15:10:40 -0700306 }
Fred Quintana89437372009-05-15 15:10:40 -0700307 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800308 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800309 != AppOpsManager.MODE_ALLOWED) {
310 throw new OperationApplicationException("App op not allowed", 0);
311 }
Fred Quintana89437372009-05-15 15:10:40 -0700312 }
313 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700314 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700315 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100316 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800317 if (results != null) {
318 for (int i = 0; i < results.length ; i++) {
319 if (userIds[i] != UserHandle.USER_CURRENT) {
320 // Adding the userId to the uri.
321 results[i] = new ContentProviderResult(results[i], userIds[i]);
322 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100323 }
324 }
325 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700326 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700327 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700328 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700329 }
330
Jeff Brown75ea64f2012-01-25 19:37:13 -0800331 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800332 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100333 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100334 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800335 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800336 return 0;
337 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700338 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700339 try {
340 return ContentProvider.this.delete(uri, selection, selectionArgs);
341 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700342 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 }
345
Jeff Brown75ea64f2012-01-25 19:37:13 -0800346 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800347 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100349 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100350 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800351 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800352 return 0;
353 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700354 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700355 try {
356 return ContentProvider.this.update(uri, values, selection, selectionArgs);
357 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700358 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 }
361
Jeff Brown75ea64f2012-01-25 19:37:13 -0800362 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700363 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800364 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
365 IBinder callerToken) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100366 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100367 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800368 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700369 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700370 try {
371 return ContentProvider.this.openFile(
372 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
373 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700374 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 }
377
Jeff Brown75ea64f2012-01-25 19:37:13 -0800378 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700379 public AssetFileDescriptor openAssetFile(
380 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100382 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100383 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800384 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700385 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700386 try {
387 return ContentProvider.this.openAssetFile(
388 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
389 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700390 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 }
393
Jeff Brown75ea64f2012-01-25 19:37:13 -0800394 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800395 public Bundle call(
396 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600397 Bundle.setDefusable(extras, true);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700398 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700399 try {
400 return ContentProvider.this.call(method, arg, extras);
401 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700402 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700403 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800404 }
405
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700406 @Override
407 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100408 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100409 uri = getUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700410 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
411 }
412
413 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800414 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700415 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600416 Bundle.setDefusable(opts, true);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100417 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100418 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800419 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700420 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700421 try {
422 return ContentProvider.this.openTypedAssetFile(
423 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
424 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700425 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700426 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700427 }
428
Jeff Brown75ea64f2012-01-25 19:37:13 -0800429 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700430 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800431 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800432 }
433
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700434 @Override
435 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100436 validateIncomingUri(uri);
437 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100438 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800439 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700440 return null;
441 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700442 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700443 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100444 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700445 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700446 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700447 }
448 }
449
450 @Override
451 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100452 validateIncomingUri(uri);
453 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100454 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800455 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700456 return null;
457 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700458 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700459 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100460 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700461 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700462 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700463 }
464 }
465
Dianne Hackbornff170242014-11-19 10:59:01 -0800466 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
467 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800468 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800469 if (enforceWritePermission(callingPkg, uri, callerToken)
470 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800471 throw new FileNotFoundException("App op not allowed");
472 }
473 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800474 if (enforceReadPermission(callingPkg, uri, callerToken)
475 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800476 throw new FileNotFoundException("App op not allowed");
477 }
478 }
479 }
480
Dianne Hackbornff170242014-11-19 10:59:01 -0800481 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
482 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700483 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
484 if (mode != MODE_ALLOWED) {
485 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800486 }
Svet Ganov99b60432015-06-27 13:15:22 -0700487
488 if (mReadOp != AppOpsManager.OP_NONE) {
489 return mAppOpsManager.noteProxyOp(mReadOp, callingPkg);
490 }
491
Dianne Hackborn35654b62013-01-14 17:38:02 -0800492 return AppOpsManager.MODE_ALLOWED;
493 }
494
Dianne Hackbornff170242014-11-19 10:59:01 -0800495 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
496 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700497 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
498 if (mode != MODE_ALLOWED) {
499 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800500 }
Svet Ganov99b60432015-06-27 13:15:22 -0700501
502 if (mWriteOp != AppOpsManager.OP_NONE) {
503 return mAppOpsManager.noteProxyOp(mWriteOp, callingPkg);
504 }
505
Dianne Hackborn35654b62013-01-14 17:38:02 -0800506 return AppOpsManager.MODE_ALLOWED;
507 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700508 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800509
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100510 boolean checkUser(int pid, int uid, Context context) {
511 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700512 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100513 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
514 == PERMISSION_GRANTED;
515 }
516
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700517 /**
518 * Verify that calling app holds both the given permission and any app-op
519 * associated with that permission.
520 */
521 private int checkPermissionAndAppOp(String permission, String callingPkg,
522 IBinder callerToken) {
523 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
524 callerToken) != PERMISSION_GRANTED) {
525 return MODE_ERRORED;
526 }
527
528 final int permOp = AppOpsManager.permissionToOpCode(permission);
529 if (permOp != AppOpsManager.OP_NONE) {
530 return mTransport.mAppOpsManager.noteProxyOp(permOp, callingPkg);
531 }
532
533 return MODE_ALLOWED;
534 }
535
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700536 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700537 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800538 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700539 final Context context = getContext();
540 final int pid = Binder.getCallingPid();
541 final int uid = Binder.getCallingUid();
542 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700543 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700544
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700545 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700546 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700547 }
548
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100549 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700550 final String componentPerm = getReadPermission();
551 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700552 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
553 if (mode == MODE_ALLOWED) {
554 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700555 } else {
556 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700557 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700558 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700559 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700560
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700561 // track if unprotected read is allowed; any denied
562 // <path-permission> below removes this ability
563 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700564
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700565 final PathPermission[] pps = getPathPermissions();
566 if (pps != null) {
567 final String path = uri.getPath();
568 for (PathPermission pp : pps) {
569 final String pathPerm = pp.getReadPermission();
570 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700571 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
572 if (mode == MODE_ALLOWED) {
573 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700574 } else {
575 // any denied <path-permission> means we lose
576 // default <provider> access.
577 allowDefaultRead = false;
578 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700579 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700580 }
581 }
582 }
583 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700584
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700585 // if we passed <path-permission> checks above, and no default
586 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700587 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700589
590 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800591 final int callingUserId = UserHandle.getUserId(uid);
592 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
593 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800594 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
595 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700596 return MODE_ALLOWED;
597 }
598
599 // If the worst denial we found above was ignored, then pass that
600 // ignored through; otherwise we assume it should be a real error below.
601 if (strongestMode == MODE_IGNORED) {
602 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700603 }
604
605 final String failReason = mExported
606 ? " requires " + missingPerm + ", or grantUriPermission()"
607 : " requires the provider be exported, or grantUriPermission()";
608 throw new SecurityException("Permission Denial: reading "
609 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
610 + ", uid=" + uid + failReason);
611 }
612
613 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700614 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800615 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700616 final Context context = getContext();
617 final int pid = Binder.getCallingPid();
618 final int uid = Binder.getCallingUid();
619 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700620 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700621
622 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700623 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700624 }
625
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100626 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700627 final String componentPerm = getWritePermission();
628 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700629 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
630 if (mode == MODE_ALLOWED) {
631 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700632 } else {
633 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700634 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700635 }
636 }
637
638 // track if unprotected write is allowed; any denied
639 // <path-permission> below removes this ability
640 boolean allowDefaultWrite = (componentPerm == null);
641
642 final PathPermission[] pps = getPathPermissions();
643 if (pps != null) {
644 final String path = uri.getPath();
645 for (PathPermission pp : pps) {
646 final String pathPerm = pp.getWritePermission();
647 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700648 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
649 if (mode == MODE_ALLOWED) {
650 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700651 } else {
652 // any denied <path-permission> means we lose
653 // default <provider> access.
654 allowDefaultWrite = false;
655 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700656 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700657 }
658 }
659 }
660 }
661
662 // if we passed <path-permission> checks above, and no default
663 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700664 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700665 }
666
667 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800668 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
669 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700670 return MODE_ALLOWED;
671 }
672
673 // If the worst denial we found above was ignored, then pass that
674 // ignored through; otherwise we assume it should be a real error below.
675 if (strongestMode == MODE_IGNORED) {
676 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700677 }
678
679 final String failReason = mExported
680 ? " requires " + missingPerm + ", or grantUriPermission()"
681 : " requires the provider be exported, or grantUriPermission()";
682 throw new SecurityException("Permission Denial: writing "
683 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
684 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 }
686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700688 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800689 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 * constructor.
691 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700692 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 return mContext;
694 }
695
696 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700697 * Set the calling package, returning the current value (or {@code null})
698 * which can be used later to restore the previous state.
699 */
700 private String setCallingPackage(String callingPackage) {
701 final String original = mCallingPackage.get();
702 mCallingPackage.set(callingPackage);
703 return original;
704 }
705
706 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700707 * Return the package name of the caller that initiated the request being
708 * processed on the current thread. The returned package will have been
709 * verified to belong to the calling UID. Returns {@code null} if not
710 * currently processing a request.
711 * <p>
712 * This will always return {@code null} when processing
713 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
714 *
715 * @see Binder#getCallingUid()
716 * @see Context#grantUriPermission(String, Uri, int)
717 * @throws SecurityException if the calling package doesn't belong to the
718 * calling UID.
719 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700720 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700721 final String pkg = mCallingPackage.get();
722 if (pkg != null) {
723 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
724 }
725 return pkg;
726 }
727
728 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100729 * Change the authorities of the ContentProvider.
730 * This is normally set for you from its manifest information when the provider is first
731 * created.
732 * @hide
733 * @param authorities the semi-colon separated authorities of the ContentProvider.
734 */
735 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100736 if (authorities != null) {
737 if (authorities.indexOf(';') == -1) {
738 mAuthority = authorities;
739 mAuthorities = null;
740 } else {
741 mAuthority = null;
742 mAuthorities = authorities.split(";");
743 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100744 }
745 }
746
747 /** @hide */
748 protected final boolean matchesOurAuthorities(String authority) {
749 if (mAuthority != null) {
750 return mAuthority.equals(authority);
751 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100752 if (mAuthorities != null) {
753 int length = mAuthorities.length;
754 for (int i = 0; i < length; i++) {
755 if (mAuthorities[i].equals(authority)) return true;
756 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100757 }
758 return false;
759 }
760
761
762 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 * Change the permission required to read data from the content
764 * provider. This is normally set for you from its manifest information
765 * when the provider is first created.
766 *
767 * @param permission Name of the permission required for read-only access.
768 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700769 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 mReadPermission = permission;
771 }
772
773 /**
774 * Return the name of the permission required for read-only access to
775 * this content provider. This method can be called from multiple
776 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800777 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
778 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700780 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 return mReadPermission;
782 }
783
784 /**
785 * Change the permission required to read and write data in the content
786 * provider. This is normally set for you from its manifest information
787 * when the provider is first created.
788 *
789 * @param permission Name of the permission required for read/write access.
790 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700791 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 mWritePermission = permission;
793 }
794
795 /**
796 * Return the name of the permission required for read/write access to
797 * this content provider. This method can be called from multiple
798 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800799 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
800 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700802 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 return mWritePermission;
804 }
805
806 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700807 * Change the path-based permission required to read and/or write data in
808 * the content provider. This is normally set for you from its manifest
809 * information when the provider is first created.
810 *
811 * @param permissions Array of path permission descriptions.
812 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700813 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700814 mPathPermissions = permissions;
815 }
816
817 /**
818 * Return the path-based permissions required for read and/or write access to
819 * this content provider. This method can be called from multiple
820 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800821 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
822 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700823 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700824 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700825 return mPathPermissions;
826 }
827
Dianne Hackborn35654b62013-01-14 17:38:02 -0800828 /** @hide */
829 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800830 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800831 mTransport.mReadOp = readOp;
832 mTransport.mWriteOp = writeOp;
833 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800834 }
835
Dianne Hackborn961321f2013-02-05 17:22:41 -0800836 /** @hide */
837 public AppOpsManager getAppOpsManager() {
838 return mTransport.mAppOpsManager;
839 }
840
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700841 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700842 * Implement this to initialize your content provider on startup.
843 * This method is called for all registered content providers on the
844 * application main thread at application launch time. It must not perform
845 * lengthy operations, or application startup will be delayed.
846 *
847 * <p>You should defer nontrivial initialization (such as opening,
848 * upgrading, and scanning databases) until the content provider is used
849 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
850 * keeps application startup fast, avoids unnecessary work if the provider
851 * turns out not to be needed, and stops database errors (such as a full
852 * disk) from halting application launch.
853 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700854 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700855 * is a helpful utility class that makes it easy to manage databases,
856 * and will automatically defer opening until first use. If you do use
857 * SQLiteOpenHelper, make sure to avoid calling
858 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
859 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
860 * from this method. (Instead, override
861 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
862 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 *
864 * @return true if the provider was successfully loaded, false otherwise
865 */
866 public abstract boolean onCreate();
867
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700868 /**
869 * {@inheritDoc}
870 * This method is always called on the application main thread, and must
871 * not perform lengthy operations.
872 *
873 * <p>The default content provider implementation does nothing.
874 * Override this method to take appropriate action.
875 * (Content providers do not usually care about things like screen
876 * orientation, but may want to know about locale changes.)
877 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 public void onConfigurationChanged(Configuration newConfig) {
879 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700880
881 /**
882 * {@inheritDoc}
883 * This method is always called on the application main thread, and must
884 * not perform lengthy operations.
885 *
886 * <p>The default content provider implementation does nothing.
887 * Subclasses may override this method to take appropriate action.
888 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 public void onLowMemory() {
890 }
891
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700892 public void onTrimMemory(int level) {
893 }
894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700896 * Implement this to handle query requests from clients.
897 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800898 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
899 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 * <p>
901 * Example client call:<p>
902 * <pre>// Request a specific record.
903 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000904 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 projection, // Which columns to return.
906 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000907 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 People.NAME + " ASC"); // Sort order.</pre>
909 * Example implementation:<p>
910 * <pre>// SQLiteQueryBuilder is a helper class that creates the
911 // proper SQL syntax for us.
912 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
913
914 // Set the table we're querying.
915 qBuilder.setTables(DATABASE_TABLE_NAME);
916
917 // If the query ends in a specific record number, we're
918 // being asked for a specific record, so set the
919 // WHERE clause in our query.
920 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
921 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
922 }
923
924 // Make the query.
925 Cursor c = qBuilder.query(mDb,
926 projection,
927 selection,
928 selectionArgs,
929 groupBy,
930 having,
931 sortOrder);
932 c.setNotificationUri(getContext().getContentResolver(), uri);
933 return c;</pre>
934 *
935 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000936 * if the client is requesting a specific record, the URI will end in a record number
937 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
938 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800940 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800942 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000943 * @param selectionArgs You may include ?s in selection, which will be replaced by
944 * the values from selectionArgs, in order that they appear in the selection.
945 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800947 * If {@code null} then the provider is free to define the sort order.
948 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700950 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
951 @Nullable String selection, @Nullable String[] selectionArgs,
952 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953
Fred Quintana5bba6322009-10-05 14:21:12 -0700954 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800955 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800956 * This method can be called from multiple threads, as described in
957 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
958 * and Threads</a>.
959 * <p>
960 * Example client call:<p>
961 * <pre>// Request a specific record.
962 * Cursor managedCursor = managedQuery(
963 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
964 projection, // Which columns to return.
965 null, // WHERE clause.
966 null, // WHERE clause value substitution
967 People.NAME + " ASC"); // Sort order.</pre>
968 * Example implementation:<p>
969 * <pre>// SQLiteQueryBuilder is a helper class that creates the
970 // proper SQL syntax for us.
971 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
972
973 // Set the table we're querying.
974 qBuilder.setTables(DATABASE_TABLE_NAME);
975
976 // If the query ends in a specific record number, we're
977 // being asked for a specific record, so set the
978 // WHERE clause in our query.
979 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
980 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
981 }
982
983 // Make the query.
984 Cursor c = qBuilder.query(mDb,
985 projection,
986 selection,
987 selectionArgs,
988 groupBy,
989 having,
990 sortOrder);
991 c.setNotificationUri(getContext().getContentResolver(), uri);
992 return c;</pre>
993 * <p>
994 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800995 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
996 * signal to ensure correct operation on older versions of the Android Framework in
997 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800998 *
999 * @param uri The URI to query. This will be the full URI sent by the client;
1000 * if the client is requesting a specific record, the URI will end in a record number
1001 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1002 * that _id value.
1003 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001004 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001005 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001006 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001007 * @param selectionArgs You may include ?s in selection, which will be replaced by
1008 * the values from selectionArgs, in order that they appear in the selection.
1009 * The values will be bound as Strings.
1010 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001011 * If {@code null} then the provider is free to define the sort order.
1012 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001013 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
1014 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001015 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001016 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001017 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1018 @Nullable String selection, @Nullable String[] selectionArgs,
1019 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001020 return query(uri, projection, selection, selectionArgs, sortOrder);
1021 }
1022
1023 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001024 * Implement this to handle requests for the MIME type of the data at the
1025 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 * <code>vnd.android.cursor.item</code> for a single record,
1027 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001028 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001029 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1030 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001032 * <p>Note that there are no permissions needed for an application to
1033 * access this information; if your content provider requires read and/or
1034 * write permissions, or is not exported, all applications can still call
1035 * this method regardless of their access permissions. This allows them
1036 * to retrieve the MIME type for a URI when dispatching intents.
1037 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001039 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001041 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042
1043 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001044 * Implement this to support canonicalization of URIs that refer to your
1045 * content provider. A canonical URI is one that can be transported across
1046 * devices, backup/restore, and other contexts, and still be able to refer
1047 * to the same data item. Typically this is implemented by adding query
1048 * params to the URI allowing the content provider to verify that an incoming
1049 * canonical URI references the same data as it was originally intended for and,
1050 * if it doesn't, to find that data (if it exists) in the current environment.
1051 *
1052 * <p>For example, if the content provider holds people and a normal URI in it
1053 * is created with a row index into that people database, the cananical representation
1054 * may have an additional query param at the end which specifies the name of the
1055 * person it is intended for. Later calls into the provider with that URI will look
1056 * up the row of that URI's base index and, if it doesn't match or its entry's
1057 * name doesn't match the name in the query param, perform a query on its database
1058 * to find the correct row to operate on.</p>
1059 *
1060 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1061 * URIs (including this one) must perform this verification and recovery of any
1062 * canonical URIs they receive. In addition, you must also implement
1063 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1064 *
1065 * <p>The default implementation of this method returns null, indicating that
1066 * canonical URIs are not supported.</p>
1067 *
1068 * @param url The Uri to canonicalize.
1069 *
1070 * @return Return the canonical representation of <var>url</var>, or null if
1071 * canonicalization of that Uri is not supported.
1072 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001073 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001074 return null;
1075 }
1076
1077 /**
1078 * Remove canonicalization from canonical URIs previously returned by
1079 * {@link #canonicalize}. For example, if your implementation is to add
1080 * a query param to canonicalize a URI, this method can simply trip any
1081 * query params on the URI. The default implementation always returns the
1082 * same <var>url</var> that was passed in.
1083 *
1084 * @param url The Uri to remove any canonicalization from.
1085 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001086 * @return Return the non-canonical representation of <var>url</var>, return
1087 * the <var>url</var> as-is if there is nothing to do, or return null if
1088 * the data identified by the canonical representation can not be found in
1089 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001090 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001091 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001092 return url;
1093 }
1094
1095 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001096 * @hide
1097 * Implementation when a caller has performed an insert on the content
1098 * provider, but that call has been rejected for the operation given
1099 * to {@link #setAppOps(int, int)}. The default implementation simply
1100 * returns a dummy URI that is the base URI with a 0 path element
1101 * appended.
1102 */
1103 public Uri rejectInsert(Uri uri, ContentValues values) {
1104 // If not allowed, we need to return some reasonable URI. Maybe the
1105 // content provider should be responsible for this, but for now we
1106 // will just return the base URI with a dummy '0' tagged on to it.
1107 // You shouldn't be able to read if you can't write, anyway, so it
1108 // shouldn't matter much what is returned.
1109 return uri.buildUpon().appendPath("0").build();
1110 }
1111
1112 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001113 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1115 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001116 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001117 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1118 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001119 * @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 -08001120 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001121 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 * @return The URI for the newly inserted item.
1123 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001124 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125
1126 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001127 * Override this to handle requests to insert a set of new rows, or the
1128 * default implementation will iterate over the values and call
1129 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1131 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001132 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001133 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1134 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 *
1136 * @param uri The content:// URI of the insertion request.
1137 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001138 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 * @return The number of values that were inserted.
1140 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001141 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 int numValues = values.length;
1143 for (int i = 0; i < numValues; i++) {
1144 insert(uri, values[i]);
1145 }
1146 return numValues;
1147 }
1148
1149 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001150 * Implement this to handle requests to delete one or more rows.
1151 * The implementation should apply the selection clause when performing
1152 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001153 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001155 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001156 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1157 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 *
1159 * <p>The implementation is responsible for parsing out a row ID at the end
1160 * of the URI, if a specific row is being deleted. That is, the client would
1161 * pass in <code>content://contacts/people/22</code> and the implementation is
1162 * responsible for parsing the record number (22) when creating a SQL statement.
1163 *
1164 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1165 * @param selection An optional restriction to apply to rows when deleting.
1166 * @return The number of rows affected.
1167 * @throws SQLException
1168 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001169 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1170 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171
1172 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001173 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001174 * The implementation should update all rows matching the selection
1175 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1177 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001178 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001179 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1180 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 *
1182 * @param uri The URI to query. This can potentially have a record ID if this
1183 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001184 * @param values A set of column_name/value pairs to update in the database.
1185 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 * @param selection An optional filter to match rows to update.
1187 * @return the number of rows affected.
1188 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001189 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001190 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191
1192 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001193 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001194 * The default implementation always throws {@link FileNotFoundException}.
1195 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001196 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1197 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001198 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001199 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1200 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001201 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 *
1203 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1204 * their responsibility to close it when done. That is, the implementation
1205 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001206 * <p>
1207 * If opened with the exclusive "r" or "w" modes, the returned
1208 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1209 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1210 * supports seeking.
1211 * <p>
1212 * If you need to detect when the returned ParcelFileDescriptor has been
1213 * closed, or if the remote process has crashed or encountered some other
1214 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1215 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1216 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1217 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001219 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1220 * to return the appropriate MIME type for the data returned here with
1221 * the same URI. This will allow intent resolution to automatically determine the data MIME
1222 * type and select the appropriate matching targets as part of its operation.</p>
1223 *
1224 * <p class="note">For better interoperability with other applications, it is recommended
1225 * that for any URIs that can be opened, you also support queries on them
1226 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1227 * You may also want to support other common columns if you have additional meta-data
1228 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1229 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1230 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 * @param uri The URI whose file is to be opened.
1232 * @param mode Access mode for the file. May be "r" for read-only access,
1233 * "rw" for read and write access, or "rwt" for read and write access
1234 * that truncates any existing file.
1235 *
1236 * @return Returns a new ParcelFileDescriptor which you can use to access
1237 * the file.
1238 *
1239 * @throws FileNotFoundException Throws FileNotFoundException if there is
1240 * no file associated with the given URI or the mode is invalid.
1241 * @throws SecurityException Throws SecurityException if the caller does
1242 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001243 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 * @see #openAssetFile(Uri, String)
1245 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001246 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001247 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001248 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001249 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 throws FileNotFoundException {
1251 throw new FileNotFoundException("No files supported by provider at "
1252 + uri);
1253 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001256 * Override this to handle requests to open a file blob.
1257 * The default implementation always throws {@link FileNotFoundException}.
1258 * This method can be called from multiple threads, as described in
1259 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1260 * and Threads</a>.
1261 *
1262 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1263 * to the caller. This way large data (such as images and documents) can be
1264 * returned without copying the content.
1265 *
1266 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1267 * their responsibility to close it when done. That is, the implementation
1268 * of this method should create a new ParcelFileDescriptor for each call.
1269 * <p>
1270 * If opened with the exclusive "r" or "w" modes, the returned
1271 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1272 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1273 * supports seeking.
1274 * <p>
1275 * If you need to detect when the returned ParcelFileDescriptor has been
1276 * closed, or if the remote process has crashed or encountered some other
1277 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1278 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1279 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1280 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1281 *
1282 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1283 * to return the appropriate MIME type for the data returned here with
1284 * the same URI. This will allow intent resolution to automatically determine the data MIME
1285 * type and select the appropriate matching targets as part of its operation.</p>
1286 *
1287 * <p class="note">For better interoperability with other applications, it is recommended
1288 * that for any URIs that can be opened, you also support queries on them
1289 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1290 * You may also want to support other common columns if you have additional meta-data
1291 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1292 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1293 *
1294 * @param uri The URI whose file is to be opened.
1295 * @param mode Access mode for the file. May be "r" for read-only access,
1296 * "w" for write-only access, "rw" for read and write access, or
1297 * "rwt" for read and write access that truncates any existing
1298 * file.
1299 * @param signal A signal to cancel the operation in progress, or
1300 * {@code null} if none. For example, if you are downloading a
1301 * file from the network to service a "rw" mode request, you
1302 * should periodically call
1303 * {@link CancellationSignal#throwIfCanceled()} to check whether
1304 * the client has canceled the request and abort the download.
1305 *
1306 * @return Returns a new ParcelFileDescriptor which you can use to access
1307 * the file.
1308 *
1309 * @throws FileNotFoundException Throws FileNotFoundException if there is
1310 * no file associated with the given URI or the mode is invalid.
1311 * @throws SecurityException Throws SecurityException if the caller does
1312 * not have permission to access the file.
1313 *
1314 * @see #openAssetFile(Uri, String)
1315 * @see #openFileHelper(Uri, String)
1316 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001317 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001318 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001319 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1320 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001321 return openFile(uri, mode);
1322 }
1323
1324 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 * This is like {@link #openFile}, but can be implemented by providers
1326 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001327 * inside of their .apk.
1328 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001329 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1330 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001331 *
1332 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001333 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001334 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1336 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1337 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001338 * <p>
1339 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1340 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001341 *
1342 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 * should create the AssetFileDescriptor with
1344 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001345 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001347 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1348 * to return the appropriate MIME type for the data returned here with
1349 * the same URI. This will allow intent resolution to automatically determine the data MIME
1350 * type and select the appropriate matching targets as part of its operation.</p>
1351 *
1352 * <p class="note">For better interoperability with other applications, it is recommended
1353 * that for any URIs that can be opened, you also support queries on them
1354 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1355 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 * @param uri The URI whose file is to be opened.
1357 * @param mode Access mode for the file. May be "r" for read-only access,
1358 * "w" for write-only access (erasing whatever data is currently in
1359 * the file), "wa" for write-only access to append to any existing data,
1360 * "rw" for read and write access on any existing data, and "rwt" for read
1361 * and write access that truncates any existing file.
1362 *
1363 * @return Returns a new AssetFileDescriptor which you can use to access
1364 * the file.
1365 *
1366 * @throws FileNotFoundException Throws FileNotFoundException if there is
1367 * no file associated with the given URI or the mode is invalid.
1368 * @throws SecurityException Throws SecurityException if the caller does
1369 * not have permission to access the file.
1370 *
1371 * @see #openFile(Uri, String)
1372 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001373 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001375 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 throws FileNotFoundException {
1377 ParcelFileDescriptor fd = openFile(uri, mode);
1378 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1379 }
1380
1381 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001382 * This is like {@link #openFile}, but can be implemented by providers
1383 * that need to be able to return sub-sections of files, often assets
1384 * inside of their .apk.
1385 * This method can be called from multiple threads, as described in
1386 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1387 * and Threads</a>.
1388 *
1389 * <p>If you implement this, your clients must be able to deal with such
1390 * file slices, either directly with
1391 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1392 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1393 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1394 * methods.
1395 * <p>
1396 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1397 * streaming of data.
1398 *
1399 * <p class="note">If you are implementing this to return a full file, you
1400 * should create the AssetFileDescriptor with
1401 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1402 * applications that cannot handle sub-sections of files.</p>
1403 *
1404 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1405 * to return the appropriate MIME type for the data returned here with
1406 * the same URI. This will allow intent resolution to automatically determine the data MIME
1407 * type and select the appropriate matching targets as part of its operation.</p>
1408 *
1409 * <p class="note">For better interoperability with other applications, it is recommended
1410 * that for any URIs that can be opened, you also support queries on them
1411 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1412 *
1413 * @param uri The URI whose file is to be opened.
1414 * @param mode Access mode for the file. May be "r" for read-only access,
1415 * "w" for write-only access (erasing whatever data is currently in
1416 * the file), "wa" for write-only access to append to any existing data,
1417 * "rw" for read and write access on any existing data, and "rwt" for read
1418 * and write access that truncates any existing file.
1419 * @param signal A signal to cancel the operation in progress, or
1420 * {@code null} if none. For example, if you are downloading a
1421 * file from the network to service a "rw" mode request, you
1422 * should periodically call
1423 * {@link CancellationSignal#throwIfCanceled()} to check whether
1424 * the client has canceled the request and abort the download.
1425 *
1426 * @return Returns a new AssetFileDescriptor which you can use to access
1427 * the file.
1428 *
1429 * @throws FileNotFoundException Throws FileNotFoundException if there is
1430 * no file associated with the given URI or the mode is invalid.
1431 * @throws SecurityException Throws SecurityException if the caller does
1432 * not have permission to access the file.
1433 *
1434 * @see #openFile(Uri, String)
1435 * @see #openFileHelper(Uri, String)
1436 * @see #getType(android.net.Uri)
1437 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001438 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1439 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001440 return openAssetFile(uri, mode);
1441 }
1442
1443 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 * Convenience for subclasses that wish to implement {@link #openFile}
1445 * by looking up a column named "_data" at the given URI.
1446 *
1447 * @param uri The URI to be opened.
1448 * @param mode The file mode. May be "r" for read-only access,
1449 * "w" for write-only access (erasing whatever data is currently in
1450 * the file), "wa" for write-only access to append to any existing data,
1451 * "rw" for read and write access on any existing data, and "rwt" for read
1452 * and write access that truncates any existing file.
1453 *
1454 * @return Returns a new ParcelFileDescriptor that can be used by the
1455 * client to access the file.
1456 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001457 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1458 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1460 int count = (c != null) ? c.getCount() : 0;
1461 if (count != 1) {
1462 // If there is not exactly one result, throw an appropriate
1463 // exception.
1464 if (c != null) {
1465 c.close();
1466 }
1467 if (count == 0) {
1468 throw new FileNotFoundException("No entry for " + uri);
1469 }
1470 throw new FileNotFoundException("Multiple items at " + uri);
1471 }
1472
1473 c.moveToFirst();
1474 int i = c.getColumnIndex("_data");
1475 String path = (i >= 0 ? c.getString(i) : null);
1476 c.close();
1477 if (path == null) {
1478 throw new FileNotFoundException("Column _data not found.");
1479 }
1480
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001481 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 return ParcelFileDescriptor.open(new File(path), modeBits);
1483 }
1484
1485 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001486 * Called by a client to determine the types of data streams that this
1487 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001488 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001489 * of a particular type, return that MIME type if it matches the given
1490 * mimeTypeFilter. If it can perform type conversions, return an array
1491 * of all supported MIME types that match mimeTypeFilter.
1492 *
1493 * @param uri The data in the content provider being queried.
1494 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001495 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001496 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001497 * given mimeTypeFilter. Otherwise returns an array of all available
1498 * concrete MIME types.
1499 *
1500 * @see #getType(Uri)
1501 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001502 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001503 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001504 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001505 return null;
1506 }
1507
1508 /**
1509 * Called by a client to open a read-only stream containing data of a
1510 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1511 * except the file can only be read-only and the content provider may
1512 * perform data conversions to generate data of the desired type.
1513 *
1514 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001515 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001516 * {@link #openAssetFile(Uri, String)}.
1517 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001518 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001519 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001520 * <p>
1521 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1522 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001523 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001524 * <p class="note">For better interoperability with other applications, it is recommended
1525 * that for any URIs that can be opened, you also support queries on them
1526 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1527 * You may also want to support other common columns if you have additional meta-data
1528 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1529 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1530 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001531 * @param uri The data in the content provider being queried.
1532 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001533 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001534 * requirements; in this case the content provider will pick its best
1535 * type matching the pattern.
1536 * @param opts Additional options from the client. The definitions of
1537 * these are specific to the content provider being called.
1538 *
1539 * @return Returns a new AssetFileDescriptor from which the client can
1540 * read data of the desired type.
1541 *
1542 * @throws FileNotFoundException Throws FileNotFoundException if there is
1543 * no file associated with the given URI or the mode is invalid.
1544 * @throws SecurityException Throws SecurityException if the caller does
1545 * not have permission to access the data.
1546 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1547 * content provider does not support the requested MIME type.
1548 *
1549 * @see #getStreamTypes(Uri, String)
1550 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001551 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001552 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001553 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1554 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001555 if ("*/*".equals(mimeTypeFilter)) {
1556 // If they can take anything, the untyped open call is good enough.
1557 return openAssetFile(uri, "r");
1558 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001559 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001560 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001561 // Use old untyped open call if this provider has a type for this
1562 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001563 return openAssetFile(uri, "r");
1564 }
1565 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1566 }
1567
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001568
1569 /**
1570 * Called by a client to open a read-only stream containing data of a
1571 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1572 * except the file can only be read-only and the content provider may
1573 * perform data conversions to generate data of the desired type.
1574 *
1575 * <p>The default implementation compares the given mimeType against the
1576 * result of {@link #getType(Uri)} and, if they match, simply calls
1577 * {@link #openAssetFile(Uri, String)}.
1578 *
1579 * <p>See {@link ClipData} for examples of the use and implementation
1580 * of this method.
1581 * <p>
1582 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1583 * streaming of data.
1584 *
1585 * <p class="note">For better interoperability with other applications, it is recommended
1586 * that for any URIs that can be opened, you also support queries on them
1587 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1588 * You may also want to support other common columns if you have additional meta-data
1589 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1590 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1591 *
1592 * @param uri The data in the content provider being queried.
1593 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001594 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001595 * requirements; in this case the content provider will pick its best
1596 * type matching the pattern.
1597 * @param opts Additional options from the client. The definitions of
1598 * these are specific to the content provider being called.
1599 * @param signal A signal to cancel the operation in progress, or
1600 * {@code null} if none. For example, if you are downloading a
1601 * file from the network to service a "rw" mode request, you
1602 * should periodically call
1603 * {@link CancellationSignal#throwIfCanceled()} to check whether
1604 * the client has canceled the request and abort the download.
1605 *
1606 * @return Returns a new AssetFileDescriptor from which the client can
1607 * read data of the desired type.
1608 *
1609 * @throws FileNotFoundException Throws FileNotFoundException if there is
1610 * no file associated with the given URI or the mode is invalid.
1611 * @throws SecurityException Throws SecurityException if the caller does
1612 * not have permission to access the data.
1613 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1614 * content provider does not support the requested MIME type.
1615 *
1616 * @see #getStreamTypes(Uri, String)
1617 * @see #openAssetFile(Uri, String)
1618 * @see ClipDescription#compareMimeTypes(String, String)
1619 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001620 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1621 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1622 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001623 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1624 }
1625
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001626 /**
1627 * Interface to write a stream of data to a pipe. Use with
1628 * {@link ContentProvider#openPipeHelper}.
1629 */
1630 public interface PipeDataWriter<T> {
1631 /**
1632 * Called from a background thread to stream data out to a pipe.
1633 * Note that the pipe is blocking, so this thread can block on
1634 * writes for an arbitrary amount of time if the client is slow
1635 * at reading.
1636 *
1637 * @param output The pipe where data should be written. This will be
1638 * closed for you upon returning from this function.
1639 * @param uri The URI whose data is to be written.
1640 * @param mimeType The desired type of data to be written.
1641 * @param opts Options supplied by caller.
1642 * @param args Your own custom arguments.
1643 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001644 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1645 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001646 }
1647
1648 /**
1649 * A helper function for implementing {@link #openTypedAssetFile}, for
1650 * creating a data pipe and background thread allowing you to stream
1651 * generated data back to the client. This function returns a new
1652 * ParcelFileDescriptor that should be returned to the caller (the caller
1653 * is responsible for closing it).
1654 *
1655 * @param uri The URI whose data is to be written.
1656 * @param mimeType The desired type of data to be written.
1657 * @param opts Options supplied by caller.
1658 * @param args Your own custom arguments.
1659 * @param func Interface implementing the function that will actually
1660 * stream the data.
1661 * @return Returns a new ParcelFileDescriptor holding the read side of
1662 * the pipe. This should be returned to the caller for reading; the caller
1663 * is responsible for closing it when done.
1664 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001665 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1666 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1667 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001668 try {
1669 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1670
1671 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1672 @Override
1673 protected Object doInBackground(Object... params) {
1674 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1675 try {
1676 fds[1].close();
1677 } catch (IOException e) {
1678 Log.w(TAG, "Failure closing pipe", e);
1679 }
1680 return null;
1681 }
1682 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001683 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001684
1685 return fds[0];
1686 } catch (IOException e) {
1687 throw new FileNotFoundException("failure making pipe");
1688 }
1689 }
1690
1691 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 * Returns true if this instance is a temporary content provider.
1693 * @return true if this instance is a temporary content provider
1694 */
1695 protected boolean isTemporary() {
1696 return false;
1697 }
1698
1699 /**
1700 * Returns the Binder object for this provider.
1701 *
1702 * @return the Binder object for this provider
1703 * @hide
1704 */
1705 public IContentProvider getIContentProvider() {
1706 return mTransport;
1707 }
1708
1709 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001710 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1711 * when directly instantiating the provider for testing.
1712 * @hide
1713 */
1714 public void attachInfoForTesting(Context context, ProviderInfo info) {
1715 attachInfo(context, info, true);
1716 }
1717
1718 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 * After being instantiated, this is called to tell the content provider
1720 * about itself.
1721 *
1722 * @param context The context this provider is running in
1723 * @param info Registered information about this content provider
1724 */
1725 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001726 attachInfo(context, info, false);
1727 }
1728
1729 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001730 mNoPerms = testing;
1731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 /*
1733 * Only allow it to be set once, so after the content service gives
1734 * this to us clients can't change it.
1735 */
1736 if (mContext == null) {
1737 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001738 if (context != null) {
1739 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1740 Context.APP_OPS_SERVICE);
1741 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001742 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 if (info != null) {
1744 setReadPermission(info.readPermission);
1745 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001746 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001747 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001748 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001749 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 }
1751 ContentProvider.this.onCreate();
1752 }
1753 }
Fred Quintanace31b232009-05-04 16:01:15 -07001754
1755 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001756 * Override this to handle requests to perform a batch of operations, or the
1757 * default implementation will iterate over the operations and call
1758 * {@link ContentProviderOperation#apply} on each of them.
1759 * If all calls to {@link ContentProviderOperation#apply} succeed
1760 * then a {@link ContentProviderResult} array with as many
1761 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001762 * fail, it is up to the implementation how many of the others take effect.
1763 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001764 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1765 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001766 *
Fred Quintanace31b232009-05-04 16:01:15 -07001767 * @param operations the operations to apply
1768 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001769 * @throws OperationApplicationException thrown if any operation fails.
1770 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001771 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001772 public @NonNull ContentProviderResult[] applyBatch(
1773 @NonNull ArrayList<ContentProviderOperation> operations)
1774 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001775 final int numOperations = operations.size();
1776 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1777 for (int i = 0; i < numOperations; i++) {
1778 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001779 }
1780 return results;
1781 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001782
1783 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001784 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001785 * interfaces that are cheaper and/or unnatural for a table-like
1786 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001787 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001788 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1789 * on this entry into the content provider besides the basic ability for the application
1790 * to get access to the provider at all. For example, it has no idea whether the call
1791 * being executed may read or write data in the provider, so can't enforce those
1792 * individual permissions. Any implementation of this method <strong>must</strong>
1793 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1794 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001795 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1796 * @param arg provider-defined String argument. May be {@code null}.
1797 * @param extras provider-defined Bundle argument. May be {@code null}.
1798 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001799 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001800 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001801 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
1802 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001803 return null;
1804 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001805
1806 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001807 * Implement this to shut down the ContentProvider instance. You can then
1808 * invoke this method in unit tests.
1809 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001810 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001811 * Android normally handles ContentProvider startup and shutdown
1812 * automatically. You do not need to start up or shut down a
1813 * ContentProvider. When you invoke a test method on a ContentProvider,
1814 * however, a ContentProvider instance is started and keeps running after
1815 * the test finishes, even if a succeeding test instantiates another
1816 * ContentProvider. A conflict develops because the two instances are
1817 * usually running against the same underlying data source (for example, an
1818 * sqlite database).
1819 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001820 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001821 * Implementing shutDown() avoids this conflict by providing a way to
1822 * terminate the ContentProvider. This method can also prevent memory leaks
1823 * from multiple instantiations of the ContentProvider, and it can ensure
1824 * unit test isolation by allowing you to completely clean up the test
1825 * fixture before moving on to the next test.
1826 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001827 */
1828 public void shutdown() {
1829 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1830 "connections are gracefully shutdown");
1831 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001832
1833 /**
1834 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001835 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001836 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001837 * @param fd The raw file descriptor that the dump is being sent to.
1838 * @param writer The PrintWriter to which you should dump your state. This will be
1839 * closed for you after you return.
1840 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001841 */
1842 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1843 writer.println("nothing to dump");
1844 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001845
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001846 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001847 private void validateIncomingUri(Uri uri) throws SecurityException {
1848 String auth = uri.getAuthority();
1849 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001850 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
1851 throw new SecurityException("trying to query a ContentProvider in user "
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001852 + mContext.getUserId() + " with a uri belonging to user " + userId);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001853 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001854 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
1855 String message = "The authority of the uri " + uri + " does not match the one of the "
1856 + "contentProvider: ";
1857 if (mAuthority != null) {
1858 message += mAuthority;
1859 } else {
Andreas Gampee6748ce2015-12-11 18:00:38 -08001860 message += Arrays.toString(mAuthorities);
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001861 }
1862 throw new SecurityException(message);
1863 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001864 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001865
1866 /** @hide */
1867 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1868 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001869 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001870 if (end == -1) return defaultUserId;
1871 String userIdString = auth.substring(0, end);
1872 try {
1873 return Integer.parseInt(userIdString);
1874 } catch (NumberFormatException e) {
1875 Log.w(TAG, "Error parsing userId.", e);
1876 return UserHandle.USER_NULL;
1877 }
1878 }
1879
1880 /** @hide */
1881 public static int getUserIdFromAuthority(String auth) {
1882 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1883 }
1884
1885 /** @hide */
1886 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1887 if (uri == null) return defaultUserId;
1888 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1889 }
1890
1891 /** @hide */
1892 public static int getUserIdFromUri(Uri uri) {
1893 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1894 }
1895
1896 /**
1897 * Removes userId part from authority string. Expects format:
1898 * userId@some.authority
1899 * If there is no userId in the authority, it symply returns the argument
1900 * @hide
1901 */
1902 public static String getAuthorityWithoutUserId(String auth) {
1903 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001904 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001905 return auth.substring(end+1);
1906 }
1907
1908 /** @hide */
1909 public static Uri getUriWithoutUserId(Uri uri) {
1910 if (uri == null) return null;
1911 Uri.Builder builder = uri.buildUpon();
1912 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1913 return builder.build();
1914 }
1915
1916 /** @hide */
1917 public static boolean uriHasUserId(Uri uri) {
1918 if (uri == null) return false;
1919 return !TextUtils.isEmpty(uri.getUserInfo());
1920 }
1921
1922 /** @hide */
1923 public static Uri maybeAddUserId(Uri uri, int userId) {
1924 if (uri == null) return null;
1925 if (userId != UserHandle.USER_CURRENT
1926 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1927 if (!uriHasUserId(uri)) {
1928 //We don't add the user Id if there's already one
1929 Uri.Builder builder = uri.buildUpon();
1930 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1931 return builder.build();
1932 }
1933 }
1934 return uri;
1935 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001936}