blob: 8d8b257564e6904e2b02f4465597ecfeca1506b1 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070043import android.os.Process;
Ben Lin1cf454f2016-11-10 13:50:54 -080044import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070045import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060046import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010047import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070048import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049
50import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080051import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070053import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080054import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070055import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080056import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057
58/**
59 * Content providers are one of the primary building blocks of Android applications, providing
60 * content to applications. They encapsulate data and provide it to applications through the single
61 * {@link ContentResolver} interface. A content provider is only required if you need to share
62 * data between multiple applications. For example, the contacts data is used by multiple
63 * applications and must be stored in a content provider. If you don't need to share data amongst
64 * multiple applications you can use a database directly via
65 * {@link android.database.sqlite.SQLiteDatabase}.
66 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 * <p>When a request is made via
68 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
69 * request to the content provider registered with the authority. The content provider can interpret
70 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
71 * URIs.</p>
72 *
73 * <p>The primary methods that need to be implemented are:
74 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070075 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 * <li>{@link #query} which returns data to the caller</li>
77 * <li>{@link #insert} which inserts new data into the content provider</li>
78 * <li>{@link #update} which updates existing data in the content provider</li>
79 * <li>{@link #delete} which deletes data from the content provider</li>
80 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
81 * </ul></p>
82 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070083 * <p class="caution">Data access methods (such as {@link #insert} and
84 * {@link #update}) may be called from many threads at once, and must be thread-safe.
85 * Other methods (such as {@link #onCreate}) are only called from the application
86 * main thread, and must avoid performing lengthy operations. See the method
87 * descriptions for their expected thread behavior.</p>
88 *
89 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
90 * ContentProvider instance, so subclasses don't have to worry about the details of
91 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070092 *
93 * <div class="special reference">
94 * <h3>Developer Guides</h3>
95 * <p>For more information about using content providers, read the
96 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
97 * developer guide.</p>
Nicole Borrelli8a5f04a2018-09-20 14:19:14 -070098 * </div>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700100public abstract class ContentProvider implements ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800101
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700102 private static final String TAG = "ContentProvider";
103
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900104 /*
105 * Note: if you add methods to ContentProvider, you must add similar methods to
106 * MockContentProvider.
107 */
108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700110 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100111
112 // Since most Providers have only one authority, we keep both a String and a String[] to improve
113 // performance.
114 private String mAuthority;
115 private String[] mAuthorities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 private String mReadPermission;
117 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700118 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700119 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800120 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700121 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122
Steve McKayea93fe72016-12-02 11:35:35 -0800123 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<>();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 private Transport mTransport = new Transport();
126
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700127 /**
128 * Construct a ContentProvider instance. Content providers must be
129 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
130 * in the manifest</a>, accessed with {@link ContentResolver}, and created
131 * automatically by the system, so applications usually do not create
132 * ContentProvider instances directly.
133 *
134 * <p>At construction time, the object is uninitialized, and most fields and
135 * methods are unavailable. Subclasses should initialize themselves in
136 * {@link #onCreate}, not the constructor.
137 *
138 * <p>Content providers are created on the application main thread at
139 * application launch time. The constructor must not perform lengthy
140 * operations, or application startup will be delayed.
141 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900142 public ContentProvider() {
143 }
144
145 /**
146 * Constructor just for mocking.
147 *
148 * @param context A Context object which should be some mock instance (like the
149 * instance of {@link android.test.mock.MockContext}).
150 * @param readPermission The read permision you want this instance should have in the
151 * test, which is available via {@link #getReadPermission()}.
152 * @param writePermission The write permission you want this instance should have
153 * in the test, which is available via {@link #getWritePermission()}.
154 * @param pathPermissions The PathPermissions you want this instance should have
155 * in the test, which is available via {@link #getPathPermissions()}.
156 * @hide
157 */
158 public ContentProvider(
159 Context context,
160 String readPermission,
161 String writePermission,
162 PathPermission[] pathPermissions) {
163 mContext = context;
164 mReadPermission = readPermission;
165 mWritePermission = writePermission;
166 mPathPermissions = pathPermissions;
167 }
168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 /**
170 * Given an IContentProvider, try to coerce it back to the real
171 * ContentProvider object if it is running in the local process. This can
172 * be used if you know you are running in the same process as a provider,
173 * and want to get direct access to its implementation details. Most
174 * clients should not nor have a reason to use it.
175 *
176 * @param abstractInterface The ContentProvider interface that is to be
177 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800178 * @return If the IContentProvider is non-{@code null} and local, returns its actual
179 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 * @hide
181 */
182 public static ContentProvider coerceToLocalContentProvider(
183 IContentProvider abstractInterface) {
184 if (abstractInterface instanceof Transport) {
185 return ((Transport)abstractInterface).getContentProvider();
186 }
187 return null;
188 }
189
190 /**
191 * Binder object that deals with remoting.
192 *
193 * @hide
194 */
195 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800196 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800197 int mReadOp = AppOpsManager.OP_NONE;
198 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 ContentProvider getContentProvider() {
201 return ContentProvider.this;
202 }
203
Jeff Brownd2183652011-10-09 12:39:53 -0700204 @Override
205 public String getProviderName() {
206 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 }
208
Jeff Brown75ea64f2012-01-25 19:37:13 -0800209 @Override
Steve McKayea93fe72016-12-02 11:35:35 -0800210 public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
211 @Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100212 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100213 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800214 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700215 // The caller has no access to the data, so return an empty cursor with
216 // the columns in the requested order. The caller may ask for an invalid
217 // column and we would not catch that but this is not a problem in practice.
218 // We do not call ContentProvider#query with a modified where clause since
219 // the implementation is not guaranteed to be backed by a SQL database, hence
220 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700221 if (projection != null) {
222 return new MatrixCursor(projection, 0);
223 }
224
225 // Null projection means all columns but we have no idea which they are.
226 // However, the caller may be expecting to access them my index. Hence,
227 // we have to execute the query as if allowed to get a cursor with the
228 // columns. We then use the column names to return an empty cursor.
Steve McKayea93fe72016-12-02 11:35:35 -0800229 Cursor cursor = ContentProvider.this.query(
230 uri, projection, queryArgs,
231 CancellationSignal.fromTransport(cancellationSignal));
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700232 if (cursor == null) {
233 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700234 }
235
236 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700237 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800238 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700239 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700240 try {
241 return ContentProvider.this.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800242 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700243 CancellationSignal.fromTransport(cancellationSignal));
244 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700245 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 }
248
Jeff Brown75ea64f2012-01-25 19:37:13 -0800249 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100251 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100252 uri = maybeGetUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 return ContentProvider.this.getType(uri);
254 }
255
Jeff Brown75ea64f2012-01-25 19:37:13 -0800256 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800257 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100258 validateIncomingUri(uri);
259 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100260 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800261 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800262 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800263 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700264 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700265 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100266 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700267 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700268 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 }
271
Jeff Brown75ea64f2012-01-25 19:37:13 -0800272 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800273 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100274 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100275 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800276 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800277 return 0;
278 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700279 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700280 try {
281 return ContentProvider.this.bulkInsert(uri, initialValues);
282 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700283 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 }
286
Jeff Brown75ea64f2012-01-25 19:37:13 -0800287 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800288 public ContentProviderResult[] applyBatch(String callingPkg,
289 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700290 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100291 int numOperations = operations.size();
292 final int[] userIds = new int[numOperations];
293 for (int i = 0; i < numOperations; i++) {
294 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100295 Uri uri = operation.getUri();
296 validateIncomingUri(uri);
297 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100298 if (userIds[i] != UserHandle.USER_CURRENT) {
299 // Removing the user id from the uri.
300 operation = new ContentProviderOperation(operation, true);
301 operations.set(i, operation);
302 }
Fred Quintana89437372009-05-15 15:10:40 -0700303 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800304 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800305 != AppOpsManager.MODE_ALLOWED) {
306 throw new OperationApplicationException("App op not allowed", 0);
307 }
Fred Quintana89437372009-05-15 15:10:40 -0700308 }
Fred Quintana89437372009-05-15 15:10:40 -0700309 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800310 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800311 != AppOpsManager.MODE_ALLOWED) {
312 throw new OperationApplicationException("App op not allowed", 0);
313 }
Fred Quintana89437372009-05-15 15:10:40 -0700314 }
315 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700316 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700317 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100318 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800319 if (results != null) {
320 for (int i = 0; i < results.length ; i++) {
321 if (userIds[i] != UserHandle.USER_CURRENT) {
322 // Adding the userId to the uri.
323 results[i] = new ContentProviderResult(results[i], userIds[i]);
324 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100325 }
326 }
327 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700328 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700329 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700330 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700331 }
332
Jeff Brown75ea64f2012-01-25 19:37:13 -0800333 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800334 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100335 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100336 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800337 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800338 return 0;
339 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700340 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700341 try {
342 return ContentProvider.this.delete(uri, selection, selectionArgs);
343 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700344 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 }
347
Jeff Brown75ea64f2012-01-25 19:37:13 -0800348 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800349 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100351 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100352 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800353 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800354 return 0;
355 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700356 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700357 try {
358 return ContentProvider.this.update(uri, values, selection, selectionArgs);
359 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700360 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 }
363
Jeff Brown75ea64f2012-01-25 19:37:13 -0800364 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700365 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800366 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
367 IBinder callerToken) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100368 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100369 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800370 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700371 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700372 try {
373 return ContentProvider.this.openFile(
374 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
375 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700376 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800378 }
379
Jeff Brown75ea64f2012-01-25 19:37:13 -0800380 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700381 public AssetFileDescriptor openAssetFile(
382 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100384 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100385 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800386 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700387 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700388 try {
389 return ContentProvider.this.openAssetFile(
390 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
391 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700392 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800394 }
395
Jeff Brown75ea64f2012-01-25 19:37:13 -0800396 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800397 public Bundle call(
398 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600399 Bundle.setDefusable(extras, true);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700400 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700401 try {
402 return ContentProvider.this.call(method, arg, extras);
403 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700404 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700405 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800406 }
407
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700408 @Override
409 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100410 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100411 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700412 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
413 }
414
415 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800416 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700417 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600418 Bundle.setDefusable(opts, true);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100419 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100420 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800421 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700422 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700423 try {
424 return ContentProvider.this.openTypedAssetFile(
425 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
426 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700427 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700428 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700429 }
430
Jeff Brown75ea64f2012-01-25 19:37:13 -0800431 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700432 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800433 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800434 }
435
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700436 @Override
437 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100438 validateIncomingUri(uri);
439 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100440 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800441 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700442 return null;
443 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700444 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700445 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100446 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700447 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700448 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700449 }
450 }
451
452 @Override
453 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100454 validateIncomingUri(uri);
455 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100456 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800457 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700458 return null;
459 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700460 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700461 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100462 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700463 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700464 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700465 }
466 }
467
Ben Lin1cf454f2016-11-10 13:50:54 -0800468 @Override
469 public boolean refresh(String callingPkg, Uri uri, Bundle args,
470 ICancellationSignal cancellationSignal) throws RemoteException {
471 validateIncomingUri(uri);
472 uri = getUriWithoutUserId(uri);
473 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
474 return false;
475 }
476 final String original = setCallingPackage(callingPkg);
477 try {
478 return ContentProvider.this.refresh(uri, args,
479 CancellationSignal.fromTransport(cancellationSignal));
480 } finally {
481 setCallingPackage(original);
482 }
483 }
484
Dianne Hackbornff170242014-11-19 10:59:01 -0800485 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
486 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800487 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800488 if (enforceWritePermission(callingPkg, uri, callerToken)
489 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800490 throw new FileNotFoundException("App op not allowed");
491 }
492 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800493 if (enforceReadPermission(callingPkg, uri, callerToken)
494 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800495 throw new FileNotFoundException("App op not allowed");
496 }
497 }
498 }
499
Dianne Hackbornff170242014-11-19 10:59:01 -0800500 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
501 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700502 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
503 if (mode != MODE_ALLOWED) {
504 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800505 }
Svet Ganov99b60432015-06-27 13:15:22 -0700506
507 if (mReadOp != AppOpsManager.OP_NONE) {
508 return mAppOpsManager.noteProxyOp(mReadOp, callingPkg);
509 }
510
Dianne Hackborn35654b62013-01-14 17:38:02 -0800511 return AppOpsManager.MODE_ALLOWED;
512 }
513
Dianne Hackbornff170242014-11-19 10:59:01 -0800514 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
515 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700516 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
517 if (mode != MODE_ALLOWED) {
518 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800519 }
Svet Ganov99b60432015-06-27 13:15:22 -0700520
521 if (mWriteOp != AppOpsManager.OP_NONE) {
522 return mAppOpsManager.noteProxyOp(mWriteOp, callingPkg);
523 }
524
Dianne Hackborn35654b62013-01-14 17:38:02 -0800525 return AppOpsManager.MODE_ALLOWED;
526 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700527 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800528
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100529 boolean checkUser(int pid, int uid, Context context) {
530 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700531 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100532 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
533 == PERMISSION_GRANTED;
534 }
535
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700536 /**
537 * Verify that calling app holds both the given permission and any app-op
538 * associated with that permission.
539 */
540 private int checkPermissionAndAppOp(String permission, String callingPkg,
541 IBinder callerToken) {
542 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
543 callerToken) != PERMISSION_GRANTED) {
544 return MODE_ERRORED;
545 }
546
547 final int permOp = AppOpsManager.permissionToOpCode(permission);
548 if (permOp != AppOpsManager.OP_NONE) {
549 return mTransport.mAppOpsManager.noteProxyOp(permOp, callingPkg);
550 }
551
552 return MODE_ALLOWED;
553 }
554
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700555 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700556 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800557 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700558 final Context context = getContext();
559 final int pid = Binder.getCallingPid();
560 final int uid = Binder.getCallingUid();
561 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700562 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700563
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700564 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700565 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700566 }
567
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100568 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700569 final String componentPerm = getReadPermission();
570 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700571 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
572 if (mode == MODE_ALLOWED) {
573 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700574 } else {
575 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700576 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700577 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700578 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700579
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700580 // track if unprotected read is allowed; any denied
581 // <path-permission> below removes this ability
582 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700583
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700584 final PathPermission[] pps = getPathPermissions();
585 if (pps != null) {
586 final String path = uri.getPath();
587 for (PathPermission pp : pps) {
588 final String pathPerm = pp.getReadPermission();
589 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700590 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
591 if (mode == MODE_ALLOWED) {
592 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700593 } else {
594 // any denied <path-permission> means we lose
595 // default <provider> access.
596 allowDefaultRead = false;
597 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700598 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700599 }
600 }
601 }
602 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700603
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700604 // if we passed <path-permission> checks above, and no default
605 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700606 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700608
609 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800610 final int callingUserId = UserHandle.getUserId(uid);
611 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
612 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800613 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
614 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700615 return MODE_ALLOWED;
616 }
617
618 // If the worst denial we found above was ignored, then pass that
619 // ignored through; otherwise we assume it should be a real error below.
620 if (strongestMode == MODE_IGNORED) {
621 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700622 }
623
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600624 final String suffix;
625 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
626 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
627 } else if (mExported) {
628 suffix = " requires " + missingPerm + ", or grantUriPermission()";
629 } else {
630 suffix = " requires the provider be exported, or grantUriPermission()";
631 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700632 throw new SecurityException("Permission Denial: reading "
633 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600634 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700635 }
636
637 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700638 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800639 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700640 final Context context = getContext();
641 final int pid = Binder.getCallingPid();
642 final int uid = Binder.getCallingUid();
643 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700644 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700645
646 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700647 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700648 }
649
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100650 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700651 final String componentPerm = getWritePermission();
652 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700653 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
654 if (mode == MODE_ALLOWED) {
655 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700656 } else {
657 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700658 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700659 }
660 }
661
662 // track if unprotected write is allowed; any denied
663 // <path-permission> below removes this ability
664 boolean allowDefaultWrite = (componentPerm == null);
665
666 final PathPermission[] pps = getPathPermissions();
667 if (pps != null) {
668 final String path = uri.getPath();
669 for (PathPermission pp : pps) {
670 final String pathPerm = pp.getWritePermission();
671 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700672 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
673 if (mode == MODE_ALLOWED) {
674 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700675 } else {
676 // any denied <path-permission> means we lose
677 // default <provider> access.
678 allowDefaultWrite = false;
679 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700680 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700681 }
682 }
683 }
684 }
685
686 // if we passed <path-permission> checks above, and no default
687 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700688 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700689 }
690
691 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800692 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
693 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700694 return MODE_ALLOWED;
695 }
696
697 // If the worst denial we found above was ignored, then pass that
698 // ignored through; otherwise we assume it should be a real error below.
699 if (strongestMode == MODE_IGNORED) {
700 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700701 }
702
703 final String failReason = mExported
704 ? " requires " + missingPerm + ", or grantUriPermission()"
705 : " requires the provider be exported, or grantUriPermission()";
706 throw new SecurityException("Permission Denial: writing "
707 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
708 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 }
710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700712 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800713 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 * constructor.
715 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700716 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 return mContext;
718 }
719
720 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700721 * Set the calling package, returning the current value (or {@code null})
722 * which can be used later to restore the previous state.
723 */
724 private String setCallingPackage(String callingPackage) {
725 final String original = mCallingPackage.get();
726 mCallingPackage.set(callingPackage);
727 return original;
728 }
729
730 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700731 * Return the package name of the caller that initiated the request being
732 * processed on the current thread. The returned package will have been
733 * verified to belong to the calling UID. Returns {@code null} if not
734 * currently processing a request.
735 * <p>
736 * This will always return {@code null} when processing
737 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
738 *
739 * @see Binder#getCallingUid()
740 * @see Context#grantUriPermission(String, Uri, int)
741 * @throws SecurityException if the calling package doesn't belong to the
742 * calling UID.
743 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700744 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700745 final String pkg = mCallingPackage.get();
746 if (pkg != null) {
747 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
748 }
749 return pkg;
750 }
751
752 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100753 * Change the authorities of the ContentProvider.
754 * This is normally set for you from its manifest information when the provider is first
755 * created.
756 * @hide
757 * @param authorities the semi-colon separated authorities of the ContentProvider.
758 */
759 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100760 if (authorities != null) {
761 if (authorities.indexOf(';') == -1) {
762 mAuthority = authorities;
763 mAuthorities = null;
764 } else {
765 mAuthority = null;
766 mAuthorities = authorities.split(";");
767 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100768 }
769 }
770
771 /** @hide */
772 protected final boolean matchesOurAuthorities(String authority) {
773 if (mAuthority != null) {
774 return mAuthority.equals(authority);
775 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100776 if (mAuthorities != null) {
777 int length = mAuthorities.length;
778 for (int i = 0; i < length; i++) {
779 if (mAuthorities[i].equals(authority)) return true;
780 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100781 }
782 return false;
783 }
784
785
786 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 * Change the permission required to read data from the content
788 * provider. This is normally set for you from its manifest information
789 * when the provider is first created.
790 *
791 * @param permission Name of the permission required for read-only access.
792 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700793 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 mReadPermission = permission;
795 }
796
797 /**
798 * Return the name of the permission required for read-only access to
799 * this content provider. This method can be called from multiple
800 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800801 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
802 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700804 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 return mReadPermission;
806 }
807
808 /**
809 * Change the permission required to read and write data in the content
810 * provider. This is normally set for you from its manifest information
811 * when the provider is first created.
812 *
813 * @param permission Name of the permission required for read/write access.
814 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700815 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 mWritePermission = permission;
817 }
818
819 /**
820 * Return the name of the permission required for read/write access to
821 * this content provider. This method can be called from multiple
822 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800823 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
824 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700826 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 return mWritePermission;
828 }
829
830 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700831 * Change the path-based permission required to read and/or write data in
832 * the content provider. This is normally set for you from its manifest
833 * information when the provider is first created.
834 *
835 * @param permissions Array of path permission descriptions.
836 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700837 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700838 mPathPermissions = permissions;
839 }
840
841 /**
842 * Return the path-based permissions required for read and/or write access to
843 * this content provider. This method can be called from multiple
844 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800845 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
846 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700847 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700848 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700849 return mPathPermissions;
850 }
851
Dianne Hackborn35654b62013-01-14 17:38:02 -0800852 /** @hide */
853 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800854 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800855 mTransport.mReadOp = readOp;
856 mTransport.mWriteOp = writeOp;
857 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800858 }
859
Dianne Hackborn961321f2013-02-05 17:22:41 -0800860 /** @hide */
861 public AppOpsManager getAppOpsManager() {
862 return mTransport.mAppOpsManager;
863 }
864
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700865 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700866 * Implement this to initialize your content provider on startup.
867 * This method is called for all registered content providers on the
868 * application main thread at application launch time. It must not perform
869 * lengthy operations, or application startup will be delayed.
870 *
871 * <p>You should defer nontrivial initialization (such as opening,
872 * upgrading, and scanning databases) until the content provider is used
873 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
874 * keeps application startup fast, avoids unnecessary work if the provider
875 * turns out not to be needed, and stops database errors (such as a full
876 * disk) from halting application launch.
877 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700878 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700879 * is a helpful utility class that makes it easy to manage databases,
880 * and will automatically defer opening until first use. If you do use
881 * SQLiteOpenHelper, make sure to avoid calling
882 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
883 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
884 * from this method. (Instead, override
885 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
886 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 *
888 * @return true if the provider was successfully loaded, false otherwise
889 */
890 public abstract boolean onCreate();
891
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700892 /**
893 * {@inheritDoc}
894 * This method is always called on the application main thread, and must
895 * not perform lengthy operations.
896 *
897 * <p>The default content provider implementation does nothing.
898 * Override this method to take appropriate action.
899 * (Content providers do not usually care about things like screen
900 * orientation, but may want to know about locale changes.)
901 */
Steve McKayea93fe72016-12-02 11:35:35 -0800902 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 public void onConfigurationChanged(Configuration newConfig) {
904 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700905
906 /**
907 * {@inheritDoc}
908 * This method is always called on the application main thread, and must
909 * not perform lengthy operations.
910 *
911 * <p>The default content provider implementation does nothing.
912 * Subclasses may override this method to take appropriate action.
913 */
Steve McKayea93fe72016-12-02 11:35:35 -0800914 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 public void onLowMemory() {
916 }
917
Steve McKayea93fe72016-12-02 11:35:35 -0800918 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700919 public void onTrimMemory(int level) {
920 }
921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700923 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -0800924 *
925 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
926 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
927 * implementation of this method.
928 *
929 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800930 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
931 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 * <p>
933 * Example client call:<p>
934 * <pre>// Request a specific record.
935 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000936 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 projection, // Which columns to return.
938 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000939 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 People.NAME + " ASC"); // Sort order.</pre>
941 * Example implementation:<p>
942 * <pre>// SQLiteQueryBuilder is a helper class that creates the
943 // proper SQL syntax for us.
944 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
945
946 // Set the table we're querying.
947 qBuilder.setTables(DATABASE_TABLE_NAME);
948
949 // If the query ends in a specific record number, we're
950 // being asked for a specific record, so set the
951 // WHERE clause in our query.
952 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
953 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
954 }
955
956 // Make the query.
957 Cursor c = qBuilder.query(mDb,
958 projection,
959 selection,
960 selectionArgs,
961 groupBy,
962 having,
963 sortOrder);
964 c.setNotificationUri(getContext().getContentResolver(), uri);
965 return c;</pre>
966 *
967 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000968 * if the client is requesting a specific record, the URI will end in a record number
969 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
970 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800972 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800974 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000975 * @param selectionArgs You may include ?s in selection, which will be replaced by
976 * the values from selectionArgs, in order that they appear in the selection.
977 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800979 * If {@code null} then the provider is free to define the sort order.
980 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700982 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
983 @Nullable String selection, @Nullable String[] selectionArgs,
984 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985
Fred Quintana5bba6322009-10-05 14:21:12 -0700986 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800987 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -0800988 *
989 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
990 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
991 *
992 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -0800993 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
994 * and Threads</a>.
995 * <p>
996 * Example client call:<p>
997 * <pre>// Request a specific record.
998 * Cursor managedCursor = managedQuery(
999 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1000 projection, // Which columns to return.
1001 null, // WHERE clause.
1002 null, // WHERE clause value substitution
1003 People.NAME + " ASC"); // Sort order.</pre>
1004 * Example implementation:<p>
1005 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1006 // proper SQL syntax for us.
1007 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1008
1009 // Set the table we're querying.
1010 qBuilder.setTables(DATABASE_TABLE_NAME);
1011
1012 // If the query ends in a specific record number, we're
1013 // being asked for a specific record, so set the
1014 // WHERE clause in our query.
1015 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1016 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1017 }
1018
1019 // Make the query.
1020 Cursor c = qBuilder.query(mDb,
1021 projection,
1022 selection,
1023 selectionArgs,
1024 groupBy,
1025 having,
1026 sortOrder);
1027 c.setNotificationUri(getContext().getContentResolver(), uri);
1028 return c;</pre>
1029 * <p>
1030 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001031 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1032 * signal to ensure correct operation on older versions of the Android Framework in
1033 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001034 *
1035 * @param uri The URI to query. This will be the full URI sent by the client;
1036 * if the client is requesting a specific record, the URI will end in a record number
1037 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1038 * that _id value.
1039 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001040 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001041 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001042 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001043 * @param selectionArgs You may include ?s in selection, which will be replaced by
1044 * the values from selectionArgs, in order that they appear in the selection.
1045 * The values will be bound as Strings.
1046 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001047 * If {@code null} then the provider is free to define the sort order.
1048 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001049 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001050 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001051 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001052 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001053 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1054 @Nullable String selection, @Nullable String[] selectionArgs,
1055 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001056 return query(uri, projection, selection, selectionArgs, sortOrder);
1057 }
1058
1059 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001060 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1061 * Arguments may include traditional SQL style query arguments. When present these
1062 * should be handled according to the contract established in
1063 * {@link #query(Uri, String[], String, String[], String, CancellationSignal).
1064 *
1065 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Steve McKay29c3f682016-12-16 14:52:59 -08001066 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION}
1067 * <li>{@link ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1068 * <li>{@link ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001069 *
Steve McKay76b27702017-04-24 12:07:53 -07001070 * <p>This method can be called from multiple threads, as described in
1071 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1072 * and Threads</a>.
1073 *
1074 * <p>
1075 * Example client call:<p>
1076 * <pre>// Request 20 records starting at row index 30.
1077 Bundle queryArgs = new Bundle();
1078 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1079 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1080
1081 Cursor cursor = getContentResolver().query(
1082 contentUri, // Content Uri is specific to individual content providers.
1083 projection, // String[] describing which columns to return.
1084 queryArgs, // Query arguments.
1085 null); // Cancellation signal.</pre>
1086 *
1087 * Example implementation:<p>
1088 * <pre>
1089
1090 int recordsetSize = 0x1000; // Actual value is implementation specific.
1091 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1092
1093 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1094 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1095
1096 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1097
1098 // Calculate the number of items to include in the cursor.
1099 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1100
1101 // Build the paged result set....
1102 for (int i = offset; i < offset + numItems; i++) {
1103 // populate row from your data.
1104 }
1105
1106 Bundle extras = new Bundle();
1107 c.setExtras(extras);
1108
1109 // Any QUERY_ARG_* key may be included if honored.
1110 // In an actual implementation, include only keys that are both present in queryArgs
1111 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1112 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1113 // then QUERY_ARG_OFFSET should be omitted.
1114 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1115 ContentResolver.QUERY_ARG_OFFSET,
1116 ContentResolver.QUERY_ARG_LIMIT
1117 });
1118
1119 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1120
1121 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1122
1123 return cursor;</pre>
1124 * <p>
Steve McKayea93fe72016-12-02 11:35:35 -08001125 * @see #query(Uri, String[], String, String[], String, CancellationSignal) for
1126 * implementation details.
1127 *
1128 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001129 * @param projection The list of columns to put into the cursor.
1130 * If {@code null} provide a default set of columns.
1131 * @param queryArgs A Bundle containing all additional information necessary for the query.
1132 * Values in the Bundle may include SQL style arguments.
1133 * @param cancellationSignal A signal to cancel the operation in progress,
1134 * or {@code null}.
1135 * @return a Cursor or {@code null}.
1136 */
1137 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1138 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1139 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001140
Steve McKayd7ece9f2017-01-12 16:59:59 -08001141 // if client doesn't supply an SQL sort order argument, attempt to build one from
1142 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001143 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001144 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1145 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1146 }
1147
Steve McKayea93fe72016-12-02 11:35:35 -08001148 return query(
1149 uri,
1150 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001151 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1152 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1153 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001154 cancellationSignal);
1155 }
1156
1157 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001158 * Implement this to handle requests for the MIME type of the data at the
1159 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 * <code>vnd.android.cursor.item</code> for a single record,
1161 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001162 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001163 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1164 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001166 * <p>Note that there are no permissions needed for an application to
1167 * access this information; if your content provider requires read and/or
1168 * write permissions, or is not exported, all applications can still call
1169 * this method regardless of their access permissions. This allows them
1170 * to retrieve the MIME type for a URI when dispatching intents.
1171 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001173 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001175 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176
1177 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001178 * Implement this to support canonicalization of URIs that refer to your
1179 * content provider. A canonical URI is one that can be transported across
1180 * devices, backup/restore, and other contexts, and still be able to refer
1181 * to the same data item. Typically this is implemented by adding query
1182 * params to the URI allowing the content provider to verify that an incoming
1183 * canonical URI references the same data as it was originally intended for and,
1184 * if it doesn't, to find that data (if it exists) in the current environment.
1185 *
1186 * <p>For example, if the content provider holds people and a normal URI in it
1187 * is created with a row index into that people database, the cananical representation
1188 * may have an additional query param at the end which specifies the name of the
1189 * person it is intended for. Later calls into the provider with that URI will look
1190 * up the row of that URI's base index and, if it doesn't match or its entry's
1191 * name doesn't match the name in the query param, perform a query on its database
1192 * to find the correct row to operate on.</p>
1193 *
1194 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1195 * URIs (including this one) must perform this verification and recovery of any
1196 * canonical URIs they receive. In addition, you must also implement
1197 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1198 *
1199 * <p>The default implementation of this method returns null, indicating that
1200 * canonical URIs are not supported.</p>
1201 *
1202 * @param url The Uri to canonicalize.
1203 *
1204 * @return Return the canonical representation of <var>url</var>, or null if
1205 * canonicalization of that Uri is not supported.
1206 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001207 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001208 return null;
1209 }
1210
1211 /**
1212 * Remove canonicalization from canonical URIs previously returned by
1213 * {@link #canonicalize}. For example, if your implementation is to add
1214 * a query param to canonicalize a URI, this method can simply trip any
1215 * query params on the URI. The default implementation always returns the
1216 * same <var>url</var> that was passed in.
1217 *
1218 * @param url The Uri to remove any canonicalization from.
1219 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001220 * @return Return the non-canonical representation of <var>url</var>, return
1221 * the <var>url</var> as-is if there is nothing to do, or return null if
1222 * the data identified by the canonical representation can not be found in
1223 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001224 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001225 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001226 return url;
1227 }
1228
1229 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001230 * Implement this to support refresh of content identified by {@code uri}. By default, this
1231 * method returns false; providers who wish to implement this should return true to signal the
1232 * client that the provider has tried refreshing with its own implementation.
1233 * <p>
1234 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1235 * <p>
1236 * Client code should only invoke this method when there is a strong indication (such as a user
1237 * initiated pull to refresh gesture) that the content is stale.
1238 * <p>
1239 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1240 * notifications when content changes.
1241 *
1242 * @param uri The Uri identifying the data to refresh.
1243 * @param args Additional options from the client. The definitions of these are specific to the
1244 * content provider being called.
1245 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1246 * none. For example, if you called refresh on a particular uri, you should call
1247 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1248 * canceled the refresh request.
1249 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001250 */
1251 public boolean refresh(Uri uri, @Nullable Bundle args,
1252 @Nullable CancellationSignal cancellationSignal) {
1253 return false;
1254 }
1255
1256 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001257 * @hide
1258 * Implementation when a caller has performed an insert on the content
1259 * provider, but that call has been rejected for the operation given
1260 * to {@link #setAppOps(int, int)}. The default implementation simply
1261 * returns a dummy URI that is the base URI with a 0 path element
1262 * appended.
1263 */
1264 public Uri rejectInsert(Uri uri, ContentValues values) {
1265 // If not allowed, we need to return some reasonable URI. Maybe the
1266 // content provider should be responsible for this, but for now we
1267 // will just return the base URI with a dummy '0' tagged on to it.
1268 // You shouldn't be able to read if you can't write, anyway, so it
1269 // shouldn't matter much what is returned.
1270 return uri.buildUpon().appendPath("0").build();
1271 }
1272
1273 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001274 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1276 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001277 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001278 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1279 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001280 * @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 -08001281 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001282 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 * @return The URI for the newly inserted item.
1284 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001285 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286
1287 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001288 * Override this to handle requests to insert a set of new rows, or the
1289 * default implementation will iterate over the values and call
1290 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1292 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001293 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001294 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1295 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 *
1297 * @param uri The content:// URI of the insertion request.
1298 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001299 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 * @return The number of values that were inserted.
1301 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001302 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 int numValues = values.length;
1304 for (int i = 0; i < numValues; i++) {
1305 insert(uri, values[i]);
1306 }
1307 return numValues;
1308 }
1309
1310 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001311 * Implement this to handle requests to delete one or more rows.
1312 * The implementation should apply the selection clause when performing
1313 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001314 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001316 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001317 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1318 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 *
1320 * <p>The implementation is responsible for parsing out a row ID at the end
1321 * of the URI, if a specific row is being deleted. That is, the client would
1322 * pass in <code>content://contacts/people/22</code> and the implementation is
1323 * responsible for parsing the record number (22) when creating a SQL statement.
1324 *
1325 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1326 * @param selection An optional restriction to apply to rows when deleting.
1327 * @return The number of rows affected.
1328 * @throws SQLException
1329 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001330 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1331 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332
1333 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001334 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001335 * The implementation should update all rows matching the selection
1336 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1338 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001339 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001340 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1341 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 *
1343 * @param uri The URI to query. This can potentially have a record ID if this
1344 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001345 * @param values A set of column_name/value pairs to update in the database.
1346 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 * @param selection An optional filter to match rows to update.
1348 * @return the number of rows affected.
1349 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001350 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001351 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352
1353 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001354 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001355 * The default implementation always throws {@link FileNotFoundException}.
1356 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001357 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1358 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001359 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001360 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1361 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001362 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 *
1364 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1365 * their responsibility to close it when done. That is, the implementation
1366 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001367 * <p>
1368 * If opened with the exclusive "r" or "w" modes, the returned
1369 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1370 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1371 * supports seeking.
1372 * <p>
1373 * If you need to detect when the returned ParcelFileDescriptor has been
1374 * closed, or if the remote process has crashed or encountered some other
1375 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1376 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1377 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1378 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001379 * <p>
1380 * If you need to return a large file that isn't backed by a real file on
1381 * disk, such as a file on a network share or cloud storage service,
1382 * consider using
1383 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1384 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001386 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1387 * to return the appropriate MIME type for the data returned here with
1388 * the same URI. This will allow intent resolution to automatically determine the data MIME
1389 * type and select the appropriate matching targets as part of its operation.</p>
1390 *
1391 * <p class="note">For better interoperability with other applications, it is recommended
1392 * that for any URIs that can be opened, you also support queries on them
1393 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1394 * You may also want to support other common columns if you have additional meta-data
1395 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1396 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1397 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 * @param uri The URI whose file is to be opened.
1399 * @param mode Access mode for the file. May be "r" for read-only access,
1400 * "rw" for read and write access, or "rwt" for read and write access
1401 * that truncates any existing file.
1402 *
1403 * @return Returns a new ParcelFileDescriptor which you can use to access
1404 * the file.
1405 *
1406 * @throws FileNotFoundException Throws FileNotFoundException if there is
1407 * no file associated with the given URI or the mode is invalid.
1408 * @throws SecurityException Throws SecurityException if the caller does
1409 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001410 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 * @see #openAssetFile(Uri, String)
1412 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001413 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001414 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001415 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001416 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 throws FileNotFoundException {
1418 throw new FileNotFoundException("No files supported by provider at "
1419 + uri);
1420 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001423 * Override this to handle requests to open a file blob.
1424 * The default implementation always throws {@link FileNotFoundException}.
1425 * This method can be called from multiple threads, as described in
1426 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1427 * and Threads</a>.
1428 *
1429 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1430 * to the caller. This way large data (such as images and documents) can be
1431 * returned without copying the content.
1432 *
1433 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1434 * their responsibility to close it when done. That is, the implementation
1435 * of this method should create a new ParcelFileDescriptor for each call.
1436 * <p>
1437 * If opened with the exclusive "r" or "w" modes, the returned
1438 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1439 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1440 * supports seeking.
1441 * <p>
1442 * If you need to detect when the returned ParcelFileDescriptor has been
1443 * closed, or if the remote process has crashed or encountered some other
1444 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1445 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1446 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1447 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1448 *
1449 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1450 * to return the appropriate MIME type for the data returned here with
1451 * the same URI. This will allow intent resolution to automatically determine the data MIME
1452 * type and select the appropriate matching targets as part of its operation.</p>
1453 *
1454 * <p class="note">For better interoperability with other applications, it is recommended
1455 * that for any URIs that can be opened, you also support queries on them
1456 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1457 * You may also want to support other common columns if you have additional meta-data
1458 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1459 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1460 *
1461 * @param uri The URI whose file is to be opened.
1462 * @param mode Access mode for the file. May be "r" for read-only access,
1463 * "w" for write-only access, "rw" for read and write access, or
1464 * "rwt" for read and write access that truncates any existing
1465 * file.
1466 * @param signal A signal to cancel the operation in progress, or
1467 * {@code null} if none. For example, if you are downloading a
1468 * file from the network to service a "rw" mode request, you
1469 * should periodically call
1470 * {@link CancellationSignal#throwIfCanceled()} to check whether
1471 * the client has canceled the request and abort the download.
1472 *
1473 * @return Returns a new ParcelFileDescriptor which you can use to access
1474 * the file.
1475 *
1476 * @throws FileNotFoundException Throws FileNotFoundException if there is
1477 * no file associated with the given URI or the mode is invalid.
1478 * @throws SecurityException Throws SecurityException if the caller does
1479 * not have permission to access the file.
1480 *
1481 * @see #openAssetFile(Uri, String)
1482 * @see #openFileHelper(Uri, String)
1483 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001484 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001485 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001486 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1487 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001488 return openFile(uri, mode);
1489 }
1490
1491 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 * This is like {@link #openFile}, but can be implemented by providers
1493 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001494 * inside of their .apk.
1495 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001496 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1497 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001498 *
1499 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001500 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001501 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1503 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1504 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001505 * <p>
1506 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1507 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001508 *
1509 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 * should create the AssetFileDescriptor with
1511 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001512 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001514 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1515 * to return the appropriate MIME type for the data returned here with
1516 * the same URI. This will allow intent resolution to automatically determine the data MIME
1517 * type and select the appropriate matching targets as part of its operation.</p>
1518 *
1519 * <p class="note">For better interoperability with other applications, it is recommended
1520 * that for any URIs that can be opened, you also support queries on them
1521 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1522 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 * @param uri The URI whose file is to be opened.
1524 * @param mode Access mode for the file. May be "r" for read-only access,
1525 * "w" for write-only access (erasing whatever data is currently in
1526 * the file), "wa" for write-only access to append to any existing data,
1527 * "rw" for read and write access on any existing data, and "rwt" for read
1528 * and write access that truncates any existing file.
1529 *
1530 * @return Returns a new AssetFileDescriptor which you can use to access
1531 * the file.
1532 *
1533 * @throws FileNotFoundException Throws FileNotFoundException if there is
1534 * no file associated with the given URI or the mode is invalid.
1535 * @throws SecurityException Throws SecurityException if the caller does
1536 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001537 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 * @see #openFile(Uri, String)
1539 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001540 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001542 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 throws FileNotFoundException {
1544 ParcelFileDescriptor fd = openFile(uri, mode);
1545 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1546 }
1547
1548 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001549 * This is like {@link #openFile}, but can be implemented by providers
1550 * that need to be able to return sub-sections of files, often assets
1551 * inside of their .apk.
1552 * This method can be called from multiple threads, as described in
1553 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1554 * and Threads</a>.
1555 *
1556 * <p>If you implement this, your clients must be able to deal with such
1557 * file slices, either directly with
1558 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1559 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1560 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1561 * methods.
1562 * <p>
1563 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1564 * streaming of data.
1565 *
1566 * <p class="note">If you are implementing this to return a full file, you
1567 * should create the AssetFileDescriptor with
1568 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1569 * applications that cannot handle sub-sections of files.</p>
1570 *
1571 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1572 * to return the appropriate MIME type for the data returned here with
1573 * the same URI. This will allow intent resolution to automatically determine the data MIME
1574 * type and select the appropriate matching targets as part of its operation.</p>
1575 *
1576 * <p class="note">For better interoperability with other applications, it is recommended
1577 * that for any URIs that can be opened, you also support queries on them
1578 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1579 *
1580 * @param uri The URI whose file is to be opened.
1581 * @param mode Access mode for the file. May be "r" for read-only access,
1582 * "w" for write-only access (erasing whatever data is currently in
1583 * the file), "wa" for write-only access to append to any existing data,
1584 * "rw" for read and write access on any existing data, and "rwt" for read
1585 * and write access that truncates any existing file.
1586 * @param signal A signal to cancel the operation in progress, or
1587 * {@code null} if none. For example, if you are downloading a
1588 * file from the network to service a "rw" mode request, you
1589 * should periodically call
1590 * {@link CancellationSignal#throwIfCanceled()} to check whether
1591 * the client has canceled the request and abort the download.
1592 *
1593 * @return Returns a new AssetFileDescriptor which you can use to access
1594 * the file.
1595 *
1596 * @throws FileNotFoundException Throws FileNotFoundException if there is
1597 * no file associated with the given URI or the mode is invalid.
1598 * @throws SecurityException Throws SecurityException if the caller does
1599 * not have permission to access the file.
1600 *
1601 * @see #openFile(Uri, String)
1602 * @see #openFileHelper(Uri, String)
1603 * @see #getType(android.net.Uri)
1604 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001605 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1606 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001607 return openAssetFile(uri, mode);
1608 }
1609
1610 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 * Convenience for subclasses that wish to implement {@link #openFile}
1612 * by looking up a column named "_data" at the given URI.
1613 *
1614 * @param uri The URI to be opened.
1615 * @param mode The file mode. May be "r" for read-only access,
1616 * "w" for write-only access (erasing whatever data is currently in
1617 * the file), "wa" for write-only access to append to any existing data,
1618 * "rw" for read and write access on any existing data, and "rwt" for read
1619 * and write access that truncates any existing file.
1620 *
1621 * @return Returns a new ParcelFileDescriptor that can be used by the
1622 * client to access the file.
1623 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001624 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1625 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1627 int count = (c != null) ? c.getCount() : 0;
1628 if (count != 1) {
1629 // If there is not exactly one result, throw an appropriate
1630 // exception.
1631 if (c != null) {
1632 c.close();
1633 }
1634 if (count == 0) {
1635 throw new FileNotFoundException("No entry for " + uri);
1636 }
1637 throw new FileNotFoundException("Multiple items at " + uri);
1638 }
1639
1640 c.moveToFirst();
1641 int i = c.getColumnIndex("_data");
1642 String path = (i >= 0 ? c.getString(i) : null);
1643 c.close();
1644 if (path == null) {
1645 throw new FileNotFoundException("Column _data not found.");
1646 }
1647
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001648 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 return ParcelFileDescriptor.open(new File(path), modeBits);
1650 }
1651
1652 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001653 * Called by a client to determine the types of data streams that this
1654 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001655 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001656 * of a particular type, return that MIME type if it matches the given
1657 * mimeTypeFilter. If it can perform type conversions, return an array
1658 * of all supported MIME types that match mimeTypeFilter.
1659 *
1660 * @param uri The data in the content provider being queried.
1661 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001662 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001663 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001664 * given mimeTypeFilter. Otherwise returns an array of all available
1665 * concrete MIME types.
1666 *
1667 * @see #getType(Uri)
1668 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001669 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001670 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001671 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001672 return null;
1673 }
1674
1675 /**
1676 * Called by a client to open a read-only stream containing data of a
1677 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1678 * except the file can only be read-only and the content provider may
1679 * perform data conversions to generate data of the desired type.
1680 *
1681 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001682 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001683 * {@link #openAssetFile(Uri, String)}.
1684 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001685 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001686 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001687 * <p>
1688 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1689 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001690 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001691 * <p class="note">For better interoperability with other applications, it is recommended
1692 * that for any URIs that can be opened, you also support queries on them
1693 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1694 * You may also want to support other common columns if you have additional meta-data
1695 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1696 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1697 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001698 * @param uri The data in the content provider being queried.
1699 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001700 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001701 * requirements; in this case the content provider will pick its best
1702 * type matching the pattern.
1703 * @param opts Additional options from the client. The definitions of
1704 * these are specific to the content provider being called.
1705 *
1706 * @return Returns a new AssetFileDescriptor from which the client can
1707 * read data of the desired type.
1708 *
1709 * @throws FileNotFoundException Throws FileNotFoundException if there is
1710 * no file associated with the given URI or the mode is invalid.
1711 * @throws SecurityException Throws SecurityException if the caller does
1712 * not have permission to access the data.
1713 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1714 * content provider does not support the requested MIME type.
1715 *
1716 * @see #getStreamTypes(Uri, String)
1717 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001718 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001719 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001720 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1721 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001722 if ("*/*".equals(mimeTypeFilter)) {
1723 // If they can take anything, the untyped open call is good enough.
1724 return openAssetFile(uri, "r");
1725 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001726 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001727 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001728 // Use old untyped open call if this provider has a type for this
1729 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001730 return openAssetFile(uri, "r");
1731 }
1732 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1733 }
1734
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001735
1736 /**
1737 * Called by a client to open a read-only stream containing data of a
1738 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1739 * except the file can only be read-only and the content provider may
1740 * perform data conversions to generate data of the desired type.
1741 *
1742 * <p>The default implementation compares the given mimeType against the
1743 * result of {@link #getType(Uri)} and, if they match, simply calls
1744 * {@link #openAssetFile(Uri, String)}.
1745 *
1746 * <p>See {@link ClipData} for examples of the use and implementation
1747 * of this method.
1748 * <p>
1749 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1750 * streaming of data.
1751 *
1752 * <p class="note">For better interoperability with other applications, it is recommended
1753 * that for any URIs that can be opened, you also support queries on them
1754 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1755 * You may also want to support other common columns if you have additional meta-data
1756 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1757 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1758 *
1759 * @param uri The data in the content provider being queried.
1760 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001761 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001762 * requirements; in this case the content provider will pick its best
1763 * type matching the pattern.
1764 * @param opts Additional options from the client. The definitions of
1765 * these are specific to the content provider being called.
1766 * @param signal A signal to cancel the operation in progress, or
1767 * {@code null} if none. For example, if you are downloading a
1768 * file from the network to service a "rw" mode request, you
1769 * should periodically call
1770 * {@link CancellationSignal#throwIfCanceled()} to check whether
1771 * the client has canceled the request and abort the download.
1772 *
1773 * @return Returns a new AssetFileDescriptor from which the client can
1774 * read data of the desired type.
1775 *
1776 * @throws FileNotFoundException Throws FileNotFoundException if there is
1777 * no file associated with the given URI or the mode is invalid.
1778 * @throws SecurityException Throws SecurityException if the caller does
1779 * not have permission to access the data.
1780 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1781 * content provider does not support the requested MIME type.
1782 *
1783 * @see #getStreamTypes(Uri, String)
1784 * @see #openAssetFile(Uri, String)
1785 * @see ClipDescription#compareMimeTypes(String, String)
1786 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001787 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1788 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1789 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001790 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1791 }
1792
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001793 /**
1794 * Interface to write a stream of data to a pipe. Use with
1795 * {@link ContentProvider#openPipeHelper}.
1796 */
1797 public interface PipeDataWriter<T> {
1798 /**
1799 * Called from a background thread to stream data out to a pipe.
1800 * Note that the pipe is blocking, so this thread can block on
1801 * writes for an arbitrary amount of time if the client is slow
1802 * at reading.
1803 *
1804 * @param output The pipe where data should be written. This will be
1805 * closed for you upon returning from this function.
1806 * @param uri The URI whose data is to be written.
1807 * @param mimeType The desired type of data to be written.
1808 * @param opts Options supplied by caller.
1809 * @param args Your own custom arguments.
1810 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001811 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1812 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001813 }
1814
1815 /**
1816 * A helper function for implementing {@link #openTypedAssetFile}, for
1817 * creating a data pipe and background thread allowing you to stream
1818 * generated data back to the client. This function returns a new
1819 * ParcelFileDescriptor that should be returned to the caller (the caller
1820 * is responsible for closing it).
1821 *
1822 * @param uri The URI whose data is to be written.
1823 * @param mimeType The desired type of data to be written.
1824 * @param opts Options supplied by caller.
1825 * @param args Your own custom arguments.
1826 * @param func Interface implementing the function that will actually
1827 * stream the data.
1828 * @return Returns a new ParcelFileDescriptor holding the read side of
1829 * the pipe. This should be returned to the caller for reading; the caller
1830 * is responsible for closing it when done.
1831 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001832 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1833 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1834 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001835 try {
1836 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1837
1838 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1839 @Override
1840 protected Object doInBackground(Object... params) {
1841 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1842 try {
1843 fds[1].close();
1844 } catch (IOException e) {
1845 Log.w(TAG, "Failure closing pipe", e);
1846 }
1847 return null;
1848 }
1849 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001850 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001851
1852 return fds[0];
1853 } catch (IOException e) {
1854 throw new FileNotFoundException("failure making pipe");
1855 }
1856 }
1857
1858 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 * Returns true if this instance is a temporary content provider.
1860 * @return true if this instance is a temporary content provider
1861 */
1862 protected boolean isTemporary() {
1863 return false;
1864 }
1865
1866 /**
1867 * Returns the Binder object for this provider.
1868 *
1869 * @return the Binder object for this provider
1870 * @hide
1871 */
1872 public IContentProvider getIContentProvider() {
1873 return mTransport;
1874 }
1875
1876 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001877 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1878 * when directly instantiating the provider for testing.
1879 * @hide
1880 */
1881 public void attachInfoForTesting(Context context, ProviderInfo info) {
1882 attachInfo(context, info, true);
1883 }
1884
1885 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 * After being instantiated, this is called to tell the content provider
1887 * about itself.
1888 *
1889 * @param context The context this provider is running in
1890 * @param info Registered information about this content provider
1891 */
1892 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001893 attachInfo(context, info, false);
1894 }
1895
1896 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001897 mNoPerms = testing;
1898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 /*
1900 * Only allow it to be set once, so after the content service gives
1901 * this to us clients can't change it.
1902 */
1903 if (mContext == null) {
1904 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001905 if (context != null) {
1906 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1907 Context.APP_OPS_SERVICE);
1908 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001909 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 if (info != null) {
1911 setReadPermission(info.readPermission);
1912 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001913 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001914 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001915 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001916 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 }
1918 ContentProvider.this.onCreate();
1919 }
1920 }
Fred Quintanace31b232009-05-04 16:01:15 -07001921
1922 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001923 * Override this to handle requests to perform a batch of operations, or the
1924 * default implementation will iterate over the operations and call
1925 * {@link ContentProviderOperation#apply} on each of them.
1926 * If all calls to {@link ContentProviderOperation#apply} succeed
1927 * then a {@link ContentProviderResult} array with as many
1928 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001929 * fail, it is up to the implementation how many of the others take effect.
1930 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001931 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1932 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001933 *
Fred Quintanace31b232009-05-04 16:01:15 -07001934 * @param operations the operations to apply
1935 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001936 * @throws OperationApplicationException thrown if any operation fails.
1937 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001938 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001939 public @NonNull ContentProviderResult[] applyBatch(
1940 @NonNull ArrayList<ContentProviderOperation> operations)
1941 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001942 final int numOperations = operations.size();
1943 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1944 for (int i = 0; i < numOperations; i++) {
1945 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001946 }
1947 return results;
1948 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001949
1950 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001951 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001952 * interfaces that are cheaper and/or unnatural for a table-like
1953 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001954 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001955 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1956 * on this entry into the content provider besides the basic ability for the application
1957 * to get access to the provider at all. For example, it has no idea whether the call
1958 * being executed may read or write data in the provider, so can't enforce those
1959 * individual permissions. Any implementation of this method <strong>must</strong>
1960 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1961 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001962 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1963 * @param arg provider-defined String argument. May be {@code null}.
1964 * @param extras provider-defined Bundle argument. May be {@code null}.
1965 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001966 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001967 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001968 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
1969 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001970 return null;
1971 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001972
1973 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001974 * Implement this to shut down the ContentProvider instance. You can then
1975 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08001976 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001977 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001978 * Android normally handles ContentProvider startup and shutdown
1979 * automatically. You do not need to start up or shut down a
1980 * ContentProvider. When you invoke a test method on a ContentProvider,
1981 * however, a ContentProvider instance is started and keeps running after
1982 * the test finishes, even if a succeeding test instantiates another
1983 * ContentProvider. A conflict develops because the two instances are
1984 * usually running against the same underlying data source (for example, an
1985 * sqlite database).
1986 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001987 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001988 * Implementing shutDown() avoids this conflict by providing a way to
1989 * terminate the ContentProvider. This method can also prevent memory leaks
1990 * from multiple instantiations of the ContentProvider, and it can ensure
1991 * unit test isolation by allowing you to completely clean up the test
1992 * fixture before moving on to the next test.
1993 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001994 */
1995 public void shutdown() {
1996 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1997 "connections are gracefully shutdown");
1998 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001999
2000 /**
2001 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002002 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002003 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002004 * @param fd The raw file descriptor that the dump is being sent to.
2005 * @param writer The PrintWriter to which you should dump your state. This will be
2006 * closed for you after you return.
2007 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002008 */
2009 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2010 writer.println("nothing to dump");
2011 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002012
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002013 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002014 private void validateIncomingUri(Uri uri) throws SecurityException {
2015 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002016 if (!mSingleUser) {
2017 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2018 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2019 throw new SecurityException("trying to query a ContentProvider in user "
2020 + mContext.getUserId() + " with a uri belonging to user " + userId);
2021 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002022 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002023 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
2024 String message = "The authority of the uri " + uri + " does not match the one of the "
2025 + "contentProvider: ";
2026 if (mAuthority != null) {
2027 message += mAuthority;
2028 } else {
Andreas Gampee6748ce2015-12-11 18:00:38 -08002029 message += Arrays.toString(mAuthorities);
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002030 }
2031 throw new SecurityException(message);
2032 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002033 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002034
2035 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002036 private Uri maybeGetUriWithoutUserId(Uri uri) {
2037 if (mSingleUser) {
2038 return uri;
2039 }
2040 return getUriWithoutUserId(uri);
2041 }
2042
2043 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002044 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2045 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002046 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002047 if (end == -1) return defaultUserId;
2048 String userIdString = auth.substring(0, end);
2049 try {
2050 return Integer.parseInt(userIdString);
2051 } catch (NumberFormatException e) {
2052 Log.w(TAG, "Error parsing userId.", e);
2053 return UserHandle.USER_NULL;
2054 }
2055 }
2056
2057 /** @hide */
2058 public static int getUserIdFromAuthority(String auth) {
2059 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2060 }
2061
2062 /** @hide */
2063 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2064 if (uri == null) return defaultUserId;
2065 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2066 }
2067
2068 /** @hide */
2069 public static int getUserIdFromUri(Uri uri) {
2070 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2071 }
2072
2073 /**
2074 * Removes userId part from authority string. Expects format:
2075 * userId@some.authority
2076 * If there is no userId in the authority, it symply returns the argument
2077 * @hide
2078 */
2079 public static String getAuthorityWithoutUserId(String auth) {
2080 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002081 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002082 return auth.substring(end+1);
2083 }
2084
2085 /** @hide */
2086 public static Uri getUriWithoutUserId(Uri uri) {
2087 if (uri == null) return null;
2088 Uri.Builder builder = uri.buildUpon();
2089 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2090 return builder.build();
2091 }
2092
2093 /** @hide */
2094 public static boolean uriHasUserId(Uri uri) {
2095 if (uri == null) return false;
2096 return !TextUtils.isEmpty(uri.getUserInfo());
2097 }
2098
2099 /** @hide */
2100 public static Uri maybeAddUserId(Uri uri, int userId) {
2101 if (uri == null) return null;
2102 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002103 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002104 if (!uriHasUserId(uri)) {
2105 //We don't add the user Id if there's already one
2106 Uri.Builder builder = uri.buildUpon();
2107 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2108 return builder.build();
2109 }
2110 }
2111 return uri;
2112 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002113}