blob: 1c3f45cdbde85e5de7f4fa1f6c3fb0b636570ce2 [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 Sharkey72e2e352013-09-09 18:52:48 -0700397 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700398 try {
399 return ContentProvider.this.call(method, arg, extras);
400 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700401 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700402 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800403 }
404
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700405 @Override
406 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100407 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100408 uri = getUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700409 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
410 }
411
412 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800413 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700414 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100415 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100416 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800417 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700418 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700419 try {
420 return ContentProvider.this.openTypedAssetFile(
421 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
422 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700423 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700424 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700425 }
426
Jeff Brown75ea64f2012-01-25 19:37:13 -0800427 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700428 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800429 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800430 }
431
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700432 @Override
433 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100434 validateIncomingUri(uri);
435 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100436 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800437 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700438 return null;
439 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700440 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700441 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100442 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700443 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700444 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700445 }
446 }
447
448 @Override
449 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100450 validateIncomingUri(uri);
451 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100452 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800453 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700454 return null;
455 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700456 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700457 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100458 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700459 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700460 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700461 }
462 }
463
Dianne Hackbornff170242014-11-19 10:59:01 -0800464 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
465 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800466 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800467 if (enforceWritePermission(callingPkg, uri, callerToken)
468 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800469 throw new FileNotFoundException("App op not allowed");
470 }
471 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800472 if (enforceReadPermission(callingPkg, uri, callerToken)
473 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800474 throw new FileNotFoundException("App op not allowed");
475 }
476 }
477 }
478
Dianne Hackbornff170242014-11-19 10:59:01 -0800479 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
480 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700481 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
482 if (mode != MODE_ALLOWED) {
483 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800484 }
Svet Ganov99b60432015-06-27 13:15:22 -0700485
486 if (mReadOp != AppOpsManager.OP_NONE) {
487 return mAppOpsManager.noteProxyOp(mReadOp, callingPkg);
488 }
489
Dianne Hackborn35654b62013-01-14 17:38:02 -0800490 return AppOpsManager.MODE_ALLOWED;
491 }
492
Dianne Hackbornff170242014-11-19 10:59:01 -0800493 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
494 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700495 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
496 if (mode != MODE_ALLOWED) {
497 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800498 }
Svet Ganov99b60432015-06-27 13:15:22 -0700499
500 if (mWriteOp != AppOpsManager.OP_NONE) {
501 return mAppOpsManager.noteProxyOp(mWriteOp, callingPkg);
502 }
503
Dianne Hackborn35654b62013-01-14 17:38:02 -0800504 return AppOpsManager.MODE_ALLOWED;
505 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700506 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800507
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100508 boolean checkUser(int pid, int uid, Context context) {
509 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700510 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100511 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
512 == PERMISSION_GRANTED;
513 }
514
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700515 /**
516 * Verify that calling app holds both the given permission and any app-op
517 * associated with that permission.
518 */
519 private int checkPermissionAndAppOp(String permission, String callingPkg,
520 IBinder callerToken) {
521 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
522 callerToken) != PERMISSION_GRANTED) {
523 return MODE_ERRORED;
524 }
525
526 final int permOp = AppOpsManager.permissionToOpCode(permission);
527 if (permOp != AppOpsManager.OP_NONE) {
528 return mTransport.mAppOpsManager.noteProxyOp(permOp, callingPkg);
529 }
530
531 return MODE_ALLOWED;
532 }
533
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700534 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700535 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800536 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700537 final Context context = getContext();
538 final int pid = Binder.getCallingPid();
539 final int uid = Binder.getCallingUid();
540 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700541 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700542
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700543 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700544 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700545 }
546
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100547 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700548 final String componentPerm = getReadPermission();
549 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700550 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
551 if (mode == MODE_ALLOWED) {
552 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700553 } else {
554 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700555 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700556 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700557 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700558
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700559 // track if unprotected read is allowed; any denied
560 // <path-permission> below removes this ability
561 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700562
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700563 final PathPermission[] pps = getPathPermissions();
564 if (pps != null) {
565 final String path = uri.getPath();
566 for (PathPermission pp : pps) {
567 final String pathPerm = pp.getReadPermission();
568 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700569 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
570 if (mode == MODE_ALLOWED) {
571 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700572 } else {
573 // any denied <path-permission> means we lose
574 // default <provider> access.
575 allowDefaultRead = false;
576 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700577 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700578 }
579 }
580 }
581 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700582
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700583 // if we passed <path-permission> checks above, and no default
584 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700585 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700587
588 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800589 final int callingUserId = UserHandle.getUserId(uid);
590 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
591 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800592 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
593 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700594 return MODE_ALLOWED;
595 }
596
597 // If the worst denial we found above was ignored, then pass that
598 // ignored through; otherwise we assume it should be a real error below.
599 if (strongestMode == MODE_IGNORED) {
600 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700601 }
602
603 final String failReason = mExported
604 ? " requires " + missingPerm + ", or grantUriPermission()"
605 : " requires the provider be exported, or grantUriPermission()";
606 throw new SecurityException("Permission Denial: reading "
607 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
608 + ", uid=" + uid + failReason);
609 }
610
611 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700612 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800613 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700614 final Context context = getContext();
615 final int pid = Binder.getCallingPid();
616 final int uid = Binder.getCallingUid();
617 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700618 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700619
620 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700621 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700622 }
623
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100624 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700625 final String componentPerm = getWritePermission();
626 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700627 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
628 if (mode == MODE_ALLOWED) {
629 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700630 } else {
631 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700632 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700633 }
634 }
635
636 // track if unprotected write is allowed; any denied
637 // <path-permission> below removes this ability
638 boolean allowDefaultWrite = (componentPerm == null);
639
640 final PathPermission[] pps = getPathPermissions();
641 if (pps != null) {
642 final String path = uri.getPath();
643 for (PathPermission pp : pps) {
644 final String pathPerm = pp.getWritePermission();
645 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700646 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
647 if (mode == MODE_ALLOWED) {
648 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700649 } else {
650 // any denied <path-permission> means we lose
651 // default <provider> access.
652 allowDefaultWrite = false;
653 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700654 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700655 }
656 }
657 }
658 }
659
660 // if we passed <path-permission> checks above, and no default
661 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700662 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700663 }
664
665 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800666 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
667 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700668 return MODE_ALLOWED;
669 }
670
671 // If the worst denial we found above was ignored, then pass that
672 // ignored through; otherwise we assume it should be a real error below.
673 if (strongestMode == MODE_IGNORED) {
674 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700675 }
676
677 final String failReason = mExported
678 ? " requires " + missingPerm + ", or grantUriPermission()"
679 : " requires the provider be exported, or grantUriPermission()";
680 throw new SecurityException("Permission Denial: writing "
681 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
682 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 }
684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700686 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800687 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 * constructor.
689 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700690 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 return mContext;
692 }
693
694 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700695 * Set the calling package, returning the current value (or {@code null})
696 * which can be used later to restore the previous state.
697 */
698 private String setCallingPackage(String callingPackage) {
699 final String original = mCallingPackage.get();
700 mCallingPackage.set(callingPackage);
701 return original;
702 }
703
704 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700705 * Return the package name of the caller that initiated the request being
706 * processed on the current thread. The returned package will have been
707 * verified to belong to the calling UID. Returns {@code null} if not
708 * currently processing a request.
709 * <p>
710 * This will always return {@code null} when processing
711 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
712 *
713 * @see Binder#getCallingUid()
714 * @see Context#grantUriPermission(String, Uri, int)
715 * @throws SecurityException if the calling package doesn't belong to the
716 * calling UID.
717 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700718 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700719 final String pkg = mCallingPackage.get();
720 if (pkg != null) {
721 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
722 }
723 return pkg;
724 }
725
726 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100727 * Change the authorities of the ContentProvider.
728 * This is normally set for you from its manifest information when the provider is first
729 * created.
730 * @hide
731 * @param authorities the semi-colon separated authorities of the ContentProvider.
732 */
733 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100734 if (authorities != null) {
735 if (authorities.indexOf(';') == -1) {
736 mAuthority = authorities;
737 mAuthorities = null;
738 } else {
739 mAuthority = null;
740 mAuthorities = authorities.split(";");
741 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100742 }
743 }
744
745 /** @hide */
746 protected final boolean matchesOurAuthorities(String authority) {
747 if (mAuthority != null) {
748 return mAuthority.equals(authority);
749 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100750 if (mAuthorities != null) {
751 int length = mAuthorities.length;
752 for (int i = 0; i < length; i++) {
753 if (mAuthorities[i].equals(authority)) return true;
754 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100755 }
756 return false;
757 }
758
759
760 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 * Change the permission required to read data from the content
762 * provider. This is normally set for you from its manifest information
763 * when the provider is first created.
764 *
765 * @param permission Name of the permission required for read-only access.
766 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700767 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 mReadPermission = permission;
769 }
770
771 /**
772 * Return the name of the permission required for read-only access to
773 * this content provider. This method can be called from multiple
774 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800775 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
776 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700778 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 return mReadPermission;
780 }
781
782 /**
783 * Change the permission required to read and write data in the content
784 * provider. This is normally set for you from its manifest information
785 * when the provider is first created.
786 *
787 * @param permission Name of the permission required for read/write access.
788 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700789 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 mWritePermission = permission;
791 }
792
793 /**
794 * Return the name of the permission required for read/write access to
795 * this content provider. This method can be called from multiple
796 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800797 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
798 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700800 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 return mWritePermission;
802 }
803
804 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700805 * Change the path-based permission required to read and/or write data in
806 * the content provider. This is normally set for you from its manifest
807 * information when the provider is first created.
808 *
809 * @param permissions Array of path permission descriptions.
810 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700811 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700812 mPathPermissions = permissions;
813 }
814
815 /**
816 * Return the path-based permissions required for read and/or write access to
817 * this content provider. This method can be called from multiple
818 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800819 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
820 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700821 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700822 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700823 return mPathPermissions;
824 }
825
Dianne Hackborn35654b62013-01-14 17:38:02 -0800826 /** @hide */
827 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800828 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800829 mTransport.mReadOp = readOp;
830 mTransport.mWriteOp = writeOp;
831 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800832 }
833
Dianne Hackborn961321f2013-02-05 17:22:41 -0800834 /** @hide */
835 public AppOpsManager getAppOpsManager() {
836 return mTransport.mAppOpsManager;
837 }
838
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700839 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700840 * Implement this to initialize your content provider on startup.
841 * This method is called for all registered content providers on the
842 * application main thread at application launch time. It must not perform
843 * lengthy operations, or application startup will be delayed.
844 *
845 * <p>You should defer nontrivial initialization (such as opening,
846 * upgrading, and scanning databases) until the content provider is used
847 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
848 * keeps application startup fast, avoids unnecessary work if the provider
849 * turns out not to be needed, and stops database errors (such as a full
850 * disk) from halting application launch.
851 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700852 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700853 * is a helpful utility class that makes it easy to manage databases,
854 * and will automatically defer opening until first use. If you do use
855 * SQLiteOpenHelper, make sure to avoid calling
856 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
857 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
858 * from this method. (Instead, override
859 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
860 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 *
862 * @return true if the provider was successfully loaded, false otherwise
863 */
864 public abstract boolean onCreate();
865
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700866 /**
867 * {@inheritDoc}
868 * This method is always called on the application main thread, and must
869 * not perform lengthy operations.
870 *
871 * <p>The default content provider implementation does nothing.
872 * Override this method to take appropriate action.
873 * (Content providers do not usually care about things like screen
874 * orientation, but may want to know about locale changes.)
875 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 public void onConfigurationChanged(Configuration newConfig) {
877 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700878
879 /**
880 * {@inheritDoc}
881 * This method is always called on the application main thread, and must
882 * not perform lengthy operations.
883 *
884 * <p>The default content provider implementation does nothing.
885 * Subclasses may override this method to take appropriate action.
886 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 public void onLowMemory() {
888 }
889
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700890 public void onTrimMemory(int level) {
891 }
892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700894 * Implement this to handle query requests from clients.
895 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800896 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
897 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 * <p>
899 * Example client call:<p>
900 * <pre>// Request a specific record.
901 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000902 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 projection, // Which columns to return.
904 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000905 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 People.NAME + " ASC"); // Sort order.</pre>
907 * Example implementation:<p>
908 * <pre>// SQLiteQueryBuilder is a helper class that creates the
909 // proper SQL syntax for us.
910 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
911
912 // Set the table we're querying.
913 qBuilder.setTables(DATABASE_TABLE_NAME);
914
915 // If the query ends in a specific record number, we're
916 // being asked for a specific record, so set the
917 // WHERE clause in our query.
918 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
919 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
920 }
921
922 // Make the query.
923 Cursor c = qBuilder.query(mDb,
924 projection,
925 selection,
926 selectionArgs,
927 groupBy,
928 having,
929 sortOrder);
930 c.setNotificationUri(getContext().getContentResolver(), uri);
931 return c;</pre>
932 *
933 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000934 * if the client is requesting a specific record, the URI will end in a record number
935 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
936 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800938 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800940 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000941 * @param selectionArgs You may include ?s in selection, which will be replaced by
942 * the values from selectionArgs, in order that they appear in the selection.
943 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800945 * If {@code null} then the provider is free to define the sort order.
946 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700948 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
949 @Nullable String selection, @Nullable String[] selectionArgs,
950 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951
Fred Quintana5bba6322009-10-05 14:21:12 -0700952 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800953 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800954 * This method can be called from multiple threads, as described in
955 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
956 * and Threads</a>.
957 * <p>
958 * Example client call:<p>
959 * <pre>// Request a specific record.
960 * Cursor managedCursor = managedQuery(
961 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
962 projection, // Which columns to return.
963 null, // WHERE clause.
964 null, // WHERE clause value substitution
965 People.NAME + " ASC"); // Sort order.</pre>
966 * Example implementation:<p>
967 * <pre>// SQLiteQueryBuilder is a helper class that creates the
968 // proper SQL syntax for us.
969 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
970
971 // Set the table we're querying.
972 qBuilder.setTables(DATABASE_TABLE_NAME);
973
974 // If the query ends in a specific record number, we're
975 // being asked for a specific record, so set the
976 // WHERE clause in our query.
977 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
978 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
979 }
980
981 // Make the query.
982 Cursor c = qBuilder.query(mDb,
983 projection,
984 selection,
985 selectionArgs,
986 groupBy,
987 having,
988 sortOrder);
989 c.setNotificationUri(getContext().getContentResolver(), uri);
990 return c;</pre>
991 * <p>
992 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800993 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
994 * signal to ensure correct operation on older versions of the Android Framework in
995 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800996 *
997 * @param uri The URI to query. This will be the full URI sent by the client;
998 * if the client is requesting a specific record, the URI will end in a record number
999 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1000 * that _id value.
1001 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001002 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001003 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001004 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001005 * @param selectionArgs You may include ?s in selection, which will be replaced by
1006 * the values from selectionArgs, in order that they appear in the selection.
1007 * The values will be bound as Strings.
1008 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001009 * If {@code null} then the provider is free to define the sort order.
1010 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001011 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
1012 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001013 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001014 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001015 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1016 @Nullable String selection, @Nullable String[] selectionArgs,
1017 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001018 return query(uri, projection, selection, selectionArgs, sortOrder);
1019 }
1020
1021 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001022 * Implement this to handle requests for the MIME type of the data at the
1023 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 * <code>vnd.android.cursor.item</code> for a single record,
1025 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001026 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001027 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1028 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001030 * <p>Note that there are no permissions needed for an application to
1031 * access this information; if your content provider requires read and/or
1032 * write permissions, or is not exported, all applications can still call
1033 * this method regardless of their access permissions. This allows them
1034 * to retrieve the MIME type for a URI when dispatching intents.
1035 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001037 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001039 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040
1041 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001042 * Implement this to support canonicalization of URIs that refer to your
1043 * content provider. A canonical URI is one that can be transported across
1044 * devices, backup/restore, and other contexts, and still be able to refer
1045 * to the same data item. Typically this is implemented by adding query
1046 * params to the URI allowing the content provider to verify that an incoming
1047 * canonical URI references the same data as it was originally intended for and,
1048 * if it doesn't, to find that data (if it exists) in the current environment.
1049 *
1050 * <p>For example, if the content provider holds people and a normal URI in it
1051 * is created with a row index into that people database, the cananical representation
1052 * may have an additional query param at the end which specifies the name of the
1053 * person it is intended for. Later calls into the provider with that URI will look
1054 * up the row of that URI's base index and, if it doesn't match or its entry's
1055 * name doesn't match the name in the query param, perform a query on its database
1056 * to find the correct row to operate on.</p>
1057 *
1058 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1059 * URIs (including this one) must perform this verification and recovery of any
1060 * canonical URIs they receive. In addition, you must also implement
1061 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1062 *
1063 * <p>The default implementation of this method returns null, indicating that
1064 * canonical URIs are not supported.</p>
1065 *
1066 * @param url The Uri to canonicalize.
1067 *
1068 * @return Return the canonical representation of <var>url</var>, or null if
1069 * canonicalization of that Uri is not supported.
1070 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001071 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001072 return null;
1073 }
1074
1075 /**
1076 * Remove canonicalization from canonical URIs previously returned by
1077 * {@link #canonicalize}. For example, if your implementation is to add
1078 * a query param to canonicalize a URI, this method can simply trip any
1079 * query params on the URI. The default implementation always returns the
1080 * same <var>url</var> that was passed in.
1081 *
1082 * @param url The Uri to remove any canonicalization from.
1083 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001084 * @return Return the non-canonical representation of <var>url</var>, return
1085 * the <var>url</var> as-is if there is nothing to do, or return null if
1086 * the data identified by the canonical representation can not be found in
1087 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001088 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001089 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001090 return url;
1091 }
1092
1093 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001094 * @hide
1095 * Implementation when a caller has performed an insert on the content
1096 * provider, but that call has been rejected for the operation given
1097 * to {@link #setAppOps(int, int)}. The default implementation simply
1098 * returns a dummy URI that is the base URI with a 0 path element
1099 * appended.
1100 */
1101 public Uri rejectInsert(Uri uri, ContentValues values) {
1102 // If not allowed, we need to return some reasonable URI. Maybe the
1103 // content provider should be responsible for this, but for now we
1104 // will just return the base URI with a dummy '0' tagged on to it.
1105 // You shouldn't be able to read if you can't write, anyway, so it
1106 // shouldn't matter much what is returned.
1107 return uri.buildUpon().appendPath("0").build();
1108 }
1109
1110 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001111 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1113 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001114 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001115 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1116 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001117 * @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 -08001118 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001119 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 * @return The URI for the newly inserted item.
1121 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001122 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123
1124 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001125 * Override this to handle requests to insert a set of new rows, or the
1126 * default implementation will iterate over the values and call
1127 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1129 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001130 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001131 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1132 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 *
1134 * @param uri The content:// URI of the insertion request.
1135 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001136 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 * @return The number of values that were inserted.
1138 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001139 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 int numValues = values.length;
1141 for (int i = 0; i < numValues; i++) {
1142 insert(uri, values[i]);
1143 }
1144 return numValues;
1145 }
1146
1147 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001148 * Implement this to handle requests to delete one or more rows.
1149 * The implementation should apply the selection clause when performing
1150 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001151 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001153 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001154 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1155 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 *
1157 * <p>The implementation is responsible for parsing out a row ID at the end
1158 * of the URI, if a specific row is being deleted. That is, the client would
1159 * pass in <code>content://contacts/people/22</code> and the implementation is
1160 * responsible for parsing the record number (22) when creating a SQL statement.
1161 *
1162 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1163 * @param selection An optional restriction to apply to rows when deleting.
1164 * @return The number of rows affected.
1165 * @throws SQLException
1166 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001167 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1168 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169
1170 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001171 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001172 * The implementation should update all rows matching the selection
1173 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1175 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001176 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001177 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1178 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 *
1180 * @param uri The URI to query. This can potentially have a record ID if this
1181 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001182 * @param values A set of column_name/value pairs to update in the database.
1183 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 * @param selection An optional filter to match rows to update.
1185 * @return the number of rows affected.
1186 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001187 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001188 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189
1190 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001191 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001192 * The default implementation always throws {@link FileNotFoundException}.
1193 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001194 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1195 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001196 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001197 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1198 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001199 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 *
1201 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1202 * their responsibility to close it when done. That is, the implementation
1203 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001204 * <p>
1205 * If opened with the exclusive "r" or "w" modes, the returned
1206 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1207 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1208 * supports seeking.
1209 * <p>
1210 * If you need to detect when the returned ParcelFileDescriptor has been
1211 * closed, or if the remote process has crashed or encountered some other
1212 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1213 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1214 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1215 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001217 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1218 * to return the appropriate MIME type for the data returned here with
1219 * the same URI. This will allow intent resolution to automatically determine the data MIME
1220 * type and select the appropriate matching targets as part of its operation.</p>
1221 *
1222 * <p class="note">For better interoperability with other applications, it is recommended
1223 * that for any URIs that can be opened, you also support queries on them
1224 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1225 * You may also want to support other common columns if you have additional meta-data
1226 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1227 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1228 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 * @param uri The URI whose file is to be opened.
1230 * @param mode Access mode for the file. May be "r" for read-only access,
1231 * "rw" for read and write access, or "rwt" for read and write access
1232 * that truncates any existing file.
1233 *
1234 * @return Returns a new ParcelFileDescriptor which you can use to access
1235 * the file.
1236 *
1237 * @throws FileNotFoundException Throws FileNotFoundException if there is
1238 * no file associated with the given URI or the mode is invalid.
1239 * @throws SecurityException Throws SecurityException if the caller does
1240 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001241 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 * @see #openAssetFile(Uri, String)
1243 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001244 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001245 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001246 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001247 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 throws FileNotFoundException {
1249 throw new FileNotFoundException("No files supported by provider at "
1250 + uri);
1251 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001254 * Override this to handle requests to open a file blob.
1255 * The default implementation always throws {@link FileNotFoundException}.
1256 * This method can be called from multiple threads, as described in
1257 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1258 * and Threads</a>.
1259 *
1260 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1261 * to the caller. This way large data (such as images and documents) can be
1262 * returned without copying the content.
1263 *
1264 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1265 * their responsibility to close it when done. That is, the implementation
1266 * of this method should create a new ParcelFileDescriptor for each call.
1267 * <p>
1268 * If opened with the exclusive "r" or "w" modes, the returned
1269 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1270 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1271 * supports seeking.
1272 * <p>
1273 * If you need to detect when the returned ParcelFileDescriptor has been
1274 * closed, or if the remote process has crashed or encountered some other
1275 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1276 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1277 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1278 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1279 *
1280 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1281 * to return the appropriate MIME type for the data returned here with
1282 * the same URI. This will allow intent resolution to automatically determine the data MIME
1283 * type and select the appropriate matching targets as part of its operation.</p>
1284 *
1285 * <p class="note">For better interoperability with other applications, it is recommended
1286 * that for any URIs that can be opened, you also support queries on them
1287 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1288 * You may also want to support other common columns if you have additional meta-data
1289 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1290 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1291 *
1292 * @param uri The URI whose file is to be opened.
1293 * @param mode Access mode for the file. May be "r" for read-only access,
1294 * "w" for write-only access, "rw" for read and write access, or
1295 * "rwt" for read and write access that truncates any existing
1296 * file.
1297 * @param signal A signal to cancel the operation in progress, or
1298 * {@code null} if none. For example, if you are downloading a
1299 * file from the network to service a "rw" mode request, you
1300 * should periodically call
1301 * {@link CancellationSignal#throwIfCanceled()} to check whether
1302 * the client has canceled the request and abort the download.
1303 *
1304 * @return Returns a new ParcelFileDescriptor which you can use to access
1305 * the file.
1306 *
1307 * @throws FileNotFoundException Throws FileNotFoundException if there is
1308 * no file associated with the given URI or the mode is invalid.
1309 * @throws SecurityException Throws SecurityException if the caller does
1310 * not have permission to access the file.
1311 *
1312 * @see #openAssetFile(Uri, String)
1313 * @see #openFileHelper(Uri, String)
1314 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001315 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001316 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001317 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1318 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001319 return openFile(uri, mode);
1320 }
1321
1322 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 * This is like {@link #openFile}, but can be implemented by providers
1324 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001325 * inside of their .apk.
1326 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001327 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1328 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001329 *
1330 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001331 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001332 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1334 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1335 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001336 * <p>
1337 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1338 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001339 *
1340 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 * should create the AssetFileDescriptor with
1342 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001343 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001345 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1346 * to return the appropriate MIME type for the data returned here with
1347 * the same URI. This will allow intent resolution to automatically determine the data MIME
1348 * type and select the appropriate matching targets as part of its operation.</p>
1349 *
1350 * <p class="note">For better interoperability with other applications, it is recommended
1351 * that for any URIs that can be opened, you also support queries on them
1352 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1353 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 * @param uri The URI whose file is to be opened.
1355 * @param mode Access mode for the file. May be "r" for read-only access,
1356 * "w" for write-only access (erasing whatever data is currently in
1357 * the file), "wa" for write-only access to append to any existing data,
1358 * "rw" for read and write access on any existing data, and "rwt" for read
1359 * and write access that truncates any existing file.
1360 *
1361 * @return Returns a new AssetFileDescriptor which you can use to access
1362 * the file.
1363 *
1364 * @throws FileNotFoundException Throws FileNotFoundException if there is
1365 * no file associated with the given URI or the mode is invalid.
1366 * @throws SecurityException Throws SecurityException if the caller does
1367 * not have permission to access the file.
1368 *
1369 * @see #openFile(Uri, String)
1370 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001371 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001373 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 throws FileNotFoundException {
1375 ParcelFileDescriptor fd = openFile(uri, mode);
1376 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1377 }
1378
1379 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001380 * This is like {@link #openFile}, but can be implemented by providers
1381 * that need to be able to return sub-sections of files, often assets
1382 * inside of their .apk.
1383 * This method can be called from multiple threads, as described in
1384 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1385 * and Threads</a>.
1386 *
1387 * <p>If you implement this, your clients must be able to deal with such
1388 * file slices, either directly with
1389 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1390 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1391 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1392 * methods.
1393 * <p>
1394 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1395 * streaming of data.
1396 *
1397 * <p class="note">If you are implementing this to return a full file, you
1398 * should create the AssetFileDescriptor with
1399 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1400 * applications that cannot handle sub-sections of files.</p>
1401 *
1402 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1403 * to return the appropriate MIME type for the data returned here with
1404 * the same URI. This will allow intent resolution to automatically determine the data MIME
1405 * type and select the appropriate matching targets as part of its operation.</p>
1406 *
1407 * <p class="note">For better interoperability with other applications, it is recommended
1408 * that for any URIs that can be opened, you also support queries on them
1409 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1410 *
1411 * @param uri The URI whose file is to be opened.
1412 * @param mode Access mode for the file. May be "r" for read-only access,
1413 * "w" for write-only access (erasing whatever data is currently in
1414 * the file), "wa" for write-only access to append to any existing data,
1415 * "rw" for read and write access on any existing data, and "rwt" for read
1416 * and write access that truncates any existing file.
1417 * @param signal A signal to cancel the operation in progress, or
1418 * {@code null} if none. For example, if you are downloading a
1419 * file from the network to service a "rw" mode request, you
1420 * should periodically call
1421 * {@link CancellationSignal#throwIfCanceled()} to check whether
1422 * the client has canceled the request and abort the download.
1423 *
1424 * @return Returns a new AssetFileDescriptor which you can use to access
1425 * the file.
1426 *
1427 * @throws FileNotFoundException Throws FileNotFoundException if there is
1428 * no file associated with the given URI or the mode is invalid.
1429 * @throws SecurityException Throws SecurityException if the caller does
1430 * not have permission to access the file.
1431 *
1432 * @see #openFile(Uri, String)
1433 * @see #openFileHelper(Uri, String)
1434 * @see #getType(android.net.Uri)
1435 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001436 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1437 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001438 return openAssetFile(uri, mode);
1439 }
1440
1441 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 * Convenience for subclasses that wish to implement {@link #openFile}
1443 * by looking up a column named "_data" at the given URI.
1444 *
1445 * @param uri The URI to be opened.
1446 * @param mode The file mode. May be "r" for read-only access,
1447 * "w" for write-only access (erasing whatever data is currently in
1448 * the file), "wa" for write-only access to append to any existing data,
1449 * "rw" for read and write access on any existing data, and "rwt" for read
1450 * and write access that truncates any existing file.
1451 *
1452 * @return Returns a new ParcelFileDescriptor that can be used by the
1453 * client to access the file.
1454 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001455 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1456 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1458 int count = (c != null) ? c.getCount() : 0;
1459 if (count != 1) {
1460 // If there is not exactly one result, throw an appropriate
1461 // exception.
1462 if (c != null) {
1463 c.close();
1464 }
1465 if (count == 0) {
1466 throw new FileNotFoundException("No entry for " + uri);
1467 }
1468 throw new FileNotFoundException("Multiple items at " + uri);
1469 }
1470
1471 c.moveToFirst();
1472 int i = c.getColumnIndex("_data");
1473 String path = (i >= 0 ? c.getString(i) : null);
1474 c.close();
1475 if (path == null) {
1476 throw new FileNotFoundException("Column _data not found.");
1477 }
1478
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001479 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 return ParcelFileDescriptor.open(new File(path), modeBits);
1481 }
1482
1483 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001484 * Called by a client to determine the types of data streams that this
1485 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001486 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001487 * of a particular type, return that MIME type if it matches the given
1488 * mimeTypeFilter. If it can perform type conversions, return an array
1489 * of all supported MIME types that match mimeTypeFilter.
1490 *
1491 * @param uri The data in the content provider being queried.
1492 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001493 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001494 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001495 * given mimeTypeFilter. Otherwise returns an array of all available
1496 * concrete MIME types.
1497 *
1498 * @see #getType(Uri)
1499 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001500 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001501 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001502 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001503 return null;
1504 }
1505
1506 /**
1507 * Called by a client to open a read-only stream containing data of a
1508 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1509 * except the file can only be read-only and the content provider may
1510 * perform data conversions to generate data of the desired type.
1511 *
1512 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001513 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001514 * {@link #openAssetFile(Uri, String)}.
1515 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001516 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001517 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001518 * <p>
1519 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1520 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001521 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001522 * <p class="note">For better interoperability with other applications, it is recommended
1523 * that for any URIs that can be opened, you also support queries on them
1524 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1525 * You may also want to support other common columns if you have additional meta-data
1526 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1527 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1528 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001529 * @param uri The data in the content provider being queried.
1530 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001531 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001532 * requirements; in this case the content provider will pick its best
1533 * type matching the pattern.
1534 * @param opts Additional options from the client. The definitions of
1535 * these are specific to the content provider being called.
1536 *
1537 * @return Returns a new AssetFileDescriptor from which the client can
1538 * read data of the desired type.
1539 *
1540 * @throws FileNotFoundException Throws FileNotFoundException if there is
1541 * no file associated with the given URI or the mode is invalid.
1542 * @throws SecurityException Throws SecurityException if the caller does
1543 * not have permission to access the data.
1544 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1545 * content provider does not support the requested MIME type.
1546 *
1547 * @see #getStreamTypes(Uri, String)
1548 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001549 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001550 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001551 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1552 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001553 if ("*/*".equals(mimeTypeFilter)) {
1554 // If they can take anything, the untyped open call is good enough.
1555 return openAssetFile(uri, "r");
1556 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001557 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001558 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001559 // Use old untyped open call if this provider has a type for this
1560 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001561 return openAssetFile(uri, "r");
1562 }
1563 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1564 }
1565
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001566
1567 /**
1568 * Called by a client to open a read-only stream containing data of a
1569 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1570 * except the file can only be read-only and the content provider may
1571 * perform data conversions to generate data of the desired type.
1572 *
1573 * <p>The default implementation compares the given mimeType against the
1574 * result of {@link #getType(Uri)} and, if they match, simply calls
1575 * {@link #openAssetFile(Uri, String)}.
1576 *
1577 * <p>See {@link ClipData} for examples of the use and implementation
1578 * of this method.
1579 * <p>
1580 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1581 * streaming of data.
1582 *
1583 * <p class="note">For better interoperability with other applications, it is recommended
1584 * that for any URIs that can be opened, you also support queries on them
1585 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1586 * You may also want to support other common columns if you have additional meta-data
1587 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1588 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1589 *
1590 * @param uri The data in the content provider being queried.
1591 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001592 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001593 * requirements; in this case the content provider will pick its best
1594 * type matching the pattern.
1595 * @param opts Additional options from the client. The definitions of
1596 * these are specific to the content provider being called.
1597 * @param signal A signal to cancel the operation in progress, or
1598 * {@code null} if none. For example, if you are downloading a
1599 * file from the network to service a "rw" mode request, you
1600 * should periodically call
1601 * {@link CancellationSignal#throwIfCanceled()} to check whether
1602 * the client has canceled the request and abort the download.
1603 *
1604 * @return Returns a new AssetFileDescriptor from which the client can
1605 * read data of the desired type.
1606 *
1607 * @throws FileNotFoundException Throws FileNotFoundException if there is
1608 * no file associated with the given URI or the mode is invalid.
1609 * @throws SecurityException Throws SecurityException if the caller does
1610 * not have permission to access the data.
1611 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1612 * content provider does not support the requested MIME type.
1613 *
1614 * @see #getStreamTypes(Uri, String)
1615 * @see #openAssetFile(Uri, String)
1616 * @see ClipDescription#compareMimeTypes(String, String)
1617 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001618 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1619 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1620 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001621 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1622 }
1623
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001624 /**
1625 * Interface to write a stream of data to a pipe. Use with
1626 * {@link ContentProvider#openPipeHelper}.
1627 */
1628 public interface PipeDataWriter<T> {
1629 /**
1630 * Called from a background thread to stream data out to a pipe.
1631 * Note that the pipe is blocking, so this thread can block on
1632 * writes for an arbitrary amount of time if the client is slow
1633 * at reading.
1634 *
1635 * @param output The pipe where data should be written. This will be
1636 * closed for you upon returning from this function.
1637 * @param uri The URI whose data is to be written.
1638 * @param mimeType The desired type of data to be written.
1639 * @param opts Options supplied by caller.
1640 * @param args Your own custom arguments.
1641 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001642 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1643 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001644 }
1645
1646 /**
1647 * A helper function for implementing {@link #openTypedAssetFile}, for
1648 * creating a data pipe and background thread allowing you to stream
1649 * generated data back to the client. This function returns a new
1650 * ParcelFileDescriptor that should be returned to the caller (the caller
1651 * is responsible for closing it).
1652 *
1653 * @param uri The URI whose data is to be written.
1654 * @param mimeType The desired type of data to be written.
1655 * @param opts Options supplied by caller.
1656 * @param args Your own custom arguments.
1657 * @param func Interface implementing the function that will actually
1658 * stream the data.
1659 * @return Returns a new ParcelFileDescriptor holding the read side of
1660 * the pipe. This should be returned to the caller for reading; the caller
1661 * is responsible for closing it when done.
1662 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001663 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1664 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1665 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001666 try {
1667 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1668
1669 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1670 @Override
1671 protected Object doInBackground(Object... params) {
1672 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1673 try {
1674 fds[1].close();
1675 } catch (IOException e) {
1676 Log.w(TAG, "Failure closing pipe", e);
1677 }
1678 return null;
1679 }
1680 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001681 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001682
1683 return fds[0];
1684 } catch (IOException e) {
1685 throw new FileNotFoundException("failure making pipe");
1686 }
1687 }
1688
1689 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 * Returns true if this instance is a temporary content provider.
1691 * @return true if this instance is a temporary content provider
1692 */
1693 protected boolean isTemporary() {
1694 return false;
1695 }
1696
1697 /**
1698 * Returns the Binder object for this provider.
1699 *
1700 * @return the Binder object for this provider
1701 * @hide
1702 */
1703 public IContentProvider getIContentProvider() {
1704 return mTransport;
1705 }
1706
1707 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001708 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1709 * when directly instantiating the provider for testing.
1710 * @hide
1711 */
1712 public void attachInfoForTesting(Context context, ProviderInfo info) {
1713 attachInfo(context, info, true);
1714 }
1715
1716 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 * After being instantiated, this is called to tell the content provider
1718 * about itself.
1719 *
1720 * @param context The context this provider is running in
1721 * @param info Registered information about this content provider
1722 */
1723 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001724 attachInfo(context, info, false);
1725 }
1726
1727 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001728 mNoPerms = testing;
1729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 /*
1731 * Only allow it to be set once, so after the content service gives
1732 * this to us clients can't change it.
1733 */
1734 if (mContext == null) {
1735 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001736 if (context != null) {
1737 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1738 Context.APP_OPS_SERVICE);
1739 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001740 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 if (info != null) {
1742 setReadPermission(info.readPermission);
1743 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001744 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001745 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001746 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001747 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 }
1749 ContentProvider.this.onCreate();
1750 }
1751 }
Fred Quintanace31b232009-05-04 16:01:15 -07001752
1753 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001754 * Override this to handle requests to perform a batch of operations, or the
1755 * default implementation will iterate over the operations and call
1756 * {@link ContentProviderOperation#apply} on each of them.
1757 * If all calls to {@link ContentProviderOperation#apply} succeed
1758 * then a {@link ContentProviderResult} array with as many
1759 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001760 * fail, it is up to the implementation how many of the others take effect.
1761 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001762 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1763 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001764 *
Fred Quintanace31b232009-05-04 16:01:15 -07001765 * @param operations the operations to apply
1766 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001767 * @throws OperationApplicationException thrown if any operation fails.
1768 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001769 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001770 public @NonNull ContentProviderResult[] applyBatch(
1771 @NonNull ArrayList<ContentProviderOperation> operations)
1772 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001773 final int numOperations = operations.size();
1774 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1775 for (int i = 0; i < numOperations; i++) {
1776 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001777 }
1778 return results;
1779 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001780
1781 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001782 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001783 * interfaces that are cheaper and/or unnatural for a table-like
1784 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001785 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001786 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1787 * on this entry into the content provider besides the basic ability for the application
1788 * to get access to the provider at all. For example, it has no idea whether the call
1789 * being executed may read or write data in the provider, so can't enforce those
1790 * individual permissions. Any implementation of this method <strong>must</strong>
1791 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1792 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001793 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1794 * @param arg provider-defined String argument. May be {@code null}.
1795 * @param extras provider-defined Bundle argument. May be {@code null}.
1796 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001797 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001798 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001799 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
1800 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001801 return null;
1802 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001803
1804 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001805 * Implement this to shut down the ContentProvider instance. You can then
1806 * invoke this method in unit tests.
1807 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001808 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001809 * Android normally handles ContentProvider startup and shutdown
1810 * automatically. You do not need to start up or shut down a
1811 * ContentProvider. When you invoke a test method on a ContentProvider,
1812 * however, a ContentProvider instance is started and keeps running after
1813 * the test finishes, even if a succeeding test instantiates another
1814 * ContentProvider. A conflict develops because the two instances are
1815 * usually running against the same underlying data source (for example, an
1816 * sqlite database).
1817 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001818 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001819 * Implementing shutDown() avoids this conflict by providing a way to
1820 * terminate the ContentProvider. This method can also prevent memory leaks
1821 * from multiple instantiations of the ContentProvider, and it can ensure
1822 * unit test isolation by allowing you to completely clean up the test
1823 * fixture before moving on to the next test.
1824 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001825 */
1826 public void shutdown() {
1827 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1828 "connections are gracefully shutdown");
1829 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001830
1831 /**
1832 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001833 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001834 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001835 * @param fd The raw file descriptor that the dump is being sent to.
1836 * @param writer The PrintWriter to which you should dump your state. This will be
1837 * closed for you after you return.
1838 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001839 */
1840 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1841 writer.println("nothing to dump");
1842 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001843
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001844 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001845 private void validateIncomingUri(Uri uri) throws SecurityException {
1846 String auth = uri.getAuthority();
1847 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001848 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
1849 throw new SecurityException("trying to query a ContentProvider in user "
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001850 + mContext.getUserId() + " with a uri belonging to user " + userId);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001851 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001852 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
1853 String message = "The authority of the uri " + uri + " does not match the one of the "
1854 + "contentProvider: ";
1855 if (mAuthority != null) {
1856 message += mAuthority;
1857 } else {
Andreas Gampee6748ce2015-12-11 18:00:38 -08001858 message += Arrays.toString(mAuthorities);
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001859 }
1860 throw new SecurityException(message);
1861 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001862 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001863
1864 /** @hide */
1865 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1866 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001867 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001868 if (end == -1) return defaultUserId;
1869 String userIdString = auth.substring(0, end);
1870 try {
1871 return Integer.parseInt(userIdString);
1872 } catch (NumberFormatException e) {
1873 Log.w(TAG, "Error parsing userId.", e);
1874 return UserHandle.USER_NULL;
1875 }
1876 }
1877
1878 /** @hide */
1879 public static int getUserIdFromAuthority(String auth) {
1880 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1881 }
1882
1883 /** @hide */
1884 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1885 if (uri == null) return defaultUserId;
1886 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1887 }
1888
1889 /** @hide */
1890 public static int getUserIdFromUri(Uri uri) {
1891 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1892 }
1893
1894 /**
1895 * Removes userId part from authority string. Expects format:
1896 * userId@some.authority
1897 * If there is no userId in the authority, it symply returns the argument
1898 * @hide
1899 */
1900 public static String getAuthorityWithoutUserId(String auth) {
1901 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001902 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001903 return auth.substring(end+1);
1904 }
1905
1906 /** @hide */
1907 public static Uri getUriWithoutUserId(Uri uri) {
1908 if (uri == null) return null;
1909 Uri.Builder builder = uri.buildUpon();
1910 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1911 return builder.build();
1912 }
1913
1914 /** @hide */
1915 public static boolean uriHasUserId(Uri uri) {
1916 if (uri == null) return false;
1917 return !TextUtils.isEmpty(uri.getUserInfo());
1918 }
1919
1920 /** @hide */
1921 public static Uri maybeAddUserId(Uri uri, int userId) {
1922 if (uri == null) return null;
1923 if (userId != UserHandle.USER_CURRENT
1924 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1925 if (!uriHasUserId(uri)) {
1926 //We don't add the user Id if there's already one
1927 Uri.Builder builder = uri.buildUpon();
1928 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1929 return builder.build();
1930 }
1931 }
1932 return uri;
1933 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001934}