blob: 64e464c318d3aed2d08a9042aad1b4a66e2ed168 [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;
Ben Lin1cf454f2016-11-10 13:50:54 -080045import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070046import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060047import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010048import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070049import android.util.Log;
Steve McKay76b27702017-04-24 12:07:53 -070050import android.util.MathUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051
52import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080053import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070055import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080056import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070057import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080058import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059
60/**
61 * Content providers are one of the primary building blocks of Android applications, providing
62 * content to applications. They encapsulate data and provide it to applications through the single
63 * {@link ContentResolver} interface. A content provider is only required if you need to share
64 * data between multiple applications. For example, the contacts data is used by multiple
65 * applications and must be stored in a content provider. If you don't need to share data amongst
66 * multiple applications you can use a database directly via
67 * {@link android.database.sqlite.SQLiteDatabase}.
68 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 * <p>When a request is made via
70 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
71 * request to the content provider registered with the authority. The content provider can interpret
72 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
73 * URIs.</p>
74 *
75 * <p>The primary methods that need to be implemented are:
76 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070077 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 * <li>{@link #query} which returns data to the caller</li>
79 * <li>{@link #insert} which inserts new data into the content provider</li>
80 * <li>{@link #update} which updates existing data in the content provider</li>
81 * <li>{@link #delete} which deletes data from the content provider</li>
82 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
83 * </ul></p>
84 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070085 * <p class="caution">Data access methods (such as {@link #insert} and
86 * {@link #update}) may be called from many threads at once, and must be thread-safe.
87 * Other methods (such as {@link #onCreate}) are only called from the application
88 * main thread, and must avoid performing lengthy operations. See the method
89 * descriptions for their expected thread behavior.</p>
90 *
91 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
92 * ContentProvider instance, so subclasses don't have to worry about the details of
93 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070094 *
95 * <div class="special reference">
96 * <h3>Developer Guides</h3>
97 * <p>For more information about using content providers, read the
98 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
99 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700101public abstract class ContentProvider implements ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800102
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700103 private static final String TAG = "ContentProvider";
104
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900105 /*
106 * Note: if you add methods to ContentProvider, you must add similar methods to
107 * MockContentProvider.
108 */
109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700111 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100112
113 // Since most Providers have only one authority, we keep both a String and a String[] to improve
114 // performance.
115 private String mAuthority;
116 private String[] mAuthorities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 private String mReadPermission;
118 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700119 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700120 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800121 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700122 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123
Steve McKayea93fe72016-12-02 11:35:35 -0800124 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<>();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 private Transport mTransport = new Transport();
127
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700128 /**
129 * Construct a ContentProvider instance. Content providers must be
130 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
131 * in the manifest</a>, accessed with {@link ContentResolver}, and created
132 * automatically by the system, so applications usually do not create
133 * ContentProvider instances directly.
134 *
135 * <p>At construction time, the object is uninitialized, and most fields and
136 * methods are unavailable. Subclasses should initialize themselves in
137 * {@link #onCreate}, not the constructor.
138 *
139 * <p>Content providers are created on the application main thread at
140 * application launch time. The constructor must not perform lengthy
141 * operations, or application startup will be delayed.
142 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900143 public ContentProvider() {
144 }
145
146 /**
147 * Constructor just for mocking.
148 *
149 * @param context A Context object which should be some mock instance (like the
150 * instance of {@link android.test.mock.MockContext}).
151 * @param readPermission The read permision you want this instance should have in the
152 * test, which is available via {@link #getReadPermission()}.
153 * @param writePermission The write permission you want this instance should have
154 * in the test, which is available via {@link #getWritePermission()}.
155 * @param pathPermissions The PathPermissions you want this instance should have
156 * in the test, which is available via {@link #getPathPermissions()}.
157 * @hide
158 */
159 public ContentProvider(
160 Context context,
161 String readPermission,
162 String writePermission,
163 PathPermission[] pathPermissions) {
164 mContext = context;
165 mReadPermission = readPermission;
166 mWritePermission = writePermission;
167 mPathPermissions = pathPermissions;
168 }
169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 /**
171 * Given an IContentProvider, try to coerce it back to the real
172 * ContentProvider object if it is running in the local process. This can
173 * be used if you know you are running in the same process as a provider,
174 * and want to get direct access to its implementation details. Most
175 * clients should not nor have a reason to use it.
176 *
177 * @param abstractInterface The ContentProvider interface that is to be
178 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800179 * @return If the IContentProvider is non-{@code null} and local, returns its actual
180 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 * @hide
182 */
183 public static ContentProvider coerceToLocalContentProvider(
184 IContentProvider abstractInterface) {
185 if (abstractInterface instanceof Transport) {
186 return ((Transport)abstractInterface).getContentProvider();
187 }
188 return null;
189 }
190
191 /**
192 * Binder object that deals with remoting.
193 *
194 * @hide
195 */
196 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800197 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800198 int mReadOp = AppOpsManager.OP_NONE;
199 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 ContentProvider getContentProvider() {
202 return ContentProvider.this;
203 }
204
Jeff Brownd2183652011-10-09 12:39:53 -0700205 @Override
206 public String getProviderName() {
207 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 }
209
Jeff Brown75ea64f2012-01-25 19:37:13 -0800210 @Override
Steve McKayea93fe72016-12-02 11:35:35 -0800211 public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
212 @Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100213 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100214 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800215 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700216 // The caller has no access to the data, so return an empty cursor with
217 // the columns in the requested order. The caller may ask for an invalid
218 // column and we would not catch that but this is not a problem in practice.
219 // We do not call ContentProvider#query with a modified where clause since
220 // the implementation is not guaranteed to be backed by a SQL database, hence
221 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700222 if (projection != null) {
223 return new MatrixCursor(projection, 0);
224 }
225
226 // Null projection means all columns but we have no idea which they are.
227 // However, the caller may be expecting to access them my index. Hence,
228 // we have to execute the query as if allowed to get a cursor with the
229 // columns. We then use the column names to return an empty cursor.
Steve McKayea93fe72016-12-02 11:35:35 -0800230 Cursor cursor = ContentProvider.this.query(
231 uri, projection, queryArgs,
232 CancellationSignal.fromTransport(cancellationSignal));
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700233 if (cursor == null) {
234 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700235 }
236
237 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700238 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800239 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700240 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700241 try {
242 return ContentProvider.this.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800243 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700244 CancellationSignal.fromTransport(cancellationSignal));
245 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700246 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 }
249
Jeff Brown75ea64f2012-01-25 19:37:13 -0800250 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100252 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100253 uri = maybeGetUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 return ContentProvider.this.getType(uri);
255 }
256
Jeff Brown75ea64f2012-01-25 19:37:13 -0800257 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800258 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100259 validateIncomingUri(uri);
260 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100261 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800262 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800263 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800264 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700265 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700266 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100267 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700268 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700269 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 }
272
Jeff Brown75ea64f2012-01-25 19:37:13 -0800273 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800274 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100275 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100276 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800277 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800278 return 0;
279 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700280 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700281 try {
282 return ContentProvider.this.bulkInsert(uri, initialValues);
283 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700284 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 }
287
Jeff Brown75ea64f2012-01-25 19:37:13 -0800288 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800289 public ContentProviderResult[] applyBatch(String callingPkg,
290 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700291 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100292 int numOperations = operations.size();
293 final int[] userIds = new int[numOperations];
294 for (int i = 0; i < numOperations; i++) {
295 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100296 Uri uri = operation.getUri();
297 validateIncomingUri(uri);
298 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100299 if (userIds[i] != UserHandle.USER_CURRENT) {
300 // Removing the user id from the uri.
301 operation = new ContentProviderOperation(operation, true);
302 operations.set(i, operation);
303 }
Fred Quintana89437372009-05-15 15:10:40 -0700304 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800305 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800306 != AppOpsManager.MODE_ALLOWED) {
307 throw new OperationApplicationException("App op not allowed", 0);
308 }
Fred Quintana89437372009-05-15 15:10:40 -0700309 }
Fred Quintana89437372009-05-15 15:10:40 -0700310 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800311 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800312 != AppOpsManager.MODE_ALLOWED) {
313 throw new OperationApplicationException("App op not allowed", 0);
314 }
Fred Quintana89437372009-05-15 15:10:40 -0700315 }
316 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700317 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700318 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100319 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800320 if (results != null) {
321 for (int i = 0; i < results.length ; i++) {
322 if (userIds[i] != UserHandle.USER_CURRENT) {
323 // Adding the userId to the uri.
324 results[i] = new ContentProviderResult(results[i], userIds[i]);
325 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100326 }
327 }
328 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700329 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700330 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700331 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700332 }
333
Jeff Brown75ea64f2012-01-25 19:37:13 -0800334 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800335 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100336 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100337 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800338 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800339 return 0;
340 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700341 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700342 try {
343 return ContentProvider.this.delete(uri, selection, selectionArgs);
344 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700345 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 }
348
Jeff Brown75ea64f2012-01-25 19:37:13 -0800349 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800350 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100352 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100353 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800354 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800355 return 0;
356 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700357 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700358 try {
359 return ContentProvider.this.update(uri, values, selection, selectionArgs);
360 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700361 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 }
364
Jeff Brown75ea64f2012-01-25 19:37:13 -0800365 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700366 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800367 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
368 IBinder callerToken) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100369 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100370 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800371 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700372 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700373 try {
374 return ContentProvider.this.openFile(
375 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
376 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700377 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379 }
380
Jeff Brown75ea64f2012-01-25 19:37:13 -0800381 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700382 public AssetFileDescriptor openAssetFile(
383 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100385 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100386 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800387 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700388 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700389 try {
390 return ContentProvider.this.openAssetFile(
391 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
392 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700393 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 }
396
Jeff Brown75ea64f2012-01-25 19:37:13 -0800397 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800398 public Bundle call(
399 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600400 Bundle.setDefusable(extras, true);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700401 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700402 try {
403 return ContentProvider.this.call(method, arg, extras);
404 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700405 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700406 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800407 }
408
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700409 @Override
410 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100411 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100412 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700413 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
414 }
415
416 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800417 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700418 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600419 Bundle.setDefusable(opts, true);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100420 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100421 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800422 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700423 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700424 try {
425 return ContentProvider.this.openTypedAssetFile(
426 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
427 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700428 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700429 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700430 }
431
Jeff Brown75ea64f2012-01-25 19:37:13 -0800432 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700433 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800434 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800435 }
436
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700437 @Override
438 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100439 validateIncomingUri(uri);
440 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100441 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800442 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700443 return null;
444 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700445 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700446 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100447 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700448 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700449 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700450 }
451 }
452
453 @Override
454 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100455 validateIncomingUri(uri);
456 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100457 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800458 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700459 return null;
460 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700461 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700462 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100463 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700464 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700465 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700466 }
467 }
468
Ben Lin1cf454f2016-11-10 13:50:54 -0800469 @Override
470 public boolean refresh(String callingPkg, Uri uri, Bundle args,
471 ICancellationSignal cancellationSignal) throws RemoteException {
472 validateIncomingUri(uri);
473 uri = getUriWithoutUserId(uri);
474 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
475 return false;
476 }
477 final String original = setCallingPackage(callingPkg);
478 try {
479 return ContentProvider.this.refresh(uri, args,
480 CancellationSignal.fromTransport(cancellationSignal));
481 } finally {
482 setCallingPackage(original);
483 }
484 }
485
Dianne Hackbornff170242014-11-19 10:59:01 -0800486 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
487 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800488 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800489 if (enforceWritePermission(callingPkg, uri, callerToken)
490 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800491 throw new FileNotFoundException("App op not allowed");
492 }
493 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800494 if (enforceReadPermission(callingPkg, uri, callerToken)
495 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800496 throw new FileNotFoundException("App op not allowed");
497 }
498 }
499 }
500
Dianne Hackbornff170242014-11-19 10:59:01 -0800501 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
502 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700503 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
504 if (mode != MODE_ALLOWED) {
505 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800506 }
Svet Ganov99b60432015-06-27 13:15:22 -0700507
508 if (mReadOp != AppOpsManager.OP_NONE) {
509 return mAppOpsManager.noteProxyOp(mReadOp, callingPkg);
510 }
511
Dianne Hackborn35654b62013-01-14 17:38:02 -0800512 return AppOpsManager.MODE_ALLOWED;
513 }
514
Dianne Hackbornff170242014-11-19 10:59:01 -0800515 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
516 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700517 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
518 if (mode != MODE_ALLOWED) {
519 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800520 }
Svet Ganov99b60432015-06-27 13:15:22 -0700521
522 if (mWriteOp != AppOpsManager.OP_NONE) {
523 return mAppOpsManager.noteProxyOp(mWriteOp, callingPkg);
524 }
525
Dianne Hackborn35654b62013-01-14 17:38:02 -0800526 return AppOpsManager.MODE_ALLOWED;
527 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700528 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800529
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100530 boolean checkUser(int pid, int uid, Context context) {
531 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700532 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100533 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
534 == PERMISSION_GRANTED;
535 }
536
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700537 /**
538 * Verify that calling app holds both the given permission and any app-op
539 * associated with that permission.
540 */
541 private int checkPermissionAndAppOp(String permission, String callingPkg,
542 IBinder callerToken) {
543 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
544 callerToken) != PERMISSION_GRANTED) {
545 return MODE_ERRORED;
546 }
547
548 final int permOp = AppOpsManager.permissionToOpCode(permission);
549 if (permOp != AppOpsManager.OP_NONE) {
550 return mTransport.mAppOpsManager.noteProxyOp(permOp, callingPkg);
551 }
552
553 return MODE_ALLOWED;
554 }
555
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700556 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700557 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800558 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700559 final Context context = getContext();
560 final int pid = Binder.getCallingPid();
561 final int uid = Binder.getCallingUid();
562 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700563 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700564
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700565 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700566 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700567 }
568
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100569 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700570 final String componentPerm = getReadPermission();
571 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700572 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
573 if (mode == MODE_ALLOWED) {
574 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700575 } else {
576 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700577 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700578 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700579 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700580
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700581 // track if unprotected read is allowed; any denied
582 // <path-permission> below removes this ability
583 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700584
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700585 final PathPermission[] pps = getPathPermissions();
586 if (pps != null) {
587 final String path = uri.getPath();
588 for (PathPermission pp : pps) {
589 final String pathPerm = pp.getReadPermission();
590 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700591 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
592 if (mode == MODE_ALLOWED) {
593 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700594 } else {
595 // any denied <path-permission> means we lose
596 // default <provider> access.
597 allowDefaultRead = false;
598 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700599 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700600 }
601 }
602 }
603 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700604
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700605 // if we passed <path-permission> checks above, and no default
606 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700607 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700609
610 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800611 final int callingUserId = UserHandle.getUserId(uid);
612 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
613 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800614 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
615 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700616 return MODE_ALLOWED;
617 }
618
619 // If the worst denial we found above was ignored, then pass that
620 // ignored through; otherwise we assume it should be a real error below.
621 if (strongestMode == MODE_IGNORED) {
622 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700623 }
624
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600625 final String suffix;
626 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
627 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
628 } else if (mExported) {
629 suffix = " requires " + missingPerm + ", or grantUriPermission()";
630 } else {
631 suffix = " requires the provider be exported, or grantUriPermission()";
632 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700633 throw new SecurityException("Permission Denial: reading "
634 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600635 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700636 }
637
638 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700639 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800640 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700641 final Context context = getContext();
642 final int pid = Binder.getCallingPid();
643 final int uid = Binder.getCallingUid();
644 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700645 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700646
647 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700648 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700649 }
650
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100651 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700652 final String componentPerm = getWritePermission();
653 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700654 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
655 if (mode == MODE_ALLOWED) {
656 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700657 } else {
658 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700659 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700660 }
661 }
662
663 // track if unprotected write is allowed; any denied
664 // <path-permission> below removes this ability
665 boolean allowDefaultWrite = (componentPerm == null);
666
667 final PathPermission[] pps = getPathPermissions();
668 if (pps != null) {
669 final String path = uri.getPath();
670 for (PathPermission pp : pps) {
671 final String pathPerm = pp.getWritePermission();
672 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700673 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
674 if (mode == MODE_ALLOWED) {
675 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700676 } else {
677 // any denied <path-permission> means we lose
678 // default <provider> access.
679 allowDefaultWrite = false;
680 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700681 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700682 }
683 }
684 }
685 }
686
687 // if we passed <path-permission> checks above, and no default
688 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700689 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700690 }
691
692 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800693 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
694 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700695 return MODE_ALLOWED;
696 }
697
698 // If the worst denial we found above was ignored, then pass that
699 // ignored through; otherwise we assume it should be a real error below.
700 if (strongestMode == MODE_IGNORED) {
701 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700702 }
703
704 final String failReason = mExported
705 ? " requires " + missingPerm + ", or grantUriPermission()"
706 : " requires the provider be exported, or grantUriPermission()";
707 throw new SecurityException("Permission Denial: writing "
708 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
709 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 }
711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700713 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800714 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 * constructor.
716 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700717 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 return mContext;
719 }
720
721 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700722 * Set the calling package, returning the current value (or {@code null})
723 * which can be used later to restore the previous state.
724 */
725 private String setCallingPackage(String callingPackage) {
726 final String original = mCallingPackage.get();
727 mCallingPackage.set(callingPackage);
728 return original;
729 }
730
731 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700732 * Return the package name of the caller that initiated the request being
733 * processed on the current thread. The returned package will have been
734 * verified to belong to the calling UID. Returns {@code null} if not
735 * currently processing a request.
736 * <p>
737 * This will always return {@code null} when processing
738 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
739 *
740 * @see Binder#getCallingUid()
741 * @see Context#grantUriPermission(String, Uri, int)
742 * @throws SecurityException if the calling package doesn't belong to the
743 * calling UID.
744 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700745 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700746 final String pkg = mCallingPackage.get();
747 if (pkg != null) {
748 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
749 }
750 return pkg;
751 }
752
753 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100754 * Change the authorities of the ContentProvider.
755 * This is normally set for you from its manifest information when the provider is first
756 * created.
757 * @hide
758 * @param authorities the semi-colon separated authorities of the ContentProvider.
759 */
760 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100761 if (authorities != null) {
762 if (authorities.indexOf(';') == -1) {
763 mAuthority = authorities;
764 mAuthorities = null;
765 } else {
766 mAuthority = null;
767 mAuthorities = authorities.split(";");
768 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100769 }
770 }
771
772 /** @hide */
773 protected final boolean matchesOurAuthorities(String authority) {
774 if (mAuthority != null) {
775 return mAuthority.equals(authority);
776 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100777 if (mAuthorities != null) {
778 int length = mAuthorities.length;
779 for (int i = 0; i < length; i++) {
780 if (mAuthorities[i].equals(authority)) return true;
781 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100782 }
783 return false;
784 }
785
786
787 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 * Change the permission required to read data from the content
789 * provider. This is normally set for you from its manifest information
790 * when the provider is first created.
791 *
792 * @param permission Name of the permission required for read-only access.
793 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700794 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 mReadPermission = permission;
796 }
797
798 /**
799 * Return the name of the permission required for read-only access to
800 * this content provider. This method can be called from multiple
801 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800802 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
803 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700805 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 return mReadPermission;
807 }
808
809 /**
810 * Change the permission required to read and write data in the content
811 * provider. This is normally set for you from its manifest information
812 * when the provider is first created.
813 *
814 * @param permission Name of the permission required for read/write access.
815 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700816 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 mWritePermission = permission;
818 }
819
820 /**
821 * Return the name of the permission required for read/write access to
822 * this content provider. This method can be called from multiple
823 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800824 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
825 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700827 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 return mWritePermission;
829 }
830
831 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700832 * Change the path-based permission required to read and/or write data in
833 * the content provider. This is normally set for you from its manifest
834 * information when the provider is first created.
835 *
836 * @param permissions Array of path permission descriptions.
837 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700838 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700839 mPathPermissions = permissions;
840 }
841
842 /**
843 * Return the path-based permissions required for read and/or write access to
844 * this content provider. This method can be called from multiple
845 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800846 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
847 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700848 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700849 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700850 return mPathPermissions;
851 }
852
Dianne Hackborn35654b62013-01-14 17:38:02 -0800853 /** @hide */
854 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800855 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800856 mTransport.mReadOp = readOp;
857 mTransport.mWriteOp = writeOp;
858 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800859 }
860
Dianne Hackborn961321f2013-02-05 17:22:41 -0800861 /** @hide */
862 public AppOpsManager getAppOpsManager() {
863 return mTransport.mAppOpsManager;
864 }
865
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700866 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700867 * Implement this to initialize your content provider on startup.
868 * This method is called for all registered content providers on the
869 * application main thread at application launch time. It must not perform
870 * lengthy operations, or application startup will be delayed.
871 *
872 * <p>You should defer nontrivial initialization (such as opening,
873 * upgrading, and scanning databases) until the content provider is used
874 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
875 * keeps application startup fast, avoids unnecessary work if the provider
876 * turns out not to be needed, and stops database errors (such as a full
877 * disk) from halting application launch.
878 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700879 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700880 * is a helpful utility class that makes it easy to manage databases,
881 * and will automatically defer opening until first use. If you do use
882 * SQLiteOpenHelper, make sure to avoid calling
883 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
884 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
885 * from this method. (Instead, override
886 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
887 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 *
889 * @return true if the provider was successfully loaded, false otherwise
890 */
891 public abstract boolean onCreate();
892
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700893 /**
894 * {@inheritDoc}
895 * This method is always called on the application main thread, and must
896 * not perform lengthy operations.
897 *
898 * <p>The default content provider implementation does nothing.
899 * Override this method to take appropriate action.
900 * (Content providers do not usually care about things like screen
901 * orientation, but may want to know about locale changes.)
902 */
Steve McKayea93fe72016-12-02 11:35:35 -0800903 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 public void onConfigurationChanged(Configuration newConfig) {
905 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700906
907 /**
908 * {@inheritDoc}
909 * This method is always called on the application main thread, and must
910 * not perform lengthy operations.
911 *
912 * <p>The default content provider implementation does nothing.
913 * Subclasses may override this method to take appropriate action.
914 */
Steve McKayea93fe72016-12-02 11:35:35 -0800915 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 public void onLowMemory() {
917 }
918
Steve McKayea93fe72016-12-02 11:35:35 -0800919 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700920 public void onTrimMemory(int level) {
921 }
922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700924 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -0800925 *
926 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
927 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
928 * implementation of this method.
929 *
930 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800931 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
932 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 * <p>
934 * Example client call:<p>
935 * <pre>// Request a specific record.
936 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000937 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 projection, // Which columns to return.
939 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000940 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 People.NAME + " ASC"); // Sort order.</pre>
942 * Example implementation:<p>
943 * <pre>// SQLiteQueryBuilder is a helper class that creates the
944 // proper SQL syntax for us.
945 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
946
947 // Set the table we're querying.
948 qBuilder.setTables(DATABASE_TABLE_NAME);
949
950 // If the query ends in a specific record number, we're
951 // being asked for a specific record, so set the
952 // WHERE clause in our query.
953 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
954 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
955 }
956
957 // Make the query.
958 Cursor c = qBuilder.query(mDb,
959 projection,
960 selection,
961 selectionArgs,
962 groupBy,
963 having,
964 sortOrder);
965 c.setNotificationUri(getContext().getContentResolver(), uri);
966 return c;</pre>
967 *
968 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000969 * if the client is requesting a specific record, the URI will end in a record number
970 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
971 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800973 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800975 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000976 * @param selectionArgs You may include ?s in selection, which will be replaced by
977 * the values from selectionArgs, in order that they appear in the selection.
978 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800980 * If {@code null} then the provider is free to define the sort order.
981 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700983 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
984 @Nullable String selection, @Nullable String[] selectionArgs,
985 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986
Fred Quintana5bba6322009-10-05 14:21:12 -0700987 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800988 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -0800989 *
990 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
991 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
992 *
993 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -0800994 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
995 * and Threads</a>.
996 * <p>
997 * Example client call:<p>
998 * <pre>// Request a specific record.
999 * Cursor managedCursor = managedQuery(
1000 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1001 projection, // Which columns to return.
1002 null, // WHERE clause.
1003 null, // WHERE clause value substitution
1004 People.NAME + " ASC"); // Sort order.</pre>
1005 * Example implementation:<p>
1006 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1007 // proper SQL syntax for us.
1008 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1009
1010 // Set the table we're querying.
1011 qBuilder.setTables(DATABASE_TABLE_NAME);
1012
1013 // If the query ends in a specific record number, we're
1014 // being asked for a specific record, so set the
1015 // WHERE clause in our query.
1016 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1017 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1018 }
1019
1020 // Make the query.
1021 Cursor c = qBuilder.query(mDb,
1022 projection,
1023 selection,
1024 selectionArgs,
1025 groupBy,
1026 having,
1027 sortOrder);
1028 c.setNotificationUri(getContext().getContentResolver(), uri);
1029 return c;</pre>
1030 * <p>
1031 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001032 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1033 * signal to ensure correct operation on older versions of the Android Framework in
1034 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001035 *
1036 * @param uri The URI to query. This will be the full URI sent by the client;
1037 * if the client is requesting a specific record, the URI will end in a record number
1038 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1039 * that _id value.
1040 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001041 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001042 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001043 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001044 * @param selectionArgs You may include ?s in selection, which will be replaced by
1045 * the values from selectionArgs, in order that they appear in the selection.
1046 * The values will be bound as Strings.
1047 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001048 * If {@code null} then the provider is free to define the sort order.
1049 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001050 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
1051 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001052 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001053 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001054 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1055 @Nullable String selection, @Nullable String[] selectionArgs,
1056 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001057 return query(uri, projection, selection, selectionArgs, sortOrder);
1058 }
1059
1060 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001061 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1062 * Arguments may include traditional SQL style query arguments. When present these
1063 * should be handled according to the contract established in
1064 * {@link #query(Uri, String[], String, String[], String, CancellationSignal).
1065 *
1066 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Steve McKay29c3f682016-12-16 14:52:59 -08001067 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION}
1068 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1069 * <li>{@link ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001070 *
Steve McKay76b27702017-04-24 12:07:53 -07001071 * <p>This method can be called from multiple threads, as described in
1072 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1073 * and Threads</a>.
1074 *
1075 * <p>
1076 * Example client call:<p>
1077 * <pre>// Request 20 records starting at row index 30.
1078 Bundle queryArgs = new Bundle();
1079 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1080 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1081
1082 Cursor cursor = getContentResolver().query(
1083 contentUri, // Content Uri is specific to individual content providers.
1084 projection, // String[] describing which columns to return.
1085 queryArgs, // Query arguments.
1086 null); // Cancellation signal.</pre>
1087 *
1088 * Example implementation:<p>
1089 * <pre>
1090
1091 int recordsetSize = 0x1000; // Actual value is implementation specific.
1092 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1093
1094 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1095 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1096
1097 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1098
1099 // Calculate the number of items to include in the cursor.
1100 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1101
1102 // Build the paged result set....
1103 for (int i = offset; i < offset + numItems; i++) {
1104 // populate row from your data.
1105 }
1106
1107 Bundle extras = new Bundle();
1108 c.setExtras(extras);
1109
1110 // Any QUERY_ARG_* key may be included if honored.
1111 // In an actual implementation, include only keys that are both present in queryArgs
1112 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1113 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1114 // then QUERY_ARG_OFFSET should be omitted.
1115 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1116 ContentResolver.QUERY_ARG_OFFSET,
1117 ContentResolver.QUERY_ARG_LIMIT
1118 });
1119
1120 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1121
1122 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1123
1124 return cursor;</pre>
1125 * <p>
Steve McKayea93fe72016-12-02 11:35:35 -08001126 * @see #query(Uri, String[], String, String[], String, CancellationSignal) for
1127 * implementation details.
1128 *
1129 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001130 * @param projection The list of columns to put into the cursor.
1131 * If {@code null} provide a default set of columns.
1132 * @param queryArgs A Bundle containing all additional information necessary for the query.
1133 * Values in the Bundle may include SQL style arguments.
1134 * @param cancellationSignal A signal to cancel the operation in progress,
1135 * or {@code null}.
1136 * @return a Cursor or {@code null}.
1137 */
1138 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1139 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1140 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001141
Steve McKayd7ece9f2017-01-12 16:59:59 -08001142 // if client doesn't supply an SQL sort order argument, attempt to build one from
1143 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001144 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001145 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1146 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1147 }
1148
Steve McKayea93fe72016-12-02 11:35:35 -08001149 return query(
1150 uri,
1151 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001152 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1153 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1154 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001155 cancellationSignal);
1156 }
1157
1158 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001159 * Implement this to handle requests for the MIME type of the data at the
1160 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 * <code>vnd.android.cursor.item</code> for a single record,
1162 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001163 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001164 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1165 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001167 * <p>Note that there are no permissions needed for an application to
1168 * access this information; if your content provider requires read and/or
1169 * write permissions, or is not exported, all applications can still call
1170 * this method regardless of their access permissions. This allows them
1171 * to retrieve the MIME type for a URI when dispatching intents.
1172 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001174 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001176 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177
1178 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001179 * Implement this to support canonicalization of URIs that refer to your
1180 * content provider. A canonical URI is one that can be transported across
1181 * devices, backup/restore, and other contexts, and still be able to refer
1182 * to the same data item. Typically this is implemented by adding query
1183 * params to the URI allowing the content provider to verify that an incoming
1184 * canonical URI references the same data as it was originally intended for and,
1185 * if it doesn't, to find that data (if it exists) in the current environment.
1186 *
1187 * <p>For example, if the content provider holds people and a normal URI in it
1188 * is created with a row index into that people database, the cananical representation
1189 * may have an additional query param at the end which specifies the name of the
1190 * person it is intended for. Later calls into the provider with that URI will look
1191 * up the row of that URI's base index and, if it doesn't match or its entry's
1192 * name doesn't match the name in the query param, perform a query on its database
1193 * to find the correct row to operate on.</p>
1194 *
1195 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1196 * URIs (including this one) must perform this verification and recovery of any
1197 * canonical URIs they receive. In addition, you must also implement
1198 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1199 *
1200 * <p>The default implementation of this method returns null, indicating that
1201 * canonical URIs are not supported.</p>
1202 *
1203 * @param url The Uri to canonicalize.
1204 *
1205 * @return Return the canonical representation of <var>url</var>, or null if
1206 * canonicalization of that Uri is not supported.
1207 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001208 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001209 return null;
1210 }
1211
1212 /**
1213 * Remove canonicalization from canonical URIs previously returned by
1214 * {@link #canonicalize}. For example, if your implementation is to add
1215 * a query param to canonicalize a URI, this method can simply trip any
1216 * query params on the URI. The default implementation always returns the
1217 * same <var>url</var> that was passed in.
1218 *
1219 * @param url The Uri to remove any canonicalization from.
1220 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001221 * @return Return the non-canonical representation of <var>url</var>, return
1222 * the <var>url</var> as-is if there is nothing to do, or return null if
1223 * the data identified by the canonical representation can not be found in
1224 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001225 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001226 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001227 return url;
1228 }
1229
1230 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001231 * Implement this to support refresh of content identified by {@code uri}. By default, this
1232 * method returns false; providers who wish to implement this should return true to signal the
1233 * client that the provider has tried refreshing with its own implementation.
1234 * <p>
1235 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1236 * <p>
1237 * Client code should only invoke this method when there is a strong indication (such as a user
1238 * initiated pull to refresh gesture) that the content is stale.
1239 * <p>
1240 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1241 * notifications when content changes.
1242 *
1243 * @param uri The Uri identifying the data to refresh.
1244 * @param args Additional options from the client. The definitions of these are specific to the
1245 * content provider being called.
1246 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1247 * none. For example, if you called refresh on a particular uri, you should call
1248 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1249 * canceled the refresh request.
1250 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001251 */
1252 public boolean refresh(Uri uri, @Nullable Bundle args,
1253 @Nullable CancellationSignal cancellationSignal) {
1254 return false;
1255 }
1256
1257 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001258 * @hide
1259 * Implementation when a caller has performed an insert on the content
1260 * provider, but that call has been rejected for the operation given
1261 * to {@link #setAppOps(int, int)}. The default implementation simply
1262 * returns a dummy URI that is the base URI with a 0 path element
1263 * appended.
1264 */
1265 public Uri rejectInsert(Uri uri, ContentValues values) {
1266 // If not allowed, we need to return some reasonable URI. Maybe the
1267 // content provider should be responsible for this, but for now we
1268 // will just return the base URI with a dummy '0' tagged on to it.
1269 // You shouldn't be able to read if you can't write, anyway, so it
1270 // shouldn't matter much what is returned.
1271 return uri.buildUpon().appendPath("0").build();
1272 }
1273
1274 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001275 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1277 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001278 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001279 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1280 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001281 * @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 -08001282 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001283 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 * @return The URI for the newly inserted item.
1285 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001286 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287
1288 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001289 * Override this to handle requests to insert a set of new rows, or the
1290 * default implementation will iterate over the values and call
1291 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1293 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001294 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001295 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1296 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 *
1298 * @param uri The content:// URI of the insertion request.
1299 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001300 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 * @return The number of values that were inserted.
1302 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001303 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 int numValues = values.length;
1305 for (int i = 0; i < numValues; i++) {
1306 insert(uri, values[i]);
1307 }
1308 return numValues;
1309 }
1310
1311 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001312 * Implement this to handle requests to delete one or more rows.
1313 * The implementation should apply the selection clause when performing
1314 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001315 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001317 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001318 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1319 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 *
1321 * <p>The implementation is responsible for parsing out a row ID at the end
1322 * of the URI, if a specific row is being deleted. That is, the client would
1323 * pass in <code>content://contacts/people/22</code> and the implementation is
1324 * responsible for parsing the record number (22) when creating a SQL statement.
1325 *
1326 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1327 * @param selection An optional restriction to apply to rows when deleting.
1328 * @return The number of rows affected.
1329 * @throws SQLException
1330 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001331 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1332 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333
1334 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001335 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001336 * The implementation should update all rows matching the selection
1337 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1339 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001340 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001341 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1342 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 *
1344 * @param uri The URI to query. This can potentially have a record ID if this
1345 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001346 * @param values A set of column_name/value pairs to update in the database.
1347 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 * @param selection An optional filter to match rows to update.
1349 * @return the number of rows affected.
1350 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001351 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001352 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353
1354 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001355 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001356 * The default implementation always throws {@link FileNotFoundException}.
1357 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001358 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1359 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001360 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001361 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1362 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001363 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 *
1365 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1366 * their responsibility to close it when done. That is, the implementation
1367 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001368 * <p>
1369 * If opened with the exclusive "r" or "w" modes, the returned
1370 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1371 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1372 * supports seeking.
1373 * <p>
1374 * If you need to detect when the returned ParcelFileDescriptor has been
1375 * closed, or if the remote process has crashed or encountered some other
1376 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1377 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1378 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1379 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001380 * <p>
1381 * If you need to return a large file that isn't backed by a real file on
1382 * disk, such as a file on a network share or cloud storage service,
1383 * consider using
1384 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1385 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001387 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1388 * to return the appropriate MIME type for the data returned here with
1389 * the same URI. This will allow intent resolution to automatically determine the data MIME
1390 * type and select the appropriate matching targets as part of its operation.</p>
1391 *
1392 * <p class="note">For better interoperability with other applications, it is recommended
1393 * that for any URIs that can be opened, you also support queries on them
1394 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1395 * You may also want to support other common columns if you have additional meta-data
1396 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1397 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1398 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 * @param uri The URI whose file is to be opened.
1400 * @param mode Access mode for the file. May be "r" for read-only access,
1401 * "rw" for read and write access, or "rwt" for read and write access
1402 * that truncates any existing file.
1403 *
1404 * @return Returns a new ParcelFileDescriptor which you can use to access
1405 * the file.
1406 *
1407 * @throws FileNotFoundException Throws FileNotFoundException if there is
1408 * no file associated with the given URI or the mode is invalid.
1409 * @throws SecurityException Throws SecurityException if the caller does
1410 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001411 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 * @see #openAssetFile(Uri, String)
1413 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001414 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001415 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001416 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001417 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 throws FileNotFoundException {
1419 throw new FileNotFoundException("No files supported by provider at "
1420 + uri);
1421 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001424 * Override this to handle requests to open a file blob.
1425 * The default implementation always throws {@link FileNotFoundException}.
1426 * This method can be called from multiple threads, as described in
1427 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1428 * and Threads</a>.
1429 *
1430 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1431 * to the caller. This way large data (such as images and documents) can be
1432 * returned without copying the content.
1433 *
1434 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1435 * their responsibility to close it when done. That is, the implementation
1436 * of this method should create a new ParcelFileDescriptor for each call.
1437 * <p>
1438 * If opened with the exclusive "r" or "w" modes, the returned
1439 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1440 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1441 * supports seeking.
1442 * <p>
1443 * If you need to detect when the returned ParcelFileDescriptor has been
1444 * closed, or if the remote process has crashed or encountered some other
1445 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1446 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1447 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1448 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1449 *
1450 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1451 * to return the appropriate MIME type for the data returned here with
1452 * the same URI. This will allow intent resolution to automatically determine the data MIME
1453 * type and select the appropriate matching targets as part of its operation.</p>
1454 *
1455 * <p class="note">For better interoperability with other applications, it is recommended
1456 * that for any URIs that can be opened, you also support queries on them
1457 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1458 * You may also want to support other common columns if you have additional meta-data
1459 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1460 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1461 *
1462 * @param uri The URI whose file is to be opened.
1463 * @param mode Access mode for the file. May be "r" for read-only access,
1464 * "w" for write-only access, "rw" for read and write access, or
1465 * "rwt" for read and write access that truncates any existing
1466 * file.
1467 * @param signal A signal to cancel the operation in progress, or
1468 * {@code null} if none. For example, if you are downloading a
1469 * file from the network to service a "rw" mode request, you
1470 * should periodically call
1471 * {@link CancellationSignal#throwIfCanceled()} to check whether
1472 * the client has canceled the request and abort the download.
1473 *
1474 * @return Returns a new ParcelFileDescriptor which you can use to access
1475 * the file.
1476 *
1477 * @throws FileNotFoundException Throws FileNotFoundException if there is
1478 * no file associated with the given URI or the mode is invalid.
1479 * @throws SecurityException Throws SecurityException if the caller does
1480 * not have permission to access the file.
1481 *
1482 * @see #openAssetFile(Uri, String)
1483 * @see #openFileHelper(Uri, String)
1484 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001485 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001486 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001487 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1488 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001489 return openFile(uri, mode);
1490 }
1491
1492 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 * This is like {@link #openFile}, but can be implemented by providers
1494 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001495 * inside of their .apk.
1496 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001497 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1498 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001499 *
1500 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001501 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001502 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1504 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1505 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001506 * <p>
1507 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1508 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001509 *
1510 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 * should create the AssetFileDescriptor with
1512 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001513 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001515 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1516 * to return the appropriate MIME type for the data returned here with
1517 * the same URI. This will allow intent resolution to automatically determine the data MIME
1518 * type and select the appropriate matching targets as part of its operation.</p>
1519 *
1520 * <p class="note">For better interoperability with other applications, it is recommended
1521 * that for any URIs that can be opened, you also support queries on them
1522 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1523 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 * @param uri The URI whose file is to be opened.
1525 * @param mode Access mode for the file. May be "r" for read-only access,
1526 * "w" for write-only access (erasing whatever data is currently in
1527 * the file), "wa" for write-only access to append to any existing data,
1528 * "rw" for read and write access on any existing data, and "rwt" for read
1529 * and write access that truncates any existing file.
1530 *
1531 * @return Returns a new AssetFileDescriptor which you can use to access
1532 * the file.
1533 *
1534 * @throws FileNotFoundException Throws FileNotFoundException if there is
1535 * no file associated with the given URI or the mode is invalid.
1536 * @throws SecurityException Throws SecurityException if the caller does
1537 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001538 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 * @see #openFile(Uri, String)
1540 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001541 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001543 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 throws FileNotFoundException {
1545 ParcelFileDescriptor fd = openFile(uri, mode);
1546 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1547 }
1548
1549 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001550 * This is like {@link #openFile}, but can be implemented by providers
1551 * that need to be able to return sub-sections of files, often assets
1552 * inside of their .apk.
1553 * This method can be called from multiple threads, as described in
1554 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1555 * and Threads</a>.
1556 *
1557 * <p>If you implement this, your clients must be able to deal with such
1558 * file slices, either directly with
1559 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1560 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1561 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1562 * methods.
1563 * <p>
1564 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1565 * streaming of data.
1566 *
1567 * <p class="note">If you are implementing this to return a full file, you
1568 * should create the AssetFileDescriptor with
1569 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1570 * applications that cannot handle sub-sections of files.</p>
1571 *
1572 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1573 * to return the appropriate MIME type for the data returned here with
1574 * the same URI. This will allow intent resolution to automatically determine the data MIME
1575 * type and select the appropriate matching targets as part of its operation.</p>
1576 *
1577 * <p class="note">For better interoperability with other applications, it is recommended
1578 * that for any URIs that can be opened, you also support queries on them
1579 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1580 *
1581 * @param uri The URI whose file is to be opened.
1582 * @param mode Access mode for the file. May be "r" for read-only access,
1583 * "w" for write-only access (erasing whatever data is currently in
1584 * the file), "wa" for write-only access to append to any existing data,
1585 * "rw" for read and write access on any existing data, and "rwt" for read
1586 * and write access that truncates any existing file.
1587 * @param signal A signal to cancel the operation in progress, or
1588 * {@code null} if none. For example, if you are downloading a
1589 * file from the network to service a "rw" mode request, you
1590 * should periodically call
1591 * {@link CancellationSignal#throwIfCanceled()} to check whether
1592 * the client has canceled the request and abort the download.
1593 *
1594 * @return Returns a new AssetFileDescriptor which you can use to access
1595 * the file.
1596 *
1597 * @throws FileNotFoundException Throws FileNotFoundException if there is
1598 * no file associated with the given URI or the mode is invalid.
1599 * @throws SecurityException Throws SecurityException if the caller does
1600 * not have permission to access the file.
1601 *
1602 * @see #openFile(Uri, String)
1603 * @see #openFileHelper(Uri, String)
1604 * @see #getType(android.net.Uri)
1605 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001606 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1607 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001608 return openAssetFile(uri, mode);
1609 }
1610
1611 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 * Convenience for subclasses that wish to implement {@link #openFile}
1613 * by looking up a column named "_data" at the given URI.
1614 *
1615 * @param uri The URI to be opened.
1616 * @param mode The file mode. May be "r" for read-only access,
1617 * "w" for write-only access (erasing whatever data is currently in
1618 * the file), "wa" for write-only access to append to any existing data,
1619 * "rw" for read and write access on any existing data, and "rwt" for read
1620 * and write access that truncates any existing file.
1621 *
1622 * @return Returns a new ParcelFileDescriptor that can be used by the
1623 * client to access the file.
1624 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001625 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1626 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1628 int count = (c != null) ? c.getCount() : 0;
1629 if (count != 1) {
1630 // If there is not exactly one result, throw an appropriate
1631 // exception.
1632 if (c != null) {
1633 c.close();
1634 }
1635 if (count == 0) {
1636 throw new FileNotFoundException("No entry for " + uri);
1637 }
1638 throw new FileNotFoundException("Multiple items at " + uri);
1639 }
1640
1641 c.moveToFirst();
1642 int i = c.getColumnIndex("_data");
1643 String path = (i >= 0 ? c.getString(i) : null);
1644 c.close();
1645 if (path == null) {
1646 throw new FileNotFoundException("Column _data not found.");
1647 }
1648
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001649 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 return ParcelFileDescriptor.open(new File(path), modeBits);
1651 }
1652
1653 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001654 * Called by a client to determine the types of data streams that this
1655 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001656 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001657 * of a particular type, return that MIME type if it matches the given
1658 * mimeTypeFilter. If it can perform type conversions, return an array
1659 * of all supported MIME types that match mimeTypeFilter.
1660 *
1661 * @param uri The data in the content provider being queried.
1662 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001663 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001664 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001665 * given mimeTypeFilter. Otherwise returns an array of all available
1666 * concrete MIME types.
1667 *
1668 * @see #getType(Uri)
1669 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001670 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001671 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001672 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001673 return null;
1674 }
1675
1676 /**
1677 * Called by a client to open a read-only stream containing data of a
1678 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1679 * except the file can only be read-only and the content provider may
1680 * perform data conversions to generate data of the desired type.
1681 *
1682 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001683 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001684 * {@link #openAssetFile(Uri, String)}.
1685 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001686 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001687 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001688 * <p>
1689 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1690 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001691 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001692 * <p class="note">For better interoperability with other applications, it is recommended
1693 * that for any URIs that can be opened, you also support queries on them
1694 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1695 * You may also want to support other common columns if you have additional meta-data
1696 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1697 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1698 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001699 * @param uri The data in the content provider being queried.
1700 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001701 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001702 * requirements; in this case the content provider will pick its best
1703 * type matching the pattern.
1704 * @param opts Additional options from the client. The definitions of
1705 * these are specific to the content provider being called.
1706 *
1707 * @return Returns a new AssetFileDescriptor from which the client can
1708 * read data of the desired type.
1709 *
1710 * @throws FileNotFoundException Throws FileNotFoundException if there is
1711 * no file associated with the given URI or the mode is invalid.
1712 * @throws SecurityException Throws SecurityException if the caller does
1713 * not have permission to access the data.
1714 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1715 * content provider does not support the requested MIME type.
1716 *
1717 * @see #getStreamTypes(Uri, String)
1718 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001719 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001720 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001721 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1722 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001723 if ("*/*".equals(mimeTypeFilter)) {
1724 // If they can take anything, the untyped open call is good enough.
1725 return openAssetFile(uri, "r");
1726 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001727 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001728 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001729 // Use old untyped open call if this provider has a type for this
1730 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001731 return openAssetFile(uri, "r");
1732 }
1733 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1734 }
1735
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001736
1737 /**
1738 * Called by a client to open a read-only stream containing data of a
1739 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1740 * except the file can only be read-only and the content provider may
1741 * perform data conversions to generate data of the desired type.
1742 *
1743 * <p>The default implementation compares the given mimeType against the
1744 * result of {@link #getType(Uri)} and, if they match, simply calls
1745 * {@link #openAssetFile(Uri, String)}.
1746 *
1747 * <p>See {@link ClipData} for examples of the use and implementation
1748 * of this method.
1749 * <p>
1750 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1751 * streaming of data.
1752 *
1753 * <p class="note">For better interoperability with other applications, it is recommended
1754 * that for any URIs that can be opened, you also support queries on them
1755 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1756 * You may also want to support other common columns if you have additional meta-data
1757 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1758 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1759 *
1760 * @param uri The data in the content provider being queried.
1761 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001762 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001763 * requirements; in this case the content provider will pick its best
1764 * type matching the pattern.
1765 * @param opts Additional options from the client. The definitions of
1766 * these are specific to the content provider being called.
1767 * @param signal A signal to cancel the operation in progress, or
1768 * {@code null} if none. For example, if you are downloading a
1769 * file from the network to service a "rw" mode request, you
1770 * should periodically call
1771 * {@link CancellationSignal#throwIfCanceled()} to check whether
1772 * the client has canceled the request and abort the download.
1773 *
1774 * @return Returns a new AssetFileDescriptor from which the client can
1775 * read data of the desired type.
1776 *
1777 * @throws FileNotFoundException Throws FileNotFoundException if there is
1778 * no file associated with the given URI or the mode is invalid.
1779 * @throws SecurityException Throws SecurityException if the caller does
1780 * not have permission to access the data.
1781 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1782 * content provider does not support the requested MIME type.
1783 *
1784 * @see #getStreamTypes(Uri, String)
1785 * @see #openAssetFile(Uri, String)
1786 * @see ClipDescription#compareMimeTypes(String, String)
1787 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001788 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1789 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1790 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001791 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1792 }
1793
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001794 /**
1795 * Interface to write a stream of data to a pipe. Use with
1796 * {@link ContentProvider#openPipeHelper}.
1797 */
1798 public interface PipeDataWriter<T> {
1799 /**
1800 * Called from a background thread to stream data out to a pipe.
1801 * Note that the pipe is blocking, so this thread can block on
1802 * writes for an arbitrary amount of time if the client is slow
1803 * at reading.
1804 *
1805 * @param output The pipe where data should be written. This will be
1806 * closed for you upon returning from this function.
1807 * @param uri The URI whose data is to be written.
1808 * @param mimeType The desired type of data to be written.
1809 * @param opts Options supplied by caller.
1810 * @param args Your own custom arguments.
1811 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001812 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1813 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001814 }
1815
1816 /**
1817 * A helper function for implementing {@link #openTypedAssetFile}, for
1818 * creating a data pipe and background thread allowing you to stream
1819 * generated data back to the client. This function returns a new
1820 * ParcelFileDescriptor that should be returned to the caller (the caller
1821 * is responsible for closing it).
1822 *
1823 * @param uri The URI whose data is to be written.
1824 * @param mimeType The desired type of data to be written.
1825 * @param opts Options supplied by caller.
1826 * @param args Your own custom arguments.
1827 * @param func Interface implementing the function that will actually
1828 * stream the data.
1829 * @return Returns a new ParcelFileDescriptor holding the read side of
1830 * the pipe. This should be returned to the caller for reading; the caller
1831 * is responsible for closing it when done.
1832 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001833 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1834 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1835 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001836 try {
1837 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1838
1839 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1840 @Override
1841 protected Object doInBackground(Object... params) {
1842 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1843 try {
1844 fds[1].close();
1845 } catch (IOException e) {
1846 Log.w(TAG, "Failure closing pipe", e);
1847 }
1848 return null;
1849 }
1850 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001851 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001852
1853 return fds[0];
1854 } catch (IOException e) {
1855 throw new FileNotFoundException("failure making pipe");
1856 }
1857 }
1858
1859 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 * Returns true if this instance is a temporary content provider.
1861 * @return true if this instance is a temporary content provider
1862 */
1863 protected boolean isTemporary() {
1864 return false;
1865 }
1866
1867 /**
1868 * Returns the Binder object for this provider.
1869 *
1870 * @return the Binder object for this provider
1871 * @hide
1872 */
1873 public IContentProvider getIContentProvider() {
1874 return mTransport;
1875 }
1876
1877 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001878 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1879 * when directly instantiating the provider for testing.
1880 * @hide
1881 */
1882 public void attachInfoForTesting(Context context, ProviderInfo info) {
1883 attachInfo(context, info, true);
1884 }
1885
1886 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 * After being instantiated, this is called to tell the content provider
1888 * about itself.
1889 *
1890 * @param context The context this provider is running in
1891 * @param info Registered information about this content provider
1892 */
1893 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001894 attachInfo(context, info, false);
1895 }
1896
1897 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001898 mNoPerms = testing;
1899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 /*
1901 * Only allow it to be set once, so after the content service gives
1902 * this to us clients can't change it.
1903 */
1904 if (mContext == null) {
1905 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001906 if (context != null) {
1907 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1908 Context.APP_OPS_SERVICE);
1909 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001910 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 if (info != null) {
1912 setReadPermission(info.readPermission);
1913 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001914 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001915 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001916 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001917 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 }
1919 ContentProvider.this.onCreate();
1920 }
1921 }
Fred Quintanace31b232009-05-04 16:01:15 -07001922
1923 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001924 * Override this to handle requests to perform a batch of operations, or the
1925 * default implementation will iterate over the operations and call
1926 * {@link ContentProviderOperation#apply} on each of them.
1927 * If all calls to {@link ContentProviderOperation#apply} succeed
1928 * then a {@link ContentProviderResult} array with as many
1929 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001930 * fail, it is up to the implementation how many of the others take effect.
1931 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001932 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1933 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001934 *
Fred Quintanace31b232009-05-04 16:01:15 -07001935 * @param operations the operations to apply
1936 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001937 * @throws OperationApplicationException thrown if any operation fails.
1938 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001939 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001940 public @NonNull ContentProviderResult[] applyBatch(
1941 @NonNull ArrayList<ContentProviderOperation> operations)
1942 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001943 final int numOperations = operations.size();
1944 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1945 for (int i = 0; i < numOperations; i++) {
1946 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001947 }
1948 return results;
1949 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001950
1951 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001952 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001953 * interfaces that are cheaper and/or unnatural for a table-like
1954 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001955 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001956 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1957 * on this entry into the content provider besides the basic ability for the application
1958 * to get access to the provider at all. For example, it has no idea whether the call
1959 * being executed may read or write data in the provider, so can't enforce those
1960 * individual permissions. Any implementation of this method <strong>must</strong>
1961 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1962 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001963 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1964 * @param arg provider-defined String argument. May be {@code null}.
1965 * @param extras provider-defined Bundle argument. May be {@code null}.
1966 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001967 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001968 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001969 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
1970 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001971 return null;
1972 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001973
1974 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001975 * Implement this to shut down the ContentProvider instance. You can then
1976 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08001977 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001978 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001979 * Android normally handles ContentProvider startup and shutdown
1980 * automatically. You do not need to start up or shut down a
1981 * ContentProvider. When you invoke a test method on a ContentProvider,
1982 * however, a ContentProvider instance is started and keeps running after
1983 * the test finishes, even if a succeeding test instantiates another
1984 * ContentProvider. A conflict develops because the two instances are
1985 * usually running against the same underlying data source (for example, an
1986 * sqlite database).
1987 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001988 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001989 * Implementing shutDown() avoids this conflict by providing a way to
1990 * terminate the ContentProvider. This method can also prevent memory leaks
1991 * from multiple instantiations of the ContentProvider, and it can ensure
1992 * unit test isolation by allowing you to completely clean up the test
1993 * fixture before moving on to the next test.
1994 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001995 */
1996 public void shutdown() {
1997 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1998 "connections are gracefully shutdown");
1999 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002000
2001 /**
2002 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002003 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002004 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002005 * @param fd The raw file descriptor that the dump is being sent to.
2006 * @param writer The PrintWriter to which you should dump your state. This will be
2007 * closed for you after you return.
2008 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002009 */
2010 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2011 writer.println("nothing to dump");
2012 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002013
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002014 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002015 private void validateIncomingUri(Uri uri) throws SecurityException {
2016 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002017 if (!mSingleUser) {
2018 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2019 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2020 throw new SecurityException("trying to query a ContentProvider in user "
2021 + mContext.getUserId() + " with a uri belonging to user " + userId);
2022 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002023 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002024 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
2025 String message = "The authority of the uri " + uri + " does not match the one of the "
2026 + "contentProvider: ";
2027 if (mAuthority != null) {
2028 message += mAuthority;
2029 } else {
Andreas Gampee6748ce2015-12-11 18:00:38 -08002030 message += Arrays.toString(mAuthorities);
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002031 }
2032 throw new SecurityException(message);
2033 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002034 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002035
2036 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002037 private Uri maybeGetUriWithoutUserId(Uri uri) {
2038 if (mSingleUser) {
2039 return uri;
2040 }
2041 return getUriWithoutUserId(uri);
2042 }
2043
2044 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002045 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2046 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002047 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002048 if (end == -1) return defaultUserId;
2049 String userIdString = auth.substring(0, end);
2050 try {
2051 return Integer.parseInt(userIdString);
2052 } catch (NumberFormatException e) {
2053 Log.w(TAG, "Error parsing userId.", e);
2054 return UserHandle.USER_NULL;
2055 }
2056 }
2057
2058 /** @hide */
2059 public static int getUserIdFromAuthority(String auth) {
2060 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2061 }
2062
2063 /** @hide */
2064 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2065 if (uri == null) return defaultUserId;
2066 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2067 }
2068
2069 /** @hide */
2070 public static int getUserIdFromUri(Uri uri) {
2071 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2072 }
2073
2074 /**
2075 * Removes userId part from authority string. Expects format:
2076 * userId@some.authority
2077 * If there is no userId in the authority, it symply returns the argument
2078 * @hide
2079 */
2080 public static String getAuthorityWithoutUserId(String auth) {
2081 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002082 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002083 return auth.substring(end+1);
2084 }
2085
2086 /** @hide */
2087 public static Uri getUriWithoutUserId(Uri uri) {
2088 if (uri == null) return null;
2089 Uri.Builder builder = uri.buildUpon();
2090 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2091 return builder.build();
2092 }
2093
2094 /** @hide */
2095 public static boolean uriHasUserId(Uri uri) {
2096 if (uri == null) return false;
2097 return !TextUtils.isEmpty(uri.getUserInfo());
2098 }
2099
2100 /** @hide */
2101 public static Uri maybeAddUserId(Uri uri, int userId) {
2102 if (uri == null) return null;
2103 if (userId != UserHandle.USER_CURRENT
2104 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
2105 if (!uriHasUserId(uri)) {
2106 //We don't add the user Id if there's already one
2107 Uri.Builder builder = uri.buildUpon();
2108 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2109 return builder.build();
2110 }
2111 }
2112 return uri;
2113 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002114}