blob: ddfe75568eee1abcfee45cb8d58c3a6c6ab06587 [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;
Eugene Susla93519852018-06-13 16:44:31 -070021import static android.app.AppOpsManager.MODE_DEFAULT;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070022import static android.app.AppOpsManager.MODE_ERRORED;
23import static android.app.AppOpsManager.MODE_IGNORED;
24import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060025import static android.os.Trace.TRACE_TAG_DATABASE;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070026
Jeff Sharkey673db442015-06-11 19:30:57 -070027import android.annotation.NonNull;
Scott Kennedy9f78f652015-03-01 15:29:25 -080028import android.annotation.Nullable;
Mathew Inwood5c0d3542018-08-14 13:54:31 +010029import android.annotation.UnsupportedAppUsage;
Dianne Hackborn35654b62013-01-14 17:38:02 -080030import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070031import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.content.pm.ProviderInfo;
33import android.content.res.AssetFileDescriptor;
34import android.content.res.Configuration;
35import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070036import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.database.SQLException;
38import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070039import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.os.Binder;
Mathew Inwood8c854f82018-09-14 12:35:36 +010041import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080042import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070043import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080044import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070045import android.os.ICancellationSignal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070047import android.os.Process;
Ben Lin1cf454f2016-11-10 13:50:54 -080048import android.os.RemoteException;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060049import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070050import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060051import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010052import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070053import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060055import com.android.internal.annotations.VisibleForTesting;
56
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080058import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070060import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080061import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070062import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080063import java.util.Arrays;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060064import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065
66/**
67 * Content providers are one of the primary building blocks of Android applications, providing
68 * content to applications. They encapsulate data and provide it to applications through the single
69 * {@link ContentResolver} interface. A content provider is only required if you need to share
70 * data between multiple applications. For example, the contacts data is used by multiple
71 * applications and must be stored in a content provider. If you don't need to share data amongst
72 * multiple applications you can use a database directly via
73 * {@link android.database.sqlite.SQLiteDatabase}.
74 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 * <p>When a request is made via
76 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
77 * request to the content provider registered with the authority. The content provider can interpret
78 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
79 * URIs.</p>
80 *
81 * <p>The primary methods that need to be implemented are:
82 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070083 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 * <li>{@link #query} which returns data to the caller</li>
85 * <li>{@link #insert} which inserts new data into the content provider</li>
86 * <li>{@link #update} which updates existing data in the content provider</li>
87 * <li>{@link #delete} which deletes data from the content provider</li>
88 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
89 * </ul></p>
90 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070091 * <p class="caution">Data access methods (such as {@link #insert} and
92 * {@link #update}) may be called from many threads at once, and must be thread-safe.
93 * Other methods (such as {@link #onCreate}) are only called from the application
94 * main thread, and must avoid performing lengthy operations. See the method
95 * descriptions for their expected thread behavior.</p>
96 *
97 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
98 * ContentProvider instance, so subclasses don't have to worry about the details of
99 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -0700100 *
101 * <div class="special reference">
102 * <h3>Developer Guides</h3>
103 * <p>For more information about using content providers, read the
104 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
105 * developer guide.</p>
Nicole Borrelli8a5f04a2018-09-20 14:19:14 -0700106 * </div>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700108public abstract class ContentProvider implements ContentInterface, ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800109
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700110 private static final String TAG = "ContentProvider";
111
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900112 /*
113 * Note: if you add methods to ContentProvider, you must add similar methods to
114 * MockContentProvider.
115 */
116
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100117 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700119 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100120
121 // Since most Providers have only one authority, we keep both a String and a String[] to improve
122 // performance.
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100123 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100124 private String mAuthority;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100125 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100126 private String[] mAuthorities;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100127 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 private String mReadPermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100129 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 private String mWritePermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100131 @UnsupportedAppUsage
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700132 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700133 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800134 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700135 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136
Jeff Sharkey497789e2019-02-15 19:41:30 -0700137 private ThreadLocal<String> mCallingPackage;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 private Transport mTransport = new Transport();
140
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700141 /**
142 * Construct a ContentProvider instance. Content providers must be
143 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
144 * in the manifest</a>, accessed with {@link ContentResolver}, and created
145 * automatically by the system, so applications usually do not create
146 * ContentProvider instances directly.
147 *
148 * <p>At construction time, the object is uninitialized, and most fields and
149 * methods are unavailable. Subclasses should initialize themselves in
150 * {@link #onCreate}, not the constructor.
151 *
152 * <p>Content providers are created on the application main thread at
153 * application launch time. The constructor must not perform lengthy
154 * operations, or application startup will be delayed.
155 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900156 public ContentProvider() {
157 }
158
159 /**
160 * Constructor just for mocking.
161 *
162 * @param context A Context object which should be some mock instance (like the
163 * instance of {@link android.test.mock.MockContext}).
164 * @param readPermission The read permision you want this instance should have in the
165 * test, which is available via {@link #getReadPermission()}.
166 * @param writePermission The write permission you want this instance should have
167 * in the test, which is available via {@link #getWritePermission()}.
168 * @param pathPermissions The PathPermissions you want this instance should have
169 * in the test, which is available via {@link #getPathPermissions()}.
170 * @hide
171 */
Mathew Inwood8c854f82018-09-14 12:35:36 +0100172 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900173 public ContentProvider(
174 Context context,
175 String readPermission,
176 String writePermission,
177 PathPermission[] pathPermissions) {
178 mContext = context;
179 mReadPermission = readPermission;
180 mWritePermission = writePermission;
181 mPathPermissions = pathPermissions;
182 }
183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 /**
185 * Given an IContentProvider, try to coerce it back to the real
186 * ContentProvider object if it is running in the local process. This can
187 * be used if you know you are running in the same process as a provider,
188 * and want to get direct access to its implementation details. Most
189 * clients should not nor have a reason to use it.
190 *
191 * @param abstractInterface The ContentProvider interface that is to be
192 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800193 * @return If the IContentProvider is non-{@code null} and local, returns its actual
194 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 * @hide
196 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100197 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 public static ContentProvider coerceToLocalContentProvider(
199 IContentProvider abstractInterface) {
200 if (abstractInterface instanceof Transport) {
201 return ((Transport)abstractInterface).getContentProvider();
202 }
203 return null;
204 }
205
206 /**
207 * Binder object that deals with remoting.
208 *
209 * @hide
210 */
211 class Transport extends ContentProviderNative {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700212 volatile AppOpsManager mAppOpsManager = null;
213 volatile int mReadOp = AppOpsManager.OP_NONE;
214 volatile int mWriteOp = AppOpsManager.OP_NONE;
215 volatile ContentInterface mInterface = ContentProvider.this;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 ContentProvider getContentProvider() {
218 return ContentProvider.this;
219 }
220
Jeff Brownd2183652011-10-09 12:39:53 -0700221 @Override
222 public String getProviderName() {
223 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 }
225
Jeff Brown75ea64f2012-01-25 19:37:13 -0800226 @Override
Steve McKayea93fe72016-12-02 11:35:35 -0800227 public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
228 @Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600229 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100230 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800231 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700232 // The caller has no access to the data, so return an empty cursor with
233 // the columns in the requested order. The caller may ask for an invalid
234 // column and we would not catch that but this is not a problem in practice.
235 // We do not call ContentProvider#query with a modified where clause since
236 // the implementation is not guaranteed to be backed by a SQL database, hence
237 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700238 if (projection != null) {
239 return new MatrixCursor(projection, 0);
240 }
241
242 // Null projection means all columns but we have no idea which they are.
243 // However, the caller may be expecting to access them my index. Hence,
244 // we have to execute the query as if allowed to get a cursor with the
245 // columns. We then use the column names to return an empty cursor.
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700246 Cursor cursor;
247 final String original = setCallingPackage(callingPkg);
248 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700249 cursor = mInterface.query(
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700250 uri, projection, queryArgs,
251 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700252 } catch (RemoteException e) {
253 throw e.rethrowAsRuntimeException();
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700254 } finally {
255 setCallingPackage(original);
256 }
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700257 if (cursor == null) {
258 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700259 }
260
261 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700262 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800263 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600264 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700265 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700266 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700267 return mInterface.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800268 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700269 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700270 } catch (RemoteException e) {
271 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700272 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700273 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600274 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 }
277
Jeff Brown75ea64f2012-01-25 19:37:13 -0800278 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 public String getType(Uri uri) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700280 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600281 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100282 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600283 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
284 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700285 return mInterface.getType(uri);
286 } catch (RemoteException e) {
287 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600288 } finally {
289 Trace.traceEnd(TRACE_TAG_DATABASE);
290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 }
292
Jeff Brown75ea64f2012-01-25 19:37:13 -0800293 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800294 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600295 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100296 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100297 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800298 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700299 final String original = setCallingPackage(callingPkg);
300 try {
301 return rejectInsert(uri, initialValues);
302 } finally {
303 setCallingPackage(original);
304 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800305 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600306 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700307 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700308 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700309 return maybeAddUserId(mInterface.insert(uri, initialValues), userId);
310 } catch (RemoteException e) {
311 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700312 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700313 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600314 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 }
317
Jeff Brown75ea64f2012-01-25 19:37:13 -0800318 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800319 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600320 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100321 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800322 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800323 return 0;
324 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600325 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700326 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700327 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700328 return mInterface.bulkInsert(uri, initialValues);
329 } catch (RemoteException e) {
330 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700331 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700332 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600333 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800335 }
336
Jeff Brown75ea64f2012-01-25 19:37:13 -0800337 @Override
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700338 public ContentProviderResult[] applyBatch(String callingPkg, String authority,
Dianne Hackborn35654b62013-01-14 17:38:02 -0800339 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700340 throws OperationApplicationException {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700341 validateIncomingAuthority(authority);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100342 int numOperations = operations.size();
343 final int[] userIds = new int[numOperations];
344 for (int i = 0; i < numOperations; i++) {
345 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100346 Uri uri = operation.getUri();
Jeff Sharkey9144b4d2018-09-26 20:15:12 -0600347 userIds[i] = getUserIdFromUri(uri);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600348 uri = validateIncomingUri(uri);
349 uri = maybeGetUriWithoutUserId(uri);
350 // Rebuild operation if we changed the Uri above
351 if (!Objects.equals(operation.getUri(), uri)) {
352 operation = new ContentProviderOperation(operation, uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100353 operations.set(i, operation);
354 }
Fred Quintana89437372009-05-15 15:10:40 -0700355 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800356 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800357 != AppOpsManager.MODE_ALLOWED) {
358 throw new OperationApplicationException("App op not allowed", 0);
359 }
Fred Quintana89437372009-05-15 15:10:40 -0700360 }
Fred Quintana89437372009-05-15 15:10:40 -0700361 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800362 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800363 != AppOpsManager.MODE_ALLOWED) {
364 throw new OperationApplicationException("App op not allowed", 0);
365 }
Fred Quintana89437372009-05-15 15:10:40 -0700366 }
367 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600368 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700369 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700370 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700371 ContentProviderResult[] results = mInterface.applyBatch(authority,
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700372 operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800373 if (results != null) {
374 for (int i = 0; i < results.length ; i++) {
375 if (userIds[i] != UserHandle.USER_CURRENT) {
376 // Adding the userId to the uri.
377 results[i] = new ContentProviderResult(results[i], userIds[i]);
378 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100379 }
380 }
381 return results;
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700382 } catch (RemoteException e) {
383 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700384 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700385 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600386 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700387 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700388 }
389
Jeff Brown75ea64f2012-01-25 19:37:13 -0800390 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800391 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600392 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100393 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800394 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800395 return 0;
396 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600397 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700398 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700399 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700400 return mInterface.delete(uri, selection, selectionArgs);
401 } catch (RemoteException e) {
402 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700403 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700404 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600405 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 }
408
Jeff Brown75ea64f2012-01-25 19:37:13 -0800409 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800410 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 String[] selectionArgs) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600412 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100413 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800414 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800415 return 0;
416 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600417 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700418 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700419 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700420 return mInterface.update(uri, values, selection, selectionArgs);
421 } catch (RemoteException e) {
422 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700423 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700424 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600425 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 }
428
Jeff Brown75ea64f2012-01-25 19:37:13 -0800429 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700430 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800431 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
432 IBinder callerToken) throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600433 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100434 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800435 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600436 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700437 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700438 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700439 return mInterface.openFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700440 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700441 } catch (RemoteException e) {
442 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700443 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700444 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600445 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 }
448
Jeff Brown75ea64f2012-01-25 19:37:13 -0800449 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700450 public AssetFileDescriptor openAssetFile(
451 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800452 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600453 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100454 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800455 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600456 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700457 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700458 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700459 return mInterface.openAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700460 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700461 } catch (RemoteException e) {
462 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700463 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700464 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600465 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 }
468
Jeff Brown75ea64f2012-01-25 19:37:13 -0800469 @Override
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700470 public Bundle call(String callingPkg, String authority, String method, @Nullable String arg,
471 @Nullable Bundle extras) {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700472 validateIncomingAuthority(authority);
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600473 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600474 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700475 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700476 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700477 return mInterface.call(authority, method, arg, extras);
478 } catch (RemoteException e) {
479 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700480 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700481 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600482 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700483 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800484 }
485
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700486 @Override
487 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700488 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600489 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100490 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600491 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
492 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700493 return mInterface.getStreamTypes(uri, mimeTypeFilter);
494 } catch (RemoteException e) {
495 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600496 } finally {
497 Trace.traceEnd(TRACE_TAG_DATABASE);
498 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700499 }
500
501 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800502 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700503 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600504 Bundle.setDefusable(opts, true);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600505 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100506 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800507 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600508 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700509 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700510 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700511 return mInterface.openTypedAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700512 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700513 } catch (RemoteException e) {
514 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700515 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700516 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600517 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700518 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700519 }
520
Jeff Brown75ea64f2012-01-25 19:37:13 -0800521 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700522 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800523 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800524 }
525
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700526 @Override
527 public Uri canonicalize(String callingPkg, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600528 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100529 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100530 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800531 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700532 return null;
533 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600534 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700535 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700536 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700537 return maybeAddUserId(mInterface.canonicalize(uri), userId);
538 } catch (RemoteException e) {
539 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700540 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700541 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600542 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700543 }
544 }
545
546 @Override
547 public Uri uncanonicalize(String callingPkg, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600548 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100549 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100550 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800551 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700552 return null;
553 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600554 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700555 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700556 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700557 return maybeAddUserId(mInterface.uncanonicalize(uri), userId);
558 } catch (RemoteException e) {
559 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700560 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700561 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600562 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700563 }
564 }
565
Ben Lin1cf454f2016-11-10 13:50:54 -0800566 @Override
567 public boolean refresh(String callingPkg, Uri uri, Bundle args,
568 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600569 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800570 uri = getUriWithoutUserId(uri);
571 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
572 return false;
573 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600574 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Ben Lin1cf454f2016-11-10 13:50:54 -0800575 final String original = setCallingPackage(callingPkg);
576 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700577 return mInterface.refresh(uri, args,
Ben Lin1cf454f2016-11-10 13:50:54 -0800578 CancellationSignal.fromTransport(cancellationSignal));
579 } finally {
580 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600581 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800582 }
583 }
584
Dianne Hackbornff170242014-11-19 10:59:01 -0800585 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
586 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800587 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800588 if (enforceWritePermission(callingPkg, uri, callerToken)
589 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800590 throw new FileNotFoundException("App op not allowed");
591 }
592 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800593 if (enforceReadPermission(callingPkg, uri, callerToken)
594 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800595 throw new FileNotFoundException("App op not allowed");
596 }
597 }
598 }
599
Dianne Hackbornff170242014-11-19 10:59:01 -0800600 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
601 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700602 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
603 if (mode != MODE_ALLOWED) {
604 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800605 }
Svet Ganov99b60432015-06-27 13:15:22 -0700606
Eugene Susla93519852018-06-13 16:44:31 -0700607 return noteProxyOp(callingPkg, mReadOp);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800608 }
609
Dianne Hackbornff170242014-11-19 10:59:01 -0800610 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
611 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700612 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
613 if (mode != MODE_ALLOWED) {
614 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800615 }
Svet Ganov99b60432015-06-27 13:15:22 -0700616
Eugene Susla93519852018-06-13 16:44:31 -0700617 return noteProxyOp(callingPkg, mWriteOp);
618 }
619
620 private int noteProxyOp(String callingPkg, int op) {
621 if (op != AppOpsManager.OP_NONE) {
622 int mode = mAppOpsManager.noteProxyOp(op, callingPkg);
Eugene Suslab22f71e2018-11-30 10:17:20 -0800623 int nonDefaultMode = mode == MODE_DEFAULT ? interpretDefaultAppOpMode(op) : mode;
624 if (mode == MODE_DEFAULT && nonDefaultMode == MODE_IGNORED) {
Eugene Suslaaaa54272018-12-06 11:04:21 -0800625 Log.w(TAG, "Denying access for " + callingPkg + " to " + getClass().getName()
Eugene Suslab22f71e2018-11-30 10:17:20 -0800626 + " (" + AppOpsManager.opToName(op)
627 + " = " + AppOpsManager.opToName(mode) + ")");
628 }
629 return mode == MODE_DEFAULT ? nonDefaultMode : mode;
Svet Ganov99b60432015-06-27 13:15:22 -0700630 }
631
Dianne Hackborn35654b62013-01-14 17:38:02 -0800632 return AppOpsManager.MODE_ALLOWED;
633 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700634 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800635
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100636 boolean checkUser(int pid, int uid, Context context) {
637 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700638 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100639 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
640 == PERMISSION_GRANTED;
641 }
642
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700643 /**
644 * Verify that calling app holds both the given permission and any app-op
645 * associated with that permission.
646 */
647 private int checkPermissionAndAppOp(String permission, String callingPkg,
648 IBinder callerToken) {
649 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
650 callerToken) != PERMISSION_GRANTED) {
651 return MODE_ERRORED;
652 }
653
Eugene Susla93519852018-06-13 16:44:31 -0700654 return mTransport.noteProxyOp(callingPkg, AppOpsManager.permissionToOpCode(permission));
655 }
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700656
Eugene Susla93519852018-06-13 16:44:31 -0700657 /**
658 * Allows for custom interpretations of {@link AppOpsManager#MODE_DEFAULT} by individual
659 * content providers
660 *
661 * @hide
662 */
663 protected int interpretDefaultAppOpMode(int op) {
664 return MODE_IGNORED;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700665 }
666
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700667 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700668 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800669 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700670 final Context context = getContext();
671 final int pid = Binder.getCallingPid();
672 final int uid = Binder.getCallingUid();
673 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700674 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700675
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700676 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700677 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700678 }
679
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100680 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700681 final String componentPerm = getReadPermission();
682 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700683 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
684 if (mode == MODE_ALLOWED) {
685 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700686 } else {
687 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700688 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700689 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700690 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700691
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700692 // track if unprotected read is allowed; any denied
693 // <path-permission> below removes this ability
694 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700695
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700696 final PathPermission[] pps = getPathPermissions();
697 if (pps != null) {
698 final String path = uri.getPath();
699 for (PathPermission pp : pps) {
700 final String pathPerm = pp.getReadPermission();
701 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700702 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
703 if (mode == MODE_ALLOWED) {
704 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700705 } else {
706 // any denied <path-permission> means we lose
707 // default <provider> access.
708 allowDefaultRead = false;
709 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700710 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700711 }
712 }
713 }
714 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700715
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700716 // if we passed <path-permission> checks above, and no default
717 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700718 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700720
721 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800722 final int callingUserId = UserHandle.getUserId(uid);
723 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
724 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800725 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
726 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700727 return MODE_ALLOWED;
728 }
729
730 // If the worst denial we found above was ignored, then pass that
731 // ignored through; otherwise we assume it should be a real error below.
732 if (strongestMode == MODE_IGNORED) {
733 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700734 }
735
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600736 final String suffix;
737 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
738 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
739 } else if (mExported) {
740 suffix = " requires " + missingPerm + ", or grantUriPermission()";
741 } else {
742 suffix = " requires the provider be exported, or grantUriPermission()";
743 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700744 throw new SecurityException("Permission Denial: reading "
745 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600746 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700747 }
748
749 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700750 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800751 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700752 final Context context = getContext();
753 final int pid = Binder.getCallingPid();
754 final int uid = Binder.getCallingUid();
755 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700756 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700757
758 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700759 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700760 }
761
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100762 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700763 final String componentPerm = getWritePermission();
764 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700765 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
766 if (mode == MODE_ALLOWED) {
767 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700768 } else {
769 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700770 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700771 }
772 }
773
774 // track if unprotected write is allowed; any denied
775 // <path-permission> below removes this ability
776 boolean allowDefaultWrite = (componentPerm == null);
777
778 final PathPermission[] pps = getPathPermissions();
779 if (pps != null) {
780 final String path = uri.getPath();
781 for (PathPermission pp : pps) {
782 final String pathPerm = pp.getWritePermission();
783 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700784 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
785 if (mode == MODE_ALLOWED) {
786 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700787 } else {
788 // any denied <path-permission> means we lose
789 // default <provider> access.
790 allowDefaultWrite = false;
791 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700792 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700793 }
794 }
795 }
796 }
797
798 // if we passed <path-permission> checks above, and no default
799 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700800 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700801 }
802
803 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800804 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
805 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700806 return MODE_ALLOWED;
807 }
808
809 // If the worst denial we found above was ignored, then pass that
810 // ignored through; otherwise we assume it should be a real error below.
811 if (strongestMode == MODE_IGNORED) {
812 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700813 }
814
815 final String failReason = mExported
816 ? " requires " + missingPerm + ", or grantUriPermission()"
817 : " requires the provider be exported, or grantUriPermission()";
818 throw new SecurityException("Permission Denial: writing "
819 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
820 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 }
822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700824 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800825 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 * constructor.
827 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700828 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 return mContext;
830 }
831
832 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700833 * Set the calling package, returning the current value (or {@code null})
834 * which can be used later to restore the previous state.
835 */
836 private String setCallingPackage(String callingPackage) {
837 final String original = mCallingPackage.get();
838 mCallingPackage.set(callingPackage);
839 return original;
840 }
841
842 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700843 * Return the package name of the caller that initiated the request being
844 * processed on the current thread. The returned package will have been
845 * verified to belong to the calling UID. Returns {@code null} if not
846 * currently processing a request.
847 * <p>
848 * This will always return {@code null} when processing
849 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
850 *
851 * @see Binder#getCallingUid()
852 * @see Context#grantUriPermission(String, Uri, int)
853 * @throws SecurityException if the calling package doesn't belong to the
854 * calling UID.
855 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700856 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700857 final String pkg = mCallingPackage.get();
858 if (pkg != null) {
859 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
860 }
861 return pkg;
862 }
863
864 /**
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600865 * Opaque token representing the identity of an incoming IPC.
866 */
867 public final class CallingIdentity {
868 /** {@hide} */
869 public final long binderToken;
870 /** {@hide} */
871 public final String callingPackage;
872
873 /** {@hide} */
874 public CallingIdentity(long binderToken, String callingPackage) {
875 this.binderToken = binderToken;
876 this.callingPackage = callingPackage;
877 }
878 }
879
880 /**
881 * Reset the identity of the incoming IPC on the current thread.
882 * <p>
883 * Internally this calls {@link Binder#clearCallingIdentity()} and also
884 * clears any value stored in {@link #getCallingPackage()}.
885 *
886 * @return Returns an opaque token that can be used to restore the original
887 * calling identity by passing it to
888 * {@link #restoreCallingIdentity}.
889 */
890 public final @NonNull CallingIdentity clearCallingIdentity() {
891 return new CallingIdentity(Binder.clearCallingIdentity(), setCallingPackage(null));
892 }
893
894 /**
895 * Restore the identity of the incoming IPC on the current thread back to a
896 * previously identity that was returned by {@link #clearCallingIdentity}.
897 * <p>
898 * Internally this calls {@link Binder#restoreCallingIdentity(long)} and
899 * also restores any value stored in {@link #getCallingPackage()}.
900 */
901 public final void restoreCallingIdentity(@NonNull CallingIdentity identity) {
902 Binder.restoreCallingIdentity(identity.binderToken);
903 mCallingPackage.set(identity.callingPackage);
904 }
905
906 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100907 * Change the authorities of the ContentProvider.
908 * This is normally set for you from its manifest information when the provider is first
909 * created.
910 * @hide
911 * @param authorities the semi-colon separated authorities of the ContentProvider.
912 */
913 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100914 if (authorities != null) {
915 if (authorities.indexOf(';') == -1) {
916 mAuthority = authorities;
917 mAuthorities = null;
918 } else {
919 mAuthority = null;
920 mAuthorities = authorities.split(";");
921 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100922 }
923 }
924
925 /** @hide */
926 protected final boolean matchesOurAuthorities(String authority) {
927 if (mAuthority != null) {
928 return mAuthority.equals(authority);
929 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100930 if (mAuthorities != null) {
931 int length = mAuthorities.length;
932 for (int i = 0; i < length; i++) {
933 if (mAuthorities[i].equals(authority)) return true;
934 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100935 }
936 return false;
937 }
938
939
940 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 * Change the permission required to read data from the content
942 * provider. This is normally set for you from its manifest information
943 * when the provider is first created.
944 *
945 * @param permission Name of the permission required for read-only access.
946 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700947 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 mReadPermission = permission;
949 }
950
951 /**
952 * Return the name of the permission required for read-only access to
953 * this content provider. This method can be called from multiple
954 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800955 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
956 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700958 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 return mReadPermission;
960 }
961
962 /**
963 * Change the permission required to read and write data in the content
964 * provider. This is normally set for you from its manifest information
965 * when the provider is first created.
966 *
967 * @param permission Name of the permission required for read/write access.
968 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700969 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 mWritePermission = permission;
971 }
972
973 /**
974 * Return the name of the permission required for read/write access to
975 * this content provider. This method can be called from multiple
976 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800977 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
978 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700980 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 return mWritePermission;
982 }
983
984 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700985 * Change the path-based permission required to read and/or write data in
986 * the content provider. This is normally set for you from its manifest
987 * information when the provider is first created.
988 *
989 * @param permissions Array of path permission descriptions.
990 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700991 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700992 mPathPermissions = permissions;
993 }
994
995 /**
996 * Return the path-based permissions required for read and/or write access to
997 * this content provider. This method can be called from multiple
998 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800999 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1000 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001001 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001002 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001003 return mPathPermissions;
1004 }
1005
Dianne Hackborn35654b62013-01-14 17:38:02 -08001006 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001007 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -08001008 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001009 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001010 mTransport.mReadOp = readOp;
1011 mTransport.mWriteOp = writeOp;
1012 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001013 }
1014
Dianne Hackborn961321f2013-02-05 17:22:41 -08001015 /** @hide */
1016 public AppOpsManager getAppOpsManager() {
1017 return mTransport.mAppOpsManager;
1018 }
1019
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001020 /** @hide */
1021 public final void setTransportLoggingEnabled(boolean enabled) {
1022 if (enabled) {
1023 mTransport.mInterface = new LoggingContentInterface(getClass().getSimpleName(), this);
1024 } else {
1025 mTransport.mInterface = this;
1026 }
1027 }
1028
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001029 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001030 * Implement this to initialize your content provider on startup.
1031 * This method is called for all registered content providers on the
1032 * application main thread at application launch time. It must not perform
1033 * lengthy operations, or application startup will be delayed.
1034 *
1035 * <p>You should defer nontrivial initialization (such as opening,
1036 * upgrading, and scanning databases) until the content provider is used
1037 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
1038 * keeps application startup fast, avoids unnecessary work if the provider
1039 * turns out not to be needed, and stops database errors (such as a full
1040 * disk) from halting application launch.
1041 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001042 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001043 * is a helpful utility class that makes it easy to manage databases,
1044 * and will automatically defer opening until first use. If you do use
1045 * SQLiteOpenHelper, make sure to avoid calling
1046 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
1047 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
1048 * from this method. (Instead, override
1049 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
1050 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 *
1052 * @return true if the provider was successfully loaded, false otherwise
1053 */
1054 public abstract boolean onCreate();
1055
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001056 /**
1057 * {@inheritDoc}
1058 * This method is always called on the application main thread, and must
1059 * not perform lengthy operations.
1060 *
1061 * <p>The default content provider implementation does nothing.
1062 * Override this method to take appropriate action.
1063 * (Content providers do not usually care about things like screen
1064 * orientation, but may want to know about locale changes.)
1065 */
Steve McKayea93fe72016-12-02 11:35:35 -08001066 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 public void onConfigurationChanged(Configuration newConfig) {
1068 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001069
1070 /**
1071 * {@inheritDoc}
1072 * This method is always called on the application main thread, and must
1073 * not perform lengthy operations.
1074 *
1075 * <p>The default content provider implementation does nothing.
1076 * Subclasses may override this method to take appropriate action.
1077 */
Steve McKayea93fe72016-12-02 11:35:35 -08001078 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 public void onLowMemory() {
1080 }
1081
Steve McKayea93fe72016-12-02 11:35:35 -08001082 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001083 public void onTrimMemory(int level) {
1084 }
1085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001087 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -08001088 *
1089 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1090 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
1091 * implementation of this method.
1092 *
1093 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001094 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1095 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 * <p>
1097 * Example client call:<p>
1098 * <pre>// Request a specific record.
1099 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001100 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 projection, // Which columns to return.
1102 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001103 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 People.NAME + " ASC"); // Sort order.</pre>
1105 * Example implementation:<p>
1106 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1107 // proper SQL syntax for us.
1108 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1109
1110 // Set the table we're querying.
1111 qBuilder.setTables(DATABASE_TABLE_NAME);
1112
1113 // If the query ends in a specific record number, we're
1114 // being asked for a specific record, so set the
1115 // WHERE clause in our query.
1116 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1117 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1118 }
1119
1120 // Make the query.
1121 Cursor c = qBuilder.query(mDb,
1122 projection,
1123 selection,
1124 selectionArgs,
1125 groupBy,
1126 having,
1127 sortOrder);
1128 c.setNotificationUri(getContext().getContentResolver(), uri);
1129 return c;</pre>
1130 *
1131 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001132 * if the client is requesting a specific record, the URI will end in a record number
1133 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1134 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001136 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001138 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001139 * @param selectionArgs You may include ?s in selection, which will be replaced by
1140 * the values from selectionArgs, in order that they appear in the selection.
1141 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001143 * If {@code null} then the provider is free to define the sort order.
1144 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001146 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1147 @Nullable String selection, @Nullable String[] selectionArgs,
1148 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149
Fred Quintana5bba6322009-10-05 14:21:12 -07001150 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001151 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001152 *
1153 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1154 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1155 *
1156 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001157 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1158 * and Threads</a>.
1159 * <p>
1160 * Example client call:<p>
1161 * <pre>// Request a specific record.
1162 * Cursor managedCursor = managedQuery(
1163 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1164 projection, // Which columns to return.
1165 null, // WHERE clause.
1166 null, // WHERE clause value substitution
1167 People.NAME + " ASC"); // Sort order.</pre>
1168 * Example implementation:<p>
1169 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1170 // proper SQL syntax for us.
1171 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1172
1173 // Set the table we're querying.
1174 qBuilder.setTables(DATABASE_TABLE_NAME);
1175
1176 // If the query ends in a specific record number, we're
1177 // being asked for a specific record, so set the
1178 // WHERE clause in our query.
1179 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1180 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1181 }
1182
1183 // Make the query.
1184 Cursor c = qBuilder.query(mDb,
1185 projection,
1186 selection,
1187 selectionArgs,
1188 groupBy,
1189 having,
1190 sortOrder);
1191 c.setNotificationUri(getContext().getContentResolver(), uri);
1192 return c;</pre>
1193 * <p>
1194 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001195 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1196 * signal to ensure correct operation on older versions of the Android Framework in
1197 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001198 *
1199 * @param uri The URI to query. This will be the full URI sent by the client;
1200 * if the client is requesting a specific record, the URI will end in a record number
1201 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1202 * that _id value.
1203 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001204 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001205 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001206 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001207 * @param selectionArgs You may include ?s in selection, which will be replaced by
1208 * the values from selectionArgs, in order that they appear in the selection.
1209 * The values will be bound as Strings.
1210 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001211 * If {@code null} then the provider is free to define the sort order.
1212 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001213 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001214 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001215 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001216 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001217 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1218 @Nullable String selection, @Nullable String[] selectionArgs,
1219 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001220 return query(uri, projection, selection, selectionArgs, sortOrder);
1221 }
1222
1223 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001224 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1225 * Arguments may include traditional SQL style query arguments. When present these
1226 * should be handled according to the contract established in
Andrew Solovay27e43462018-12-12 15:38:06 -08001227 * {@link #query(Uri, String[], String, String[], String, CancellationSignal)}.
Steve McKayea93fe72016-12-02 11:35:35 -08001228 *
1229 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Andrew Solovay27e43462018-12-12 15:38:06 -08001230 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION}
1231 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1232 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001233 *
Steve McKay76b27702017-04-24 12:07:53 -07001234 * <p>This method can be called from multiple threads, as described in
1235 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1236 * and Threads</a>.
1237 *
1238 * <p>
1239 * Example client call:<p>
1240 * <pre>// Request 20 records starting at row index 30.
1241 Bundle queryArgs = new Bundle();
1242 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1243 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1244
1245 Cursor cursor = getContentResolver().query(
1246 contentUri, // Content Uri is specific to individual content providers.
1247 projection, // String[] describing which columns to return.
1248 queryArgs, // Query arguments.
1249 null); // Cancellation signal.</pre>
1250 *
1251 * Example implementation:<p>
1252 * <pre>
1253
1254 int recordsetSize = 0x1000; // Actual value is implementation specific.
1255 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1256
1257 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1258 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1259
1260 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1261
1262 // Calculate the number of items to include in the cursor.
1263 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1264
1265 // Build the paged result set....
1266 for (int i = offset; i < offset + numItems; i++) {
1267 // populate row from your data.
1268 }
1269
1270 Bundle extras = new Bundle();
1271 c.setExtras(extras);
1272
1273 // Any QUERY_ARG_* key may be included if honored.
1274 // In an actual implementation, include only keys that are both present in queryArgs
1275 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1276 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1277 // then QUERY_ARG_OFFSET should be omitted.
1278 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1279 ContentResolver.QUERY_ARG_OFFSET,
1280 ContentResolver.QUERY_ARG_LIMIT
1281 });
1282
1283 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1284
1285 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1286
1287 return cursor;</pre>
1288 * <p>
Andrew Solovay27e43462018-12-12 15:38:06 -08001289 * See {@link #query(Uri, String[], String, String[], String, CancellationSignal)}
1290 * for implementation details.
Steve McKayea93fe72016-12-02 11:35:35 -08001291 *
1292 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001293 * @param projection The list of columns to put into the cursor.
1294 * If {@code null} provide a default set of columns.
1295 * @param queryArgs A Bundle containing all additional information necessary for the query.
1296 * Values in the Bundle may include SQL style arguments.
1297 * @param cancellationSignal A signal to cancel the operation in progress,
1298 * or {@code null}.
1299 * @return a Cursor or {@code null}.
1300 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001301 @Override
Steve McKayea93fe72016-12-02 11:35:35 -08001302 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1303 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1304 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001305
Steve McKayd7ece9f2017-01-12 16:59:59 -08001306 // if client doesn't supply an SQL sort order argument, attempt to build one from
1307 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001308 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001309 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1310 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1311 }
1312
Steve McKayea93fe72016-12-02 11:35:35 -08001313 return query(
1314 uri,
1315 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001316 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1317 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1318 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001319 cancellationSignal);
1320 }
1321
1322 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001323 * Implement this to handle requests for the MIME type of the data at the
1324 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 * <code>vnd.android.cursor.item</code> for a single record,
1326 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001327 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001328 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1329 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001331 * <p>Note that there are no permissions needed for an application to
1332 * access this information; if your content provider requires read and/or
1333 * write permissions, or is not exported, all applications can still call
1334 * this method regardless of their access permissions. This allows them
1335 * to retrieve the MIME type for a URI when dispatching intents.
1336 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001338 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001340 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001341 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342
1343 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001344 * Implement this to support canonicalization of URIs that refer to your
1345 * content provider. A canonical URI is one that can be transported across
1346 * devices, backup/restore, and other contexts, and still be able to refer
1347 * to the same data item. Typically this is implemented by adding query
1348 * params to the URI allowing the content provider to verify that an incoming
1349 * canonical URI references the same data as it was originally intended for and,
1350 * if it doesn't, to find that data (if it exists) in the current environment.
1351 *
1352 * <p>For example, if the content provider holds people and a normal URI in it
1353 * is created with a row index into that people database, the cananical representation
1354 * may have an additional query param at the end which specifies the name of the
1355 * person it is intended for. Later calls into the provider with that URI will look
1356 * up the row of that URI's base index and, if it doesn't match or its entry's
1357 * name doesn't match the name in the query param, perform a query on its database
1358 * to find the correct row to operate on.</p>
1359 *
1360 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1361 * URIs (including this one) must perform this verification and recovery of any
1362 * canonical URIs they receive. In addition, you must also implement
1363 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1364 *
1365 * <p>The default implementation of this method returns null, indicating that
1366 * canonical URIs are not supported.</p>
1367 *
1368 * @param url The Uri to canonicalize.
1369 *
1370 * @return Return the canonical representation of <var>url</var>, or null if
1371 * canonicalization of that Uri is not supported.
1372 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001373 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001374 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001375 return null;
1376 }
1377
1378 /**
1379 * Remove canonicalization from canonical URIs previously returned by
1380 * {@link #canonicalize}. For example, if your implementation is to add
1381 * a query param to canonicalize a URI, this method can simply trip any
1382 * query params on the URI. The default implementation always returns the
1383 * same <var>url</var> that was passed in.
1384 *
1385 * @param url The Uri to remove any canonicalization from.
1386 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001387 * @return Return the non-canonical representation of <var>url</var>, return
1388 * the <var>url</var> as-is if there is nothing to do, or return null if
1389 * the data identified by the canonical representation can not be found in
1390 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001391 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001392 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001393 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001394 return url;
1395 }
1396
1397 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001398 * Implement this to support refresh of content identified by {@code uri}. By default, this
1399 * method returns false; providers who wish to implement this should return true to signal the
1400 * client that the provider has tried refreshing with its own implementation.
1401 * <p>
1402 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1403 * <p>
1404 * Client code should only invoke this method when there is a strong indication (such as a user
1405 * initiated pull to refresh gesture) that the content is stale.
1406 * <p>
1407 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1408 * notifications when content changes.
1409 *
1410 * @param uri The Uri identifying the data to refresh.
1411 * @param args Additional options from the client. The definitions of these are specific to the
1412 * content provider being called.
1413 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1414 * none. For example, if you called refresh on a particular uri, you should call
1415 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1416 * canceled the refresh request.
1417 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001418 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001419 @Override
Ben Lin1cf454f2016-11-10 13:50:54 -08001420 public boolean refresh(Uri uri, @Nullable Bundle args,
1421 @Nullable CancellationSignal cancellationSignal) {
1422 return false;
1423 }
1424
1425 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001426 * @hide
1427 * Implementation when a caller has performed an insert on the content
1428 * provider, but that call has been rejected for the operation given
1429 * to {@link #setAppOps(int, int)}. The default implementation simply
1430 * returns a dummy URI that is the base URI with a 0 path element
1431 * appended.
1432 */
1433 public Uri rejectInsert(Uri uri, ContentValues values) {
1434 // If not allowed, we need to return some reasonable URI. Maybe the
1435 // content provider should be responsible for this, but for now we
1436 // will just return the base URI with a dummy '0' tagged on to it.
1437 // You shouldn't be able to read if you can't write, anyway, so it
1438 // shouldn't matter much what is returned.
1439 return uri.buildUpon().appendPath("0").build();
1440 }
1441
1442 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001443 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1445 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001446 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001447 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1448 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001449 * @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 -08001450 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001451 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 * @return The URI for the newly inserted item.
1453 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001454 @Override
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001455 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456
1457 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001458 * Override this to handle requests to insert a set of new rows, or the
1459 * default implementation will iterate over the values and call
1460 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1462 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001463 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001464 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1465 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 *
1467 * @param uri The content:// URI of the insertion request.
1468 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001469 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 * @return The number of values that were inserted.
1471 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001472 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001473 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 int numValues = values.length;
1475 for (int i = 0; i < numValues; i++) {
1476 insert(uri, values[i]);
1477 }
1478 return numValues;
1479 }
1480
1481 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001482 * Implement this to handle requests to delete one or more rows.
1483 * The implementation should apply the selection clause when performing
1484 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001485 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001487 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001488 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1489 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 *
1491 * <p>The implementation is responsible for parsing out a row ID at the end
1492 * of the URI, if a specific row is being deleted. That is, the client would
1493 * pass in <code>content://contacts/people/22</code> and the implementation is
1494 * responsible for parsing the record number (22) when creating a SQL statement.
1495 *
1496 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1497 * @param selection An optional restriction to apply to rows when deleting.
1498 * @return The number of rows affected.
1499 * @throws SQLException
1500 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001501 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001502 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1503 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504
1505 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001506 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001507 * The implementation should update all rows matching the selection
1508 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1510 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001511 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001512 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1513 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 *
1515 * @param uri The URI to query. This can potentially have a record ID if this
1516 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001517 * @param values A set of column_name/value pairs to update in the database.
1518 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 * @param selection An optional filter to match rows to update.
1520 * @return the number of rows affected.
1521 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001522 @Override
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001523 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001524 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525
1526 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001527 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001528 * The default implementation always throws {@link FileNotFoundException}.
1529 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001530 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1531 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001532 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001533 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1534 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001535 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 *
1537 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1538 * their responsibility to close it when done. That is, the implementation
1539 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001540 * <p>
1541 * If opened with the exclusive "r" or "w" modes, the returned
1542 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1543 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1544 * supports seeking.
1545 * <p>
1546 * If you need to detect when the returned ParcelFileDescriptor has been
1547 * closed, or if the remote process has crashed or encountered some other
1548 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1549 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1550 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1551 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001552 * <p>
1553 * If you need to return a large file that isn't backed by a real file on
1554 * disk, such as a file on a network share or cloud storage service,
1555 * consider using
1556 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1557 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001559 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1560 * to return the appropriate MIME type for the data returned here with
1561 * the same URI. This will allow intent resolution to automatically determine the data MIME
1562 * type and select the appropriate matching targets as part of its operation.</p>
1563 *
1564 * <p class="note">For better interoperability with other applications, it is recommended
1565 * that for any URIs that can be opened, you also support queries on them
1566 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1567 * You may also want to support other common columns if you have additional meta-data
1568 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1569 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1570 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 * @param uri The URI whose file is to be opened.
1572 * @param mode Access mode for the file. May be "r" for read-only access,
1573 * "rw" for read and write access, or "rwt" for read and write access
1574 * that truncates any existing file.
1575 *
1576 * @return Returns a new ParcelFileDescriptor which you can use to access
1577 * the file.
1578 *
1579 * @throws FileNotFoundException Throws FileNotFoundException if there is
1580 * no file associated with the given URI or the mode is invalid.
1581 * @throws SecurityException Throws SecurityException if the caller does
1582 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001583 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 * @see #openAssetFile(Uri, String)
1585 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001586 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001587 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001588 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001589 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 throws FileNotFoundException {
1591 throw new FileNotFoundException("No files supported by provider at "
1592 + uri);
1593 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001596 * Override this to handle requests to open a file blob.
1597 * The default implementation always throws {@link FileNotFoundException}.
1598 * This method can be called from multiple threads, as described in
1599 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1600 * and Threads</a>.
1601 *
1602 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1603 * to the caller. This way large data (such as images and documents) can be
1604 * returned without copying the content.
1605 *
1606 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1607 * their responsibility to close it when done. That is, the implementation
1608 * of this method should create a new ParcelFileDescriptor for each call.
1609 * <p>
1610 * If opened with the exclusive "r" or "w" modes, the returned
1611 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1612 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1613 * supports seeking.
1614 * <p>
1615 * If you need to detect when the returned ParcelFileDescriptor has been
1616 * closed, or if the remote process has crashed or encountered some other
1617 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1618 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1619 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1620 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1621 *
1622 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1623 * to return the appropriate MIME type for the data returned here with
1624 * the same URI. This will allow intent resolution to automatically determine the data MIME
1625 * type and select the appropriate matching targets as part of its operation.</p>
1626 *
1627 * <p class="note">For better interoperability with other applications, it is recommended
1628 * that for any URIs that can be opened, you also support queries on them
1629 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1630 * You may also want to support other common columns if you have additional meta-data
1631 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1632 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1633 *
1634 * @param uri The URI whose file is to be opened.
1635 * @param mode Access mode for the file. May be "r" for read-only access,
1636 * "w" for write-only access, "rw" for read and write access, or
1637 * "rwt" for read and write access that truncates any existing
1638 * file.
1639 * @param signal A signal to cancel the operation in progress, or
1640 * {@code null} if none. For example, if you are downloading a
1641 * file from the network to service a "rw" mode request, you
1642 * should periodically call
1643 * {@link CancellationSignal#throwIfCanceled()} to check whether
1644 * the client has canceled the request and abort the download.
1645 *
1646 * @return Returns a new ParcelFileDescriptor which you can use to access
1647 * the file.
1648 *
1649 * @throws FileNotFoundException Throws FileNotFoundException if there is
1650 * no file associated with the given URI or the mode is invalid.
1651 * @throws SecurityException Throws SecurityException if the caller does
1652 * not have permission to access the file.
1653 *
1654 * @see #openAssetFile(Uri, String)
1655 * @see #openFileHelper(Uri, String)
1656 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001657 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001658 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001659 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001660 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1661 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001662 return openFile(uri, mode);
1663 }
1664
1665 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 * This is like {@link #openFile}, but can be implemented by providers
1667 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001668 * inside of their .apk.
1669 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001670 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1671 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001672 *
1673 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001674 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001675 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1677 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1678 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001679 * <p>
1680 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1681 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001682 *
1683 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 * should create the AssetFileDescriptor with
1685 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001686 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001688 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1689 * to return the appropriate MIME type for the data returned here with
1690 * the same URI. This will allow intent resolution to automatically determine the data MIME
1691 * type and select the appropriate matching targets as part of its operation.</p>
1692 *
1693 * <p class="note">For better interoperability with other applications, it is recommended
1694 * that for any URIs that can be opened, you also support queries on them
1695 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1696 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 * @param uri The URI whose file is to be opened.
1698 * @param mode Access mode for the file. May be "r" for read-only access,
1699 * "w" for write-only access (erasing whatever data is currently in
1700 * the file), "wa" for write-only access to append to any existing data,
1701 * "rw" for read and write access on any existing data, and "rwt" for read
1702 * and write access that truncates any existing file.
1703 *
1704 * @return Returns a new AssetFileDescriptor which you can use to access
1705 * the file.
1706 *
1707 * @throws FileNotFoundException Throws FileNotFoundException if there is
1708 * no file associated with the given URI or the mode is invalid.
1709 * @throws SecurityException Throws SecurityException if the caller does
1710 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001711 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 * @see #openFile(Uri, String)
1713 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001714 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001716 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 throws FileNotFoundException {
1718 ParcelFileDescriptor fd = openFile(uri, mode);
1719 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1720 }
1721
1722 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001723 * This is like {@link #openFile}, but can be implemented by providers
1724 * that need to be able to return sub-sections of files, often assets
1725 * inside of their .apk.
1726 * This method can be called from multiple threads, as described in
1727 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1728 * and Threads</a>.
1729 *
1730 * <p>If you implement this, your clients must be able to deal with such
1731 * file slices, either directly with
1732 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1733 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1734 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1735 * methods.
1736 * <p>
1737 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1738 * streaming of data.
1739 *
1740 * <p class="note">If you are implementing this to return a full file, you
1741 * should create the AssetFileDescriptor with
1742 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1743 * applications that cannot handle sub-sections of files.</p>
1744 *
1745 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1746 * to return the appropriate MIME type for the data returned here with
1747 * the same URI. This will allow intent resolution to automatically determine the data MIME
1748 * type and select the appropriate matching targets as part of its operation.</p>
1749 *
1750 * <p class="note">For better interoperability with other applications, it is recommended
1751 * that for any URIs that can be opened, you also support queries on them
1752 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1753 *
1754 * @param uri The URI whose file is to be opened.
1755 * @param mode Access mode for the file. May be "r" for read-only access,
1756 * "w" for write-only access (erasing whatever data is currently in
1757 * the file), "wa" for write-only access to append to any existing data,
1758 * "rw" for read and write access on any existing data, and "rwt" for read
1759 * and write access that truncates any existing file.
1760 * @param signal A signal to cancel the operation in progress, or
1761 * {@code null} if none. For example, if you are downloading a
1762 * file from the network to service a "rw" mode request, you
1763 * should periodically call
1764 * {@link CancellationSignal#throwIfCanceled()} to check whether
1765 * the client has canceled the request and abort the download.
1766 *
1767 * @return Returns a new AssetFileDescriptor which you can use to access
1768 * the file.
1769 *
1770 * @throws FileNotFoundException Throws FileNotFoundException if there is
1771 * no file associated with the given URI or the mode is invalid.
1772 * @throws SecurityException Throws SecurityException if the caller does
1773 * not have permission to access the file.
1774 *
1775 * @see #openFile(Uri, String)
1776 * @see #openFileHelper(Uri, String)
1777 * @see #getType(android.net.Uri)
1778 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001779 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001780 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1781 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001782 return openAssetFile(uri, mode);
1783 }
1784
1785 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 * Convenience for subclasses that wish to implement {@link #openFile}
1787 * by looking up a column named "_data" at the given URI.
1788 *
1789 * @param uri The URI to be opened.
1790 * @param mode The file mode. May be "r" for read-only access,
1791 * "w" for write-only access (erasing whatever data is currently in
1792 * the file), "wa" for write-only access to append to any existing data,
1793 * "rw" for read and write access on any existing data, and "rwt" for read
1794 * and write access that truncates any existing file.
1795 *
1796 * @return Returns a new ParcelFileDescriptor that can be used by the
1797 * client to access the file.
1798 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001799 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1800 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1802 int count = (c != null) ? c.getCount() : 0;
1803 if (count != 1) {
1804 // If there is not exactly one result, throw an appropriate
1805 // exception.
1806 if (c != null) {
1807 c.close();
1808 }
1809 if (count == 0) {
1810 throw new FileNotFoundException("No entry for " + uri);
1811 }
1812 throw new FileNotFoundException("Multiple items at " + uri);
1813 }
1814
1815 c.moveToFirst();
1816 int i = c.getColumnIndex("_data");
1817 String path = (i >= 0 ? c.getString(i) : null);
1818 c.close();
1819 if (path == null) {
1820 throw new FileNotFoundException("Column _data not found.");
1821 }
1822
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001823 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 return ParcelFileDescriptor.open(new File(path), modeBits);
1825 }
1826
1827 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001828 * Called by a client to determine the types of data streams that this
1829 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001830 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001831 * of a particular type, return that MIME type if it matches the given
1832 * mimeTypeFilter. If it can perform type conversions, return an array
1833 * of all supported MIME types that match mimeTypeFilter.
1834 *
1835 * @param uri The data in the content provider being queried.
1836 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001837 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001838 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001839 * given mimeTypeFilter. Otherwise returns an array of all available
1840 * concrete MIME types.
1841 *
1842 * @see #getType(Uri)
1843 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001844 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001845 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001846 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001847 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001848 return null;
1849 }
1850
1851 /**
1852 * Called by a client to open a read-only stream containing data of a
1853 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1854 * except the file can only be read-only and the content provider may
1855 * perform data conversions to generate data of the desired type.
1856 *
1857 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001858 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001859 * {@link #openAssetFile(Uri, String)}.
1860 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001861 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001862 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001863 * <p>
1864 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1865 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001866 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001867 * <p class="note">For better interoperability with other applications, it is recommended
1868 * that for any URIs that can be opened, you also support queries on them
1869 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1870 * You may also want to support other common columns if you have additional meta-data
1871 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1872 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1873 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001874 * @param uri The data in the content provider being queried.
1875 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001876 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001877 * requirements; in this case the content provider will pick its best
1878 * type matching the pattern.
1879 * @param opts Additional options from the client. The definitions of
1880 * these are specific to the content provider being called.
1881 *
1882 * @return Returns a new AssetFileDescriptor from which the client can
1883 * read data of the desired type.
1884 *
1885 * @throws FileNotFoundException Throws FileNotFoundException if there is
1886 * no file associated with the given URI or the mode is invalid.
1887 * @throws SecurityException Throws SecurityException if the caller does
1888 * not have permission to access the data.
1889 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1890 * content provider does not support the requested MIME type.
1891 *
1892 * @see #getStreamTypes(Uri, String)
1893 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001894 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001895 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001896 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1897 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001898 if ("*/*".equals(mimeTypeFilter)) {
1899 // If they can take anything, the untyped open call is good enough.
1900 return openAssetFile(uri, "r");
1901 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001902 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001903 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001904 // Use old untyped open call if this provider has a type for this
1905 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001906 return openAssetFile(uri, "r");
1907 }
1908 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1909 }
1910
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001911
1912 /**
1913 * Called by a client to open a read-only stream containing data of a
1914 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1915 * except the file can only be read-only and the content provider may
1916 * perform data conversions to generate data of the desired type.
1917 *
1918 * <p>The default implementation compares the given mimeType against the
1919 * result of {@link #getType(Uri)} and, if they match, simply calls
1920 * {@link #openAssetFile(Uri, String)}.
1921 *
1922 * <p>See {@link ClipData} for examples of the use and implementation
1923 * of this method.
1924 * <p>
1925 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1926 * streaming of data.
1927 *
1928 * <p class="note">For better interoperability with other applications, it is recommended
1929 * that for any URIs that can be opened, you also support queries on them
1930 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1931 * You may also want to support other common columns if you have additional meta-data
1932 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1933 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1934 *
1935 * @param uri The data in the content provider being queried.
1936 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001937 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001938 * requirements; in this case the content provider will pick its best
1939 * type matching the pattern.
1940 * @param opts Additional options from the client. The definitions of
1941 * these are specific to the content provider being called.
1942 * @param signal A signal to cancel the operation in progress, or
1943 * {@code null} if none. For example, if you are downloading a
1944 * file from the network to service a "rw" mode request, you
1945 * should periodically call
1946 * {@link CancellationSignal#throwIfCanceled()} to check whether
1947 * the client has canceled the request and abort the download.
1948 *
1949 * @return Returns a new AssetFileDescriptor from which the client can
1950 * read data of the desired type.
1951 *
1952 * @throws FileNotFoundException Throws FileNotFoundException if there is
1953 * no file associated with the given URI or the mode is invalid.
1954 * @throws SecurityException Throws SecurityException if the caller does
1955 * not have permission to access the data.
1956 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1957 * content provider does not support the requested MIME type.
1958 *
1959 * @see #getStreamTypes(Uri, String)
1960 * @see #openAssetFile(Uri, String)
1961 * @see ClipDescription#compareMimeTypes(String, String)
1962 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001963 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001964 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1965 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1966 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001967 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1968 }
1969
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001970 /**
1971 * Interface to write a stream of data to a pipe. Use with
1972 * {@link ContentProvider#openPipeHelper}.
1973 */
1974 public interface PipeDataWriter<T> {
1975 /**
1976 * Called from a background thread to stream data out to a pipe.
1977 * Note that the pipe is blocking, so this thread can block on
1978 * writes for an arbitrary amount of time if the client is slow
1979 * at reading.
1980 *
1981 * @param output The pipe where data should be written. This will be
1982 * closed for you upon returning from this function.
1983 * @param uri The URI whose data is to be written.
1984 * @param mimeType The desired type of data to be written.
1985 * @param opts Options supplied by caller.
1986 * @param args Your own custom arguments.
1987 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001988 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1989 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001990 }
1991
1992 /**
1993 * A helper function for implementing {@link #openTypedAssetFile}, for
1994 * creating a data pipe and background thread allowing you to stream
1995 * generated data back to the client. This function returns a new
1996 * ParcelFileDescriptor that should be returned to the caller (the caller
1997 * is responsible for closing it).
1998 *
1999 * @param uri The URI whose data is to be written.
2000 * @param mimeType The desired type of data to be written.
2001 * @param opts Options supplied by caller.
2002 * @param args Your own custom arguments.
2003 * @param func Interface implementing the function that will actually
2004 * stream the data.
2005 * @return Returns a new ParcelFileDescriptor holding the read side of
2006 * the pipe. This should be returned to the caller for reading; the caller
2007 * is responsible for closing it when done.
2008 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002009 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
2010 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
2011 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002012 try {
2013 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
2014
2015 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
2016 @Override
2017 protected Object doInBackground(Object... params) {
2018 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
2019 try {
2020 fds[1].close();
2021 } catch (IOException e) {
2022 Log.w(TAG, "Failure closing pipe", e);
2023 }
2024 return null;
2025 }
2026 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002027 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002028
2029 return fds[0];
2030 } catch (IOException e) {
2031 throw new FileNotFoundException("failure making pipe");
2032 }
2033 }
2034
2035 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 * Returns true if this instance is a temporary content provider.
2037 * @return true if this instance is a temporary content provider
2038 */
2039 protected boolean isTemporary() {
2040 return false;
2041 }
2042
2043 /**
2044 * Returns the Binder object for this provider.
2045 *
2046 * @return the Binder object for this provider
2047 * @hide
2048 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002049 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 public IContentProvider getIContentProvider() {
2051 return mTransport;
2052 }
2053
2054 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002055 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
2056 * when directly instantiating the provider for testing.
2057 * @hide
2058 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002059 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002060 public void attachInfoForTesting(Context context, ProviderInfo info) {
2061 attachInfo(context, info, true);
2062 }
2063
2064 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 * After being instantiated, this is called to tell the content provider
2066 * about itself.
2067 *
2068 * @param context The context this provider is running in
2069 * @param info Registered information about this content provider
2070 */
2071 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002072 attachInfo(context, info, false);
2073 }
2074
2075 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002076 mNoPerms = testing;
Jeff Sharkey497789e2019-02-15 19:41:30 -07002077 mCallingPackage = new ThreadLocal<>();
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 /*
2080 * Only allow it to be set once, so after the content service gives
2081 * this to us clients can't change it.
2082 */
2083 if (mContext == null) {
2084 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002085 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07002086 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
2087 Context.APP_OPS_SERVICE);
2088 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002089 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 if (info != null) {
2091 setReadPermission(info.readPermission);
2092 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002093 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07002094 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07002095 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002096 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 }
2098 ContentProvider.this.onCreate();
2099 }
2100 }
Fred Quintanace31b232009-05-04 16:01:15 -07002101
2102 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07002103 * Override this to handle requests to perform a batch of operations, or the
2104 * default implementation will iterate over the operations and call
2105 * {@link ContentProviderOperation#apply} on each of them.
2106 * If all calls to {@link ContentProviderOperation#apply} succeed
2107 * then a {@link ContentProviderResult} array with as many
2108 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002109 * fail, it is up to the implementation how many of the others take effect.
2110 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08002111 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2112 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002113 *
Fred Quintanace31b232009-05-04 16:01:15 -07002114 * @param operations the operations to apply
2115 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002116 * @throws OperationApplicationException thrown if any operation fails.
2117 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002118 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002119 @Override
2120 public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
2121 @NonNull ArrayList<ContentProviderOperation> operations)
2122 throws OperationApplicationException {
2123 return applyBatch(operations);
2124 }
2125
Jeff Sharkey673db442015-06-11 19:30:57 -07002126 public @NonNull ContentProviderResult[] applyBatch(
2127 @NonNull ArrayList<ContentProviderOperation> operations)
2128 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002129 final int numOperations = operations.size();
2130 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2131 for (int i = 0; i < numOperations; i++) {
2132 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002133 }
2134 return results;
2135 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002136
2137 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002138 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002139 * interfaces that are cheaper and/or unnatural for a table-like
2140 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002141 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002142 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2143 * on this entry into the content provider besides the basic ability for the application
2144 * to get access to the provider at all. For example, it has no idea whether the call
2145 * being executed may read or write data in the provider, so can't enforce those
2146 * individual permissions. Any implementation of this method <strong>must</strong>
2147 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2148 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002149 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2150 * @param arg provider-defined String argument. May be {@code null}.
2151 * @param extras provider-defined Bundle argument. May be {@code null}.
2152 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002153 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002154 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002155 @Override
2156 public @Nullable Bundle call(@NonNull String authority, @NonNull String method,
2157 @Nullable String arg, @Nullable Bundle extras) {
2158 return call(method, arg, extras);
2159 }
2160
Jeff Sharkey673db442015-06-11 19:30:57 -07002161 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2162 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002163 return null;
2164 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002165
2166 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002167 * Implement this to shut down the ContentProvider instance. You can then
2168 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002169 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002170 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002171 * Android normally handles ContentProvider startup and shutdown
2172 * automatically. You do not need to start up or shut down a
2173 * ContentProvider. When you invoke a test method on a ContentProvider,
2174 * however, a ContentProvider instance is started and keeps running after
2175 * the test finishes, even if a succeeding test instantiates another
2176 * ContentProvider. A conflict develops because the two instances are
2177 * usually running against the same underlying data source (for example, an
2178 * sqlite database).
2179 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002180 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002181 * Implementing shutDown() avoids this conflict by providing a way to
2182 * terminate the ContentProvider. This method can also prevent memory leaks
2183 * from multiple instantiations of the ContentProvider, and it can ensure
2184 * unit test isolation by allowing you to completely clean up the test
2185 * fixture before moving on to the next test.
2186 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002187 */
2188 public void shutdown() {
2189 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2190 "connections are gracefully shutdown");
2191 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002192
2193 /**
2194 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002195 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002196 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002197 * @param fd The raw file descriptor that the dump is being sent to.
2198 * @param writer The PrintWriter to which you should dump your state. This will be
2199 * closed for you after you return.
2200 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002201 */
2202 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2203 writer.println("nothing to dump");
2204 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002205
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002206 private void validateIncomingAuthority(String authority) throws SecurityException {
2207 if (!matchesOurAuthorities(getAuthorityWithoutUserId(authority))) {
2208 String message = "The authority " + authority + " does not match the one of the "
2209 + "contentProvider: ";
2210 if (mAuthority != null) {
2211 message += mAuthority;
2212 } else {
2213 message += Arrays.toString(mAuthorities);
2214 }
2215 throw new SecurityException(message);
2216 }
2217 }
2218
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002219 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002220 @VisibleForTesting
2221 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002222 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002223 if (!mSingleUser) {
2224 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2225 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2226 throw new SecurityException("trying to query a ContentProvider in user "
2227 + mContext.getUserId() + " with a uri belonging to user " + userId);
2228 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002229 }
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002230 validateIncomingAuthority(auth);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002231
2232 // Normalize the path by removing any empty path segments, which can be
2233 // a source of security issues.
2234 final String encodedPath = uri.getEncodedPath();
2235 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
Jeff Sharkey4a7b6ac2018-10-03 10:33:46 -06002236 final Uri normalized = uri.buildUpon()
2237 .encodedPath(encodedPath.replaceAll("//+", "/")).build();
2238 Log.w(TAG, "Normalized " + uri + " to " + normalized
2239 + " to avoid possible security issues");
2240 return normalized;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002241 } else {
2242 return uri;
2243 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002244 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002245
2246 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002247 private Uri maybeGetUriWithoutUserId(Uri uri) {
2248 if (mSingleUser) {
2249 return uri;
2250 }
2251 return getUriWithoutUserId(uri);
2252 }
2253
2254 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002255 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2256 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002257 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002258 if (end == -1) return defaultUserId;
2259 String userIdString = auth.substring(0, end);
2260 try {
2261 return Integer.parseInt(userIdString);
2262 } catch (NumberFormatException e) {
2263 Log.w(TAG, "Error parsing userId.", e);
2264 return UserHandle.USER_NULL;
2265 }
2266 }
2267
2268 /** @hide */
2269 public static int getUserIdFromAuthority(String auth) {
2270 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2271 }
2272
2273 /** @hide */
2274 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2275 if (uri == null) return defaultUserId;
2276 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2277 }
2278
2279 /** @hide */
2280 public static int getUserIdFromUri(Uri uri) {
2281 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2282 }
2283
2284 /**
2285 * Removes userId part from authority string. Expects format:
2286 * userId@some.authority
2287 * If there is no userId in the authority, it symply returns the argument
2288 * @hide
2289 */
2290 public static String getAuthorityWithoutUserId(String auth) {
2291 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002292 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002293 return auth.substring(end+1);
2294 }
2295
2296 /** @hide */
2297 public static Uri getUriWithoutUserId(Uri uri) {
2298 if (uri == null) return null;
2299 Uri.Builder builder = uri.buildUpon();
2300 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2301 return builder.build();
2302 }
2303
2304 /** @hide */
2305 public static boolean uriHasUserId(Uri uri) {
2306 if (uri == null) return false;
2307 return !TextUtils.isEmpty(uri.getUserInfo());
2308 }
2309
2310 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002311 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002312 public static Uri maybeAddUserId(Uri uri, int userId) {
2313 if (uri == null) return null;
2314 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002315 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002316 if (!uriHasUserId(uri)) {
2317 //We don't add the user Id if there's already one
2318 Uri.Builder builder = uri.buildUpon();
2319 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2320 return builder.build();
2321 }
2322 }
2323 return uri;
2324 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002325}