blob: 7de87938c1f64921db98b4cf5c8be2e2fc27fa89 [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;
Varun Shahaf8cfe32019-08-16 16:11:24 -070020import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070021import static android.app.AppOpsManager.MODE_ALLOWED;
Eugene Susla93519852018-06-13 16:44:31 -070022import static android.app.AppOpsManager.MODE_DEFAULT;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070023import static android.app.AppOpsManager.MODE_ERRORED;
24import static android.app.AppOpsManager.MODE_IGNORED;
25import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060026import static android.os.Trace.TRACE_TAG_DATABASE;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070027
Jeff Sharkey673db442015-06-11 19:30:57 -070028import android.annotation.NonNull;
Scott Kennedy9f78f652015-03-01 15:29:25 -080029import android.annotation.Nullable;
Mathew Inwood5c0d3542018-08-14 13:54:31 +010030import android.annotation.UnsupportedAppUsage;
Dianne Hackborn35654b62013-01-14 17:38:02 -080031import android.app.AppOpsManager;
Jeff Sharkey9edef252019-05-20 14:00:17 -060032import android.content.pm.PackageManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070033import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.pm.ProviderInfo;
35import android.content.res.AssetFileDescriptor;
36import android.content.res.Configuration;
37import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070038import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.database.SQLException;
40import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070041import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.Binder;
Mathew Inwood8c854f82018-09-14 12:35:36 +010043import android.os.Build;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080044import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070045import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080046import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070047import android.os.ICancellationSignal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070049import android.os.Process;
Ben Lin1cf454f2016-11-10 13:50:54 -080050import android.os.RemoteException;
Jeff Sharkey9664ff52018-08-03 17:08:04 -060051import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070052import android.os.UserHandle;
Jeff Sharkeyb31afd22017-06-12 14:17:10 -060053import android.os.storage.StorageManager;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010054import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070055import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060057import com.android.internal.annotations.VisibleForTesting;
58
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080060import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070062import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080063import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070064import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080065import java.util.Arrays;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -060066import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067
68/**
69 * Content providers are one of the primary building blocks of Android applications, providing
70 * content to applications. They encapsulate data and provide it to applications through the single
71 * {@link ContentResolver} interface. A content provider is only required if you need to share
72 * data between multiple applications. For example, the contacts data is used by multiple
73 * applications and must be stored in a content provider. If you don't need to share data amongst
74 * multiple applications you can use a database directly via
75 * {@link android.database.sqlite.SQLiteDatabase}.
76 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 * <p>When a request is made via
78 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
79 * request to the content provider registered with the authority. The content provider can interpret
80 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
81 * URIs.</p>
82 *
83 * <p>The primary methods that need to be implemented are:
84 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070085 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 * <li>{@link #query} which returns data to the caller</li>
87 * <li>{@link #insert} which inserts new data into the content provider</li>
88 * <li>{@link #update} which updates existing data in the content provider</li>
89 * <li>{@link #delete} which deletes data from the content provider</li>
90 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
91 * </ul></p>
92 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070093 * <p class="caution">Data access methods (such as {@link #insert} and
94 * {@link #update}) may be called from many threads at once, and must be thread-safe.
95 * Other methods (such as {@link #onCreate}) are only called from the application
96 * main thread, and must avoid performing lengthy operations. See the method
97 * descriptions for their expected thread behavior.</p>
98 *
99 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
100 * ContentProvider instance, so subclasses don't have to worry about the details of
101 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -0700102 *
103 * <div class="special reference">
104 * <h3>Developer Guides</h3>
105 * <p>For more information about using content providers, read the
106 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
107 * developer guide.</p>
Nicole Borrelli8a5f04a2018-09-20 14:19:14 -0700108 * </div>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700110public abstract class ContentProvider implements ContentInterface, ComponentCallbacks2 {
Steve McKayea93fe72016-12-02 11:35:35 -0800111
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700112 private static final String TAG = "ContentProvider";
113
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900114 /*
115 * Note: if you add methods to ContentProvider, you must add similar methods to
116 * MockContentProvider.
117 */
118
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100119 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700121 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100122
123 // Since most Providers have only one authority, we keep both a String and a String[] to improve
124 // performance.
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100125 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100126 private String mAuthority;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100127 @UnsupportedAppUsage
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100128 private String[] mAuthorities;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100129 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 private String mReadPermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100131 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 private String mWritePermission;
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100133 @UnsupportedAppUsage
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700134 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700135 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800136 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700137 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138
Jeff Sharkey497789e2019-02-15 19:41:30 -0700139 private ThreadLocal<String> mCallingPackage;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 private Transport mTransport = new Transport();
142
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700143 /**
144 * Construct a ContentProvider instance. Content providers must be
145 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
146 * in the manifest</a>, accessed with {@link ContentResolver}, and created
147 * automatically by the system, so applications usually do not create
148 * ContentProvider instances directly.
149 *
150 * <p>At construction time, the object is uninitialized, and most fields and
151 * methods are unavailable. Subclasses should initialize themselves in
152 * {@link #onCreate}, not the constructor.
153 *
154 * <p>Content providers are created on the application main thread at
155 * application launch time. The constructor must not perform lengthy
156 * operations, or application startup will be delayed.
157 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900158 public ContentProvider() {
159 }
160
161 /**
162 * Constructor just for mocking.
163 *
164 * @param context A Context object which should be some mock instance (like the
165 * instance of {@link android.test.mock.MockContext}).
166 * @param readPermission The read permision you want this instance should have in the
167 * test, which is available via {@link #getReadPermission()}.
168 * @param writePermission The write permission you want this instance should have
169 * in the test, which is available via {@link #getWritePermission()}.
170 * @param pathPermissions The PathPermissions you want this instance should have
171 * in the test, which is available via {@link #getPathPermissions()}.
172 * @hide
173 */
Mathew Inwood8c854f82018-09-14 12:35:36 +0100174 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900175 public ContentProvider(
176 Context context,
177 String readPermission,
178 String writePermission,
179 PathPermission[] pathPermissions) {
180 mContext = context;
181 mReadPermission = readPermission;
182 mWritePermission = writePermission;
183 mPathPermissions = pathPermissions;
184 }
185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 /**
187 * Given an IContentProvider, try to coerce it back to the real
188 * ContentProvider object if it is running in the local process. This can
189 * be used if you know you are running in the same process as a provider,
190 * and want to get direct access to its implementation details. Most
191 * clients should not nor have a reason to use it.
192 *
193 * @param abstractInterface The ContentProvider interface that is to be
194 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800195 * @return If the IContentProvider is non-{@code null} and local, returns its actual
196 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 * @hide
198 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +0100199 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 public static ContentProvider coerceToLocalContentProvider(
201 IContentProvider abstractInterface) {
202 if (abstractInterface instanceof Transport) {
203 return ((Transport)abstractInterface).getContentProvider();
204 }
205 return null;
206 }
207
208 /**
209 * Binder object that deals with remoting.
210 *
211 * @hide
212 */
213 class Transport extends ContentProviderNative {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700214 volatile AppOpsManager mAppOpsManager = null;
215 volatile int mReadOp = AppOpsManager.OP_NONE;
216 volatile int mWriteOp = AppOpsManager.OP_NONE;
217 volatile ContentInterface mInterface = ContentProvider.this;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 ContentProvider getContentProvider() {
220 return ContentProvider.this;
221 }
222
Jeff Brownd2183652011-10-09 12:39:53 -0700223 @Override
224 public String getProviderName() {
225 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226 }
227
Jeff Brown75ea64f2012-01-25 19:37:13 -0800228 @Override
Steve McKayea93fe72016-12-02 11:35:35 -0800229 public Cursor query(String callingPkg, Uri uri, @Nullable String[] projection,
230 @Nullable Bundle queryArgs, @Nullable ICancellationSignal cancellationSignal) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600231 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100232 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800233 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700234 // The caller has no access to the data, so return an empty cursor with
235 // the columns in the requested order. The caller may ask for an invalid
236 // column and we would not catch that but this is not a problem in practice.
237 // We do not call ContentProvider#query with a modified where clause since
238 // the implementation is not guaranteed to be backed by a SQL database, hence
239 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700240 if (projection != null) {
241 return new MatrixCursor(projection, 0);
242 }
243
244 // Null projection means all columns but we have no idea which they are.
245 // However, the caller may be expecting to access them my index. Hence,
246 // we have to execute the query as if allowed to get a cursor with the
247 // columns. We then use the column names to return an empty cursor.
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700248 Cursor cursor;
249 final String original = setCallingPackage(callingPkg);
250 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700251 cursor = mInterface.query(
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700252 uri, projection, queryArgs,
253 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700254 } catch (RemoteException e) {
255 throw e.rethrowAsRuntimeException();
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700256 } finally {
257 setCallingPackage(original);
258 }
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700259 if (cursor == null) {
260 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700261 }
262
263 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700264 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800265 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600266 Trace.traceBegin(TRACE_TAG_DATABASE, "query");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700267 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700268 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700269 return mInterface.query(
Steve McKayea93fe72016-12-02 11:35:35 -0800270 uri, projection, queryArgs,
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700271 CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700272 } catch (RemoteException e) {
273 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700274 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700275 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600276 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 }
279
Jeff Brown75ea64f2012-01-25 19:37:13 -0800280 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281 public String getType(Uri uri) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700282 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600283 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100284 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600285 Trace.traceBegin(TRACE_TAG_DATABASE, "getType");
286 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700287 return mInterface.getType(uri);
288 } catch (RemoteException e) {
289 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600290 } finally {
291 Trace.traceEnd(TRACE_TAG_DATABASE);
292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 }
294
Jeff Brown75ea64f2012-01-25 19:37:13 -0800295 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800296 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600297 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100298 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100299 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800300 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700301 final String original = setCallingPackage(callingPkg);
302 try {
303 return rejectInsert(uri, initialValues);
304 } finally {
305 setCallingPackage(original);
306 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800307 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600308 Trace.traceBegin(TRACE_TAG_DATABASE, "insert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700309 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700310 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700311 return maybeAddUserId(mInterface.insert(uri, initialValues), userId);
312 } catch (RemoteException e) {
313 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700314 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700315 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600316 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 }
319
Jeff Brown75ea64f2012-01-25 19:37:13 -0800320 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800321 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600322 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100323 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800324 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800325 return 0;
326 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600327 Trace.traceBegin(TRACE_TAG_DATABASE, "bulkInsert");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700328 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700329 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700330 return mInterface.bulkInsert(uri, initialValues);
331 } catch (RemoteException e) {
332 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700333 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700334 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600335 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 }
338
Jeff Brown75ea64f2012-01-25 19:37:13 -0800339 @Override
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700340 public ContentProviderResult[] applyBatch(String callingPkg, String authority,
Dianne Hackborn35654b62013-01-14 17:38:02 -0800341 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700342 throws OperationApplicationException {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700343 validateIncomingAuthority(authority);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100344 int numOperations = operations.size();
345 final int[] userIds = new int[numOperations];
346 for (int i = 0; i < numOperations; i++) {
347 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100348 Uri uri = operation.getUri();
Jeff Sharkey9144b4d2018-09-26 20:15:12 -0600349 userIds[i] = getUserIdFromUri(uri);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600350 uri = validateIncomingUri(uri);
351 uri = maybeGetUriWithoutUserId(uri);
352 // Rebuild operation if we changed the Uri above
353 if (!Objects.equals(operation.getUri(), uri)) {
354 operation = new ContentProviderOperation(operation, uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100355 operations.set(i, operation);
356 }
Fred Quintana89437372009-05-15 15:10:40 -0700357 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800358 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800359 != AppOpsManager.MODE_ALLOWED) {
360 throw new OperationApplicationException("App op not allowed", 0);
361 }
Fred Quintana89437372009-05-15 15:10:40 -0700362 }
Fred Quintana89437372009-05-15 15:10:40 -0700363 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800364 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800365 != AppOpsManager.MODE_ALLOWED) {
366 throw new OperationApplicationException("App op not allowed", 0);
367 }
Fred Quintana89437372009-05-15 15:10:40 -0700368 }
369 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600370 Trace.traceBegin(TRACE_TAG_DATABASE, "applyBatch");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700371 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700372 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700373 ContentProviderResult[] results = mInterface.applyBatch(authority,
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700374 operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800375 if (results != null) {
376 for (int i = 0; i < results.length ; i++) {
377 if (userIds[i] != UserHandle.USER_CURRENT) {
378 // Adding the userId to the uri.
379 results[i] = new ContentProviderResult(results[i], userIds[i]);
380 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100381 }
382 }
383 return results;
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700384 } catch (RemoteException e) {
385 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700386 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700387 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600388 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700389 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700390 }
391
Jeff Brown75ea64f2012-01-25 19:37:13 -0800392 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800393 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600394 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100395 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800396 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800397 return 0;
398 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600399 Trace.traceBegin(TRACE_TAG_DATABASE, "delete");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700400 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700401 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700402 return mInterface.delete(uri, selection, selectionArgs);
403 } catch (RemoteException e) {
404 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700405 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700406 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600407 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409 }
410
Jeff Brown75ea64f2012-01-25 19:37:13 -0800411 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800412 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 String[] selectionArgs) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600414 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100415 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800416 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800417 return 0;
418 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600419 Trace.traceBegin(TRACE_TAG_DATABASE, "update");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700420 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700421 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700422 return mInterface.update(uri, values, selection, selectionArgs);
423 } catch (RemoteException e) {
424 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700425 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700426 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600427 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 }
430
Jeff Brown75ea64f2012-01-25 19:37:13 -0800431 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700432 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800433 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
434 IBinder callerToken) throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600435 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100436 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800437 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600438 Trace.traceBegin(TRACE_TAG_DATABASE, "openFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700439 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700440 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700441 return mInterface.openFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700442 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700443 } catch (RemoteException e) {
444 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700445 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700446 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600447 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 }
450
Jeff Brown75ea64f2012-01-25 19:37:13 -0800451 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700452 public AssetFileDescriptor openAssetFile(
453 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 throws FileNotFoundException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600455 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100456 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800457 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600458 Trace.traceBegin(TRACE_TAG_DATABASE, "openAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700459 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700460 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700461 return mInterface.openAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700462 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700463 } catch (RemoteException e) {
464 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700465 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700466 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600467 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 }
470
Jeff Brown75ea64f2012-01-25 19:37:13 -0800471 @Override
Jeff Sharkey633a13e2018-12-07 12:00:45 -0700472 public Bundle call(String callingPkg, String authority, String method, @Nullable String arg,
473 @Nullable Bundle extras) {
Jeff Sharkey2de00bf2018-12-13 15:06:05 -0700474 validateIncomingAuthority(authority);
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600475 Bundle.setDefusable(extras, true);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600476 Trace.traceBegin(TRACE_TAG_DATABASE, "call");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700477 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700478 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700479 return mInterface.call(authority, method, arg, extras);
480 } catch (RemoteException e) {
481 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700482 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700483 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600484 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700485 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800486 }
487
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700488 @Override
489 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Makoto Onuki2cc250b2018-08-28 15:40:10 -0700490 // getCallingPackage() isn't available in getType(), as the javadoc states.
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600491 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100492 uri = maybeGetUriWithoutUserId(uri);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600493 Trace.traceBegin(TRACE_TAG_DATABASE, "getStreamTypes");
494 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700495 return mInterface.getStreamTypes(uri, mimeTypeFilter);
496 } catch (RemoteException e) {
497 throw e.rethrowAsRuntimeException();
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600498 } finally {
499 Trace.traceEnd(TRACE_TAG_DATABASE);
500 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700501 }
502
503 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800504 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700505 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600506 Bundle.setDefusable(opts, true);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600507 uri = validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100508 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800509 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600510 Trace.traceBegin(TRACE_TAG_DATABASE, "openTypedAssetFile");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700511 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700512 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700513 return mInterface.openTypedAssetFile(
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700514 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700515 } catch (RemoteException e) {
516 throw e.rethrowAsRuntimeException();
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700517 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700518 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600519 Trace.traceEnd(TRACE_TAG_DATABASE);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700520 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700521 }
522
Jeff Brown75ea64f2012-01-25 19:37:13 -0800523 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700524 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800525 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800526 }
527
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700528 @Override
529 public Uri canonicalize(String callingPkg, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600530 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100531 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100532 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800533 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700534 return null;
535 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600536 Trace.traceBegin(TRACE_TAG_DATABASE, "canonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700537 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700538 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700539 return maybeAddUserId(mInterface.canonicalize(uri), userId);
540 } catch (RemoteException e) {
541 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700542 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700543 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600544 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700545 }
546 }
547
548 @Override
549 public Uri uncanonicalize(String callingPkg, Uri uri) {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600550 uri = validateIncomingUri(uri);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100551 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100552 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800553 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700554 return null;
555 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600556 Trace.traceBegin(TRACE_TAG_DATABASE, "uncanonicalize");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700557 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700558 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700559 return maybeAddUserId(mInterface.uncanonicalize(uri), userId);
560 } catch (RemoteException e) {
561 throw e.rethrowAsRuntimeException();
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700562 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700563 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600564 Trace.traceEnd(TRACE_TAG_DATABASE);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700565 }
566 }
567
Ben Lin1cf454f2016-11-10 13:50:54 -0800568 @Override
569 public boolean refresh(String callingPkg, Uri uri, Bundle args,
570 ICancellationSignal cancellationSignal) throws RemoteException {
Jeff Sharkeyc4156e02018-09-24 13:23:57 -0600571 uri = validateIncomingUri(uri);
Ben Lin1cf454f2016-11-10 13:50:54 -0800572 uri = getUriWithoutUserId(uri);
573 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
574 return false;
575 }
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600576 Trace.traceBegin(TRACE_TAG_DATABASE, "refresh");
Ben Lin1cf454f2016-11-10 13:50:54 -0800577 final String original = setCallingPackage(callingPkg);
578 try {
Jeff Sharkeybffd2502019-02-28 16:39:12 -0700579 return mInterface.refresh(uri, args,
Ben Lin1cf454f2016-11-10 13:50:54 -0800580 CancellationSignal.fromTransport(cancellationSignal));
581 } finally {
582 setCallingPackage(original);
Jeff Sharkey9664ff52018-08-03 17:08:04 -0600583 Trace.traceEnd(TRACE_TAG_DATABASE);
Ben Lin1cf454f2016-11-10 13:50:54 -0800584 }
585 }
586
Jeff Sharkey9edef252019-05-20 14:00:17 -0600587 @Override
588 public int checkUriPermission(String callingPkg, Uri uri, int uid, int modeFlags) {
589 uri = validateIncomingUri(uri);
590 uri = maybeGetUriWithoutUserId(uri);
591 Trace.traceBegin(TRACE_TAG_DATABASE, "checkUriPermission");
592 final String original = setCallingPackage(callingPkg);
593 try {
594 return mInterface.checkUriPermission(uri, uid, modeFlags);
595 } catch (RemoteException e) {
596 throw e.rethrowAsRuntimeException();
597 } finally {
598 setCallingPackage(original);
599 Trace.traceEnd(TRACE_TAG_DATABASE);
600 }
601 }
602
Dianne Hackbornff170242014-11-19 10:59:01 -0800603 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
604 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800605 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800606 if (enforceWritePermission(callingPkg, uri, callerToken)
607 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800608 throw new FileNotFoundException("App op not allowed");
609 }
610 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800611 if (enforceReadPermission(callingPkg, uri, callerToken)
612 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800613 throw new FileNotFoundException("App op not allowed");
614 }
615 }
616 }
617
Dianne Hackbornff170242014-11-19 10:59:01 -0800618 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
619 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700620 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
621 if (mode != MODE_ALLOWED) {
622 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800623 }
Svet Ganov99b60432015-06-27 13:15:22 -0700624
Eugene Susla93519852018-06-13 16:44:31 -0700625 return noteProxyOp(callingPkg, mReadOp);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800626 }
627
Dianne Hackbornff170242014-11-19 10:59:01 -0800628 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
629 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700630 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
631 if (mode != MODE_ALLOWED) {
632 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800633 }
Svet Ganov99b60432015-06-27 13:15:22 -0700634
Eugene Susla93519852018-06-13 16:44:31 -0700635 return noteProxyOp(callingPkg, mWriteOp);
636 }
637
638 private int noteProxyOp(String callingPkg, int op) {
639 if (op != AppOpsManager.OP_NONE) {
640 int mode = mAppOpsManager.noteProxyOp(op, callingPkg);
Svet Ganovd8eb8b22019-04-05 18:52:08 -0700641 return mode == MODE_DEFAULT ? MODE_IGNORED : mode;
Svet Ganov99b60432015-06-27 13:15:22 -0700642 }
643
Dianne Hackborn35654b62013-01-14 17:38:02 -0800644 return AppOpsManager.MODE_ALLOWED;
645 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700646 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800647
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100648 boolean checkUser(int pid, int uid, Context context) {
Varun Shahaf8cfe32019-08-16 16:11:24 -0700649 if (UserHandle.getUserId(uid) == context.getUserId() || mSingleUser) {
650 return true;
651 }
652 return context.checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED
653 || context.checkPermission(INTERACT_ACROSS_USERS_FULL, pid, uid)
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100654 == PERMISSION_GRANTED;
655 }
656
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700657 /**
658 * Verify that calling app holds both the given permission and any app-op
659 * associated with that permission.
660 */
661 private int checkPermissionAndAppOp(String permission, String callingPkg,
662 IBinder callerToken) {
663 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
664 callerToken) != PERMISSION_GRANTED) {
665 return MODE_ERRORED;
666 }
667
Eugene Susla93519852018-06-13 16:44:31 -0700668 return mTransport.noteProxyOp(callingPkg, AppOpsManager.permissionToOpCode(permission));
669 }
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700670
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700671 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700672 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800673 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700674 final Context context = getContext();
675 final int pid = Binder.getCallingPid();
676 final int uid = Binder.getCallingUid();
677 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700678 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700679
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700680 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700681 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700682 }
683
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100684 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700685 final String componentPerm = getReadPermission();
686 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700687 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
688 if (mode == MODE_ALLOWED) {
689 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700690 } else {
691 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700692 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700693 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700694 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700695
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700696 // track if unprotected read is allowed; any denied
697 // <path-permission> below removes this ability
698 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700699
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700700 final PathPermission[] pps = getPathPermissions();
701 if (pps != null) {
702 final String path = uri.getPath();
703 for (PathPermission pp : pps) {
704 final String pathPerm = pp.getReadPermission();
705 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700706 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
707 if (mode == MODE_ALLOWED) {
708 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700709 } else {
710 // any denied <path-permission> means we lose
711 // default <provider> access.
712 allowDefaultRead = false;
713 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700714 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700715 }
716 }
717 }
718 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700719
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700720 // if we passed <path-permission> checks above, and no default
721 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700722 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700724
725 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800726 final int callingUserId = UserHandle.getUserId(uid);
727 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
728 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800729 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
730 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700731 return MODE_ALLOWED;
732 }
733
734 // If the worst denial we found above was ignored, then pass that
735 // ignored through; otherwise we assume it should be a real error below.
736 if (strongestMode == MODE_IGNORED) {
737 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700738 }
739
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600740 final String suffix;
741 if (android.Manifest.permission.MANAGE_DOCUMENTS.equals(mReadPermission)) {
742 suffix = " requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs";
743 } else if (mExported) {
744 suffix = " requires " + missingPerm + ", or grantUriPermission()";
745 } else {
746 suffix = " requires the provider be exported, or grantUriPermission()";
747 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700748 throw new SecurityException("Permission Denial: reading "
749 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
Jeff Sharkeyc0cc2202017-03-21 19:25:34 -0600750 + ", uid=" + uid + suffix);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700751 }
752
753 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700754 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800755 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700756 final Context context = getContext();
757 final int pid = Binder.getCallingPid();
758 final int uid = Binder.getCallingUid();
759 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700760 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700761
762 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700763 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700764 }
765
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100766 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700767 final String componentPerm = getWritePermission();
768 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700769 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
770 if (mode == MODE_ALLOWED) {
771 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700772 } else {
773 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700774 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700775 }
776 }
777
778 // track if unprotected write is allowed; any denied
779 // <path-permission> below removes this ability
780 boolean allowDefaultWrite = (componentPerm == null);
781
782 final PathPermission[] pps = getPathPermissions();
783 if (pps != null) {
784 final String path = uri.getPath();
785 for (PathPermission pp : pps) {
786 final String pathPerm = pp.getWritePermission();
787 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700788 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
789 if (mode == MODE_ALLOWED) {
790 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700791 } else {
792 // any denied <path-permission> means we lose
793 // default <provider> access.
794 allowDefaultWrite = false;
795 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700796 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700797 }
798 }
799 }
800 }
801
802 // if we passed <path-permission> checks above, and no default
803 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700804 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700805 }
806
807 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800808 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
809 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700810 return MODE_ALLOWED;
811 }
812
813 // If the worst denial we found above was ignored, then pass that
814 // ignored through; otherwise we assume it should be a real error below.
815 if (strongestMode == MODE_IGNORED) {
816 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700817 }
818
819 final String failReason = mExported
820 ? " requires " + missingPerm + ", or grantUriPermission()"
821 : " requires the provider be exported, or grantUriPermission()";
822 throw new SecurityException("Permission Denial: writing "
823 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
824 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 }
826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700828 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800829 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 * constructor.
831 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700832 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 return mContext;
834 }
835
836 /**
Pinyao Ting6dcd1132019-10-16 17:13:34 -0700837 * Retrieves a Non-Nullable Context this provider is running in, this is intended to be called
838 * after {@link #onCreate}. When called before context was created, an IllegalStateException
839 * will be thrown.
840 * <p>
841 * Note A provider must be declared in the manifest and created automatically by the system,
842 * and context is only available after {@link #onCreate} is called.
843 */
844 @NonNull
845 public final Context requireContext() {
846 final Context ctx = getContext();
847 if (ctx == null) {
848 throw new IllegalStateException("Cannot find context from the provider.");
849 }
850 return ctx;
851 }
852
853 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700854 * Set the calling package, returning the current value (or {@code null})
855 * which can be used later to restore the previous state.
856 */
857 private String setCallingPackage(String callingPackage) {
858 final String original = mCallingPackage.get();
859 mCallingPackage.set(callingPackage);
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600860 onCallingPackageChanged();
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700861 return original;
862 }
863
864 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700865 * Return the package name of the caller that initiated the request being
866 * processed on the current thread. The returned package will have been
867 * verified to belong to the calling UID. Returns {@code null} if not
868 * currently processing a request.
869 * <p>
870 * This will always return {@code null} when processing
871 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
872 *
873 * @see Binder#getCallingUid()
874 * @see Context#grantUriPermission(String, Uri, int)
875 * @throws SecurityException if the calling package doesn't belong to the
876 * calling UID.
877 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700878 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700879 final String pkg = mCallingPackage.get();
880 if (pkg != null) {
881 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
882 }
883 return pkg;
884 }
885
Jeff Sharkey951f99b2019-05-15 19:19:59 -0600886 /** {@hide} */
887 public final @Nullable String getCallingPackageUnchecked() {
888 return mCallingPackage.get();
889 }
890
891 /** {@hide} */
892 public void onCallingPackageChanged() {
893 }
894
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700895 /**
Jeff Sharkeyd2b64d72018-10-19 15:40:03 -0600896 * Opaque token representing the identity of an incoming IPC.
897 */
898 public final class CallingIdentity {
899 /** {@hide} */
900 public final long binderToken;
901 /** {@hide} */
902 public final String callingPackage;
903
904 /** {@hide} */
905 public CallingIdentity(long binderToken, String callingPackage) {
906 this.binderToken = binderToken;
907 this.callingPackage = callingPackage;
908 }
909 }
910
911 /**
912 * Reset the identity of the incoming IPC on the current thread.
913 * <p>
914 * Internally this calls {@link Binder#clearCallingIdentity()} and also
915 * clears any value stored in {@link #getCallingPackage()}.
916 *
917 * @return Returns an opaque token that can be used to restore the original
918 * calling identity by passing it to
919 * {@link #restoreCallingIdentity}.
920 */
921 public final @NonNull CallingIdentity clearCallingIdentity() {
922 return new CallingIdentity(Binder.clearCallingIdentity(), setCallingPackage(null));
923 }
924
925 /**
926 * Restore the identity of the incoming IPC on the current thread back to a
927 * previously identity that was returned by {@link #clearCallingIdentity}.
928 * <p>
929 * Internally this calls {@link Binder#restoreCallingIdentity(long)} and
930 * also restores any value stored in {@link #getCallingPackage()}.
931 */
932 public final void restoreCallingIdentity(@NonNull CallingIdentity identity) {
933 Binder.restoreCallingIdentity(identity.binderToken);
934 mCallingPackage.set(identity.callingPackage);
935 }
936
937 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100938 * Change the authorities of the ContentProvider.
939 * This is normally set for you from its manifest information when the provider is first
940 * created.
941 * @hide
942 * @param authorities the semi-colon separated authorities of the ContentProvider.
943 */
944 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100945 if (authorities != null) {
946 if (authorities.indexOf(';') == -1) {
947 mAuthority = authorities;
948 mAuthorities = null;
949 } else {
950 mAuthority = null;
951 mAuthorities = authorities.split(";");
952 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100953 }
954 }
955
956 /** @hide */
957 protected final boolean matchesOurAuthorities(String authority) {
958 if (mAuthority != null) {
959 return mAuthority.equals(authority);
960 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100961 if (mAuthorities != null) {
962 int length = mAuthorities.length;
963 for (int i = 0; i < length; i++) {
964 if (mAuthorities[i].equals(authority)) return true;
965 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100966 }
967 return false;
968 }
969
970
971 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 * Change the permission required to read data from the content
973 * provider. This is normally set for you from its manifest information
974 * when the provider is first created.
975 *
976 * @param permission Name of the permission required for read-only access.
977 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700978 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 mReadPermission = permission;
980 }
981
982 /**
983 * Return the name of the permission required for read-only access to
984 * this content provider. This method can be called from multiple
985 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800986 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
987 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700989 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 return mReadPermission;
991 }
992
993 /**
994 * Change the permission required to read and write data in the content
995 * provider. This is normally set for you from its manifest information
996 * when the provider is first created.
997 *
998 * @param permission Name of the permission required for read/write access.
999 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001000 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 mWritePermission = permission;
1002 }
1003
1004 /**
1005 * Return the name of the permission required for read/write access to
1006 * this content provider. This method can be called from multiple
1007 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001008 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1009 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001011 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 return mWritePermission;
1013 }
1014
1015 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001016 * Change the path-based permission required to read and/or write data in
1017 * the content provider. This is normally set for you from its manifest
1018 * information when the provider is first created.
1019 *
1020 * @param permissions Array of path permission descriptions.
1021 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001022 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001023 mPathPermissions = permissions;
1024 }
1025
1026 /**
1027 * Return the path-based permissions required for read and/or write access to
1028 * this content provider. This method can be called from multiple
1029 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001030 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1031 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001032 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001033 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001034 return mPathPermissions;
1035 }
1036
Dianne Hackborn35654b62013-01-14 17:38:02 -08001037 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01001038 @UnsupportedAppUsage
Dianne Hackborn35654b62013-01-14 17:38:02 -08001039 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001040 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -08001041 mTransport.mReadOp = readOp;
1042 mTransport.mWriteOp = writeOp;
1043 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001044 }
1045
Dianne Hackborn961321f2013-02-05 17:22:41 -08001046 /** @hide */
1047 public AppOpsManager getAppOpsManager() {
1048 return mTransport.mAppOpsManager;
1049 }
1050
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001051 /** @hide */
1052 public final void setTransportLoggingEnabled(boolean enabled) {
Varun Shahd5395532019-08-26 18:07:48 -07001053 if (mTransport == null) {
1054 return;
1055 }
1056 if (enabled) {
1057 mTransport.mInterface = new LoggingContentInterface(getClass().getSimpleName(), this);
1058 } else {
1059 mTransport.mInterface = this;
Jeff Sharkeybffd2502019-02-28 16:39:12 -07001060 }
1061 }
1062
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001063 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001064 * Implement this to initialize your content provider on startup.
1065 * This method is called for all registered content providers on the
1066 * application main thread at application launch time. It must not perform
1067 * lengthy operations, or application startup will be delayed.
1068 *
1069 * <p>You should defer nontrivial initialization (such as opening,
1070 * upgrading, and scanning databases) until the content provider is used
1071 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
1072 * keeps application startup fast, avoids unnecessary work if the provider
1073 * turns out not to be needed, and stops database errors (such as a full
1074 * disk) from halting application launch.
1075 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001076 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001077 * is a helpful utility class that makes it easy to manage databases,
1078 * and will automatically defer opening until first use. If you do use
1079 * SQLiteOpenHelper, make sure to avoid calling
1080 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
1081 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
1082 * from this method. (Instead, override
1083 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
1084 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 *
1086 * @return true if the provider was successfully loaded, false otherwise
1087 */
1088 public abstract boolean onCreate();
1089
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001090 /**
1091 * {@inheritDoc}
1092 * This method is always called on the application main thread, and must
1093 * not perform lengthy operations.
1094 *
1095 * <p>The default content provider implementation does nothing.
1096 * Override this method to take appropriate action.
1097 * (Content providers do not usually care about things like screen
1098 * orientation, but may want to know about locale changes.)
1099 */
Steve McKayea93fe72016-12-02 11:35:35 -08001100 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 public void onConfigurationChanged(Configuration newConfig) {
1102 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001103
1104 /**
1105 * {@inheritDoc}
1106 * This method is always called on the application main thread, and must
1107 * not perform lengthy operations.
1108 *
1109 * <p>The default content provider implementation does nothing.
1110 * Subclasses may override this method to take appropriate action.
1111 */
Steve McKayea93fe72016-12-02 11:35:35 -08001112 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 public void onLowMemory() {
1114 }
1115
Steve McKayea93fe72016-12-02 11:35:35 -08001116 @Override
Dianne Hackbornc68c9132011-07-29 01:25:18 -07001117 public void onTrimMemory(int level) {
1118 }
1119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001121 * Implement this to handle query requests from clients.
Steve McKay29c3f682016-12-16 14:52:59 -08001122 *
1123 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1124 * {@link #query(Uri, String[], Bundle, CancellationSignal)} and provide a stub
1125 * implementation of this method.
1126 *
1127 * <p>This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001128 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1129 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 * <p>
1131 * Example client call:<p>
1132 * <pre>// Request a specific record.
1133 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +10001134 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 projection, // Which columns to return.
1136 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +10001137 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 People.NAME + " ASC"); // Sort order.</pre>
1139 * Example implementation:<p>
1140 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1141 // proper SQL syntax for us.
1142 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1143
1144 // Set the table we're querying.
1145 qBuilder.setTables(DATABASE_TABLE_NAME);
1146
1147 // If the query ends in a specific record number, we're
1148 // being asked for a specific record, so set the
1149 // WHERE clause in our query.
1150 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1151 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1152 }
1153
1154 // Make the query.
1155 Cursor c = qBuilder.query(mDb,
1156 projection,
1157 selection,
1158 selectionArgs,
1159 groupBy,
1160 having,
1161 sortOrder);
1162 c.setNotificationUri(getContext().getContentResolver(), uri);
1163 return c;</pre>
1164 *
1165 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +10001166 * if the client is requesting a specific record, the URI will end in a record number
1167 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1168 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001170 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001172 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +10001173 * @param selectionArgs You may include ?s in selection, which will be replaced by
1174 * the values from selectionArgs, in order that they appear in the selection.
1175 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001177 * If {@code null} then the provider is free to define the sort order.
1178 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001180 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1181 @Nullable String selection, @Nullable String[] selectionArgs,
1182 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183
Fred Quintana5bba6322009-10-05 14:21:12 -07001184 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -08001185 * Implement this to handle query requests from clients with support for cancellation.
Steve McKay29c3f682016-12-16 14:52:59 -08001186 *
1187 * <p>Apps targeting {@link android.os.Build.VERSION_CODES#O} or higher should override
1188 * {@link #query(Uri, String[], Bundle, CancellationSignal)} instead of this method.
1189 *
1190 * <p>This method can be called from multiple threads, as described in
Jeff Brown75ea64f2012-01-25 19:37:13 -08001191 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1192 * and Threads</a>.
1193 * <p>
1194 * Example client call:<p>
1195 * <pre>// Request a specific record.
1196 * Cursor managedCursor = managedQuery(
1197 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
1198 projection, // Which columns to return.
1199 null, // WHERE clause.
1200 null, // WHERE clause value substitution
1201 People.NAME + " ASC"); // Sort order.</pre>
1202 * Example implementation:<p>
1203 * <pre>// SQLiteQueryBuilder is a helper class that creates the
1204 // proper SQL syntax for us.
1205 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
1206
1207 // Set the table we're querying.
1208 qBuilder.setTables(DATABASE_TABLE_NAME);
1209
1210 // If the query ends in a specific record number, we're
1211 // being asked for a specific record, so set the
1212 // WHERE clause in our query.
1213 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
1214 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
1215 }
1216
1217 // Make the query.
1218 Cursor c = qBuilder.query(mDb,
1219 projection,
1220 selection,
1221 selectionArgs,
1222 groupBy,
1223 having,
1224 sortOrder);
1225 c.setNotificationUri(getContext().getContentResolver(), uri);
1226 return c;</pre>
1227 * <p>
1228 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001229 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1230 * signal to ensure correct operation on older versions of the Android Framework in
1231 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001232 *
1233 * @param uri The URI to query. This will be the full URI sent by the client;
1234 * if the client is requesting a specific record, the URI will end in a record number
1235 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1236 * that _id value.
1237 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001238 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001239 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001240 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001241 * @param selectionArgs You may include ?s in selection, which will be replaced by
1242 * the values from selectionArgs, in order that they appear in the selection.
1243 * The values will be bound as Strings.
1244 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001245 * If {@code null} then the provider is free to define the sort order.
1246 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Sharkey67f9d502017-08-05 13:49:13 -06001247 * If the operation is canceled, then {@link android.os.OperationCanceledException} will be thrown
Jeff Brown75ea64f2012-01-25 19:37:13 -08001248 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001249 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001250 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001251 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1252 @Nullable String selection, @Nullable String[] selectionArgs,
1253 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001254 return query(uri, projection, selection, selectionArgs, sortOrder);
1255 }
1256
1257 /**
Steve McKayea93fe72016-12-02 11:35:35 -08001258 * Implement this to handle query requests where the arguments are packed into a {@link Bundle}.
1259 * Arguments may include traditional SQL style query arguments. When present these
1260 * should be handled according to the contract established in
Andrew Solovay27e43462018-12-12 15:38:06 -08001261 * {@link #query(Uri, String[], String, String[], String, CancellationSignal)}.
Steve McKayea93fe72016-12-02 11:35:35 -08001262 *
1263 * <p>Traditional SQL arguments can be found in the bundle using the following keys:
Andrew Solovay27e43462018-12-12 15:38:06 -08001264 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION}
1265 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SELECTION_ARGS}
1266 * <li>{@link android.content.ContentResolver#QUERY_ARG_SQL_SORT_ORDER}
Steve McKayea93fe72016-12-02 11:35:35 -08001267 *
Steve McKay76b27702017-04-24 12:07:53 -07001268 * <p>This method can be called from multiple threads, as described in
1269 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1270 * and Threads</a>.
1271 *
1272 * <p>
1273 * Example client call:<p>
1274 * <pre>// Request 20 records starting at row index 30.
1275 Bundle queryArgs = new Bundle();
1276 queryArgs.putInt(ContentResolver.QUERY_ARG_OFFSET, 30);
1277 queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, 20);
1278
1279 Cursor cursor = getContentResolver().query(
1280 contentUri, // Content Uri is specific to individual content providers.
1281 projection, // String[] describing which columns to return.
1282 queryArgs, // Query arguments.
1283 null); // Cancellation signal.</pre>
1284 *
1285 * Example implementation:<p>
1286 * <pre>
1287
1288 int recordsetSize = 0x1000; // Actual value is implementation specific.
1289 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY; // ensure queryArgs is non-null
1290
1291 int offset = queryArgs.getInt(ContentResolver.QUERY_ARG_OFFSET, 0);
1292 int limit = queryArgs.getInt(ContentResolver.QUERY_ARG_LIMIT, Integer.MIN_VALUE);
1293
1294 MatrixCursor c = new MatrixCursor(PROJECTION, limit);
1295
1296 // Calculate the number of items to include in the cursor.
1297 int numItems = MathUtils.constrain(recordsetSize - offset, 0, limit);
1298
1299 // Build the paged result set....
1300 for (int i = offset; i < offset + numItems; i++) {
1301 // populate row from your data.
1302 }
1303
1304 Bundle extras = new Bundle();
1305 c.setExtras(extras);
1306
1307 // Any QUERY_ARG_* key may be included if honored.
1308 // In an actual implementation, include only keys that are both present in queryArgs
1309 // and reflected in the Cursor output. For example, if QUERY_ARG_OFFSET were included
1310 // in queryArgs, but was ignored because it contained an invalid value (like –273),
1311 // then QUERY_ARG_OFFSET should be omitted.
1312 extras.putStringArray(ContentResolver.EXTRA_HONORED_ARGS, new String[] {
1313 ContentResolver.QUERY_ARG_OFFSET,
1314 ContentResolver.QUERY_ARG_LIMIT
1315 });
1316
1317 extras.putInt(ContentResolver.EXTRA_TOTAL_COUNT, recordsetSize);
1318
1319 cursor.setNotificationUri(getContext().getContentResolver(), uri);
1320
1321 return cursor;</pre>
1322 * <p>
Andrew Solovay27e43462018-12-12 15:38:06 -08001323 * See {@link #query(Uri, String[], String, String[], String, CancellationSignal)}
1324 * for implementation details.
Steve McKayea93fe72016-12-02 11:35:35 -08001325 *
1326 * @param uri The URI to query. This will be the full URI sent by the client.
Steve McKayea93fe72016-12-02 11:35:35 -08001327 * @param projection The list of columns to put into the cursor.
1328 * If {@code null} provide a default set of columns.
1329 * @param queryArgs A Bundle containing all additional information necessary for the query.
1330 * Values in the Bundle may include SQL style arguments.
1331 * @param cancellationSignal A signal to cancel the operation in progress,
1332 * or {@code null}.
1333 * @return a Cursor or {@code null}.
1334 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001335 @Override
Steve McKayea93fe72016-12-02 11:35:35 -08001336 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1337 @Nullable Bundle queryArgs, @Nullable CancellationSignal cancellationSignal) {
1338 queryArgs = queryArgs != null ? queryArgs : Bundle.EMPTY;
Steve McKay29c3f682016-12-16 14:52:59 -08001339
Steve McKayd7ece9f2017-01-12 16:59:59 -08001340 // if client doesn't supply an SQL sort order argument, attempt to build one from
1341 // QUERY_ARG_SORT* arguments.
Steve McKay29c3f682016-12-16 14:52:59 -08001342 String sortClause = queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER);
Steve McKay29c3f682016-12-16 14:52:59 -08001343 if (sortClause == null && queryArgs.containsKey(ContentResolver.QUERY_ARG_SORT_COLUMNS)) {
1344 sortClause = ContentResolver.createSqlSortClause(queryArgs);
1345 }
1346
Steve McKayea93fe72016-12-02 11:35:35 -08001347 return query(
1348 uri,
1349 projection,
Steve McKay29c3f682016-12-16 14:52:59 -08001350 queryArgs.getString(ContentResolver.QUERY_ARG_SQL_SELECTION),
1351 queryArgs.getStringArray(ContentResolver.QUERY_ARG_SQL_SELECTION_ARGS),
1352 sortClause,
Steve McKayea93fe72016-12-02 11:35:35 -08001353 cancellationSignal);
1354 }
1355
1356 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001357 * Implement this to handle requests for the MIME type of the data at the
1358 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 * <code>vnd.android.cursor.item</code> for a single record,
1360 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001361 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001362 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1363 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001365 * <p>Note that there are no permissions needed for an application to
1366 * access this information; if your content provider requires read and/or
1367 * write permissions, or is not exported, all applications can still call
1368 * this method regardless of their access permissions. This allows them
1369 * to retrieve the MIME type for a URI when dispatching intents.
1370 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001372 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001374 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001375 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376
1377 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001378 * Implement this to support canonicalization of URIs that refer to your
1379 * content provider. A canonical URI is one that can be transported across
1380 * devices, backup/restore, and other contexts, and still be able to refer
1381 * to the same data item. Typically this is implemented by adding query
1382 * params to the URI allowing the content provider to verify that an incoming
1383 * canonical URI references the same data as it was originally intended for and,
1384 * if it doesn't, to find that data (if it exists) in the current environment.
1385 *
1386 * <p>For example, if the content provider holds people and a normal URI in it
1387 * is created with a row index into that people database, the cananical representation
1388 * may have an additional query param at the end which specifies the name of the
1389 * person it is intended for. Later calls into the provider with that URI will look
1390 * up the row of that URI's base index and, if it doesn't match or its entry's
1391 * name doesn't match the name in the query param, perform a query on its database
1392 * to find the correct row to operate on.</p>
1393 *
1394 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1395 * URIs (including this one) must perform this verification and recovery of any
1396 * canonical URIs they receive. In addition, you must also implement
1397 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1398 *
1399 * <p>The default implementation of this method returns null, indicating that
1400 * canonical URIs are not supported.</p>
1401 *
1402 * @param url The Uri to canonicalize.
1403 *
1404 * @return Return the canonical representation of <var>url</var>, or null if
1405 * canonicalization of that Uri is not supported.
1406 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001407 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001408 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001409 return null;
1410 }
1411
1412 /**
1413 * Remove canonicalization from canonical URIs previously returned by
1414 * {@link #canonicalize}. For example, if your implementation is to add
1415 * a query param to canonicalize a URI, this method can simply trip any
1416 * query params on the URI. The default implementation always returns the
1417 * same <var>url</var> that was passed in.
1418 *
1419 * @param url The Uri to remove any canonicalization from.
1420 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001421 * @return Return the non-canonical representation of <var>url</var>, return
1422 * the <var>url</var> as-is if there is nothing to do, or return null if
1423 * the data identified by the canonical representation can not be found in
1424 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001425 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001426 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001427 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001428 return url;
1429 }
1430
1431 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001432 * Implement this to support refresh of content identified by {@code uri}. By default, this
1433 * method returns false; providers who wish to implement this should return true to signal the
1434 * client that the provider has tried refreshing with its own implementation.
1435 * <p>
1436 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1437 * <p>
1438 * Client code should only invoke this method when there is a strong indication (such as a user
1439 * initiated pull to refresh gesture) that the content is stale.
1440 * <p>
1441 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1442 * notifications when content changes.
1443 *
1444 * @param uri The Uri identifying the data to refresh.
1445 * @param args Additional options from the client. The definitions of these are specific to the
1446 * content provider being called.
1447 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1448 * none. For example, if you called refresh on a particular uri, you should call
1449 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1450 * canceled the refresh request.
1451 * @return true if the provider actually tried refreshing.
Ben Lin1cf454f2016-11-10 13:50:54 -08001452 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001453 @Override
Ben Lin1cf454f2016-11-10 13:50:54 -08001454 public boolean refresh(Uri uri, @Nullable Bundle args,
1455 @Nullable CancellationSignal cancellationSignal) {
1456 return false;
1457 }
1458
Jeff Sharkey9edef252019-05-20 14:00:17 -06001459 /** {@hide} */
1460 @Override
1461 public int checkUriPermission(@NonNull Uri uri, int uid, @Intent.AccessUriMode int modeFlags) {
1462 return PackageManager.PERMISSION_DENIED;
1463 }
1464
Ben Lin1cf454f2016-11-10 13:50:54 -08001465 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001466 * @hide
1467 * Implementation when a caller has performed an insert on the content
1468 * provider, but that call has been rejected for the operation given
1469 * to {@link #setAppOps(int, int)}. The default implementation simply
1470 * returns a dummy URI that is the base URI with a 0 path element
1471 * appended.
1472 */
1473 public Uri rejectInsert(Uri uri, ContentValues values) {
1474 // If not allowed, we need to return some reasonable URI. Maybe the
1475 // content provider should be responsible for this, but for now we
1476 // will just return the base URI with a dummy '0' tagged on to it.
1477 // You shouldn't be able to read if you can't write, anyway, so it
1478 // shouldn't matter much what is returned.
1479 return uri.buildUpon().appendPath("0").build();
1480 }
1481
1482 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001483 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1485 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001486 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001487 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1488 * and Threads</a>.
Varun Shah8c80a3f2019-10-16 12:21:19 -07001489 * @param uri The content:// URI of the insertion request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 * @param values A set of column_name/value pairs to add to the database.
1491 * @return The URI for the newly inserted item.
1492 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001493 @Override
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001494 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495
1496 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001497 * Override this to handle requests to insert a set of new rows, or the
1498 * default implementation will iterate over the values and call
1499 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1501 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001502 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001503 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1504 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 *
1506 * @param uri The content:// URI of the insertion request.
1507 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001508 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 * @return The number of values that were inserted.
1510 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001511 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001512 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 int numValues = values.length;
1514 for (int i = 0; i < numValues; i++) {
1515 insert(uri, values[i]);
1516 }
1517 return numValues;
1518 }
1519
1520 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001521 * Implement this to handle requests to delete one or more rows.
1522 * The implementation should apply the selection clause when performing
1523 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001524 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001526 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001527 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1528 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 *
1530 * <p>The implementation is responsible for parsing out a row ID at the end
1531 * of the URI, if a specific row is being deleted. That is, the client would
1532 * pass in <code>content://contacts/people/22</code> and the implementation is
1533 * responsible for parsing the record number (22) when creating a SQL statement.
1534 *
1535 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1536 * @param selection An optional restriction to apply to rows when deleting.
1537 * @return The number of rows affected.
1538 * @throws SQLException
1539 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001540 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001541 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1542 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543
1544 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001545 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001546 * The implementation should update all rows matching the selection
1547 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1549 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001550 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001551 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1552 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 *
1554 * @param uri The URI to query. This can potentially have a record ID if this
1555 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001556 * @param values A set of column_name/value pairs to update in the database.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 * @param selection An optional filter to match rows to update.
1558 * @return the number of rows affected.
1559 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001560 @Override
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001561 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001562 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563
1564 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001565 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001566 * The default implementation always throws {@link FileNotFoundException}.
1567 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001568 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1569 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001570 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001571 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1572 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001573 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 *
1575 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1576 * their responsibility to close it when done. That is, the implementation
1577 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001578 * <p>
1579 * If opened with the exclusive "r" or "w" modes, the returned
1580 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1581 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1582 * supports seeking.
1583 * <p>
1584 * If you need to detect when the returned ParcelFileDescriptor has been
1585 * closed, or if the remote process has crashed or encountered some other
1586 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1587 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1588 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1589 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
Jeff Sharkeyb31afd22017-06-12 14:17:10 -06001590 * <p>
1591 * If you need to return a large file that isn't backed by a real file on
1592 * disk, such as a file on a network share or cloud storage service,
1593 * consider using
1594 * {@link StorageManager#openProxyFileDescriptor(int, android.os.ProxyFileDescriptorCallback, android.os.Handler)}
1595 * which will let you to stream the content on-demand.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001597 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1598 * to return the appropriate MIME type for the data returned here with
1599 * the same URI. This will allow intent resolution to automatically determine the data MIME
1600 * type and select the appropriate matching targets as part of its operation.</p>
1601 *
1602 * <p class="note">For better interoperability with other applications, it is recommended
1603 * that for any URIs that can be opened, you also support queries on them
1604 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1605 * You may also want to support other common columns if you have additional meta-data
1606 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1607 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1608 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 * @param uri The URI whose file is to be opened.
1610 * @param mode Access mode for the file. May be "r" for read-only access,
1611 * "rw" for read and write access, or "rwt" for read and write access
1612 * that truncates any existing file.
1613 *
1614 * @return Returns a new ParcelFileDescriptor which you can use to access
1615 * the file.
1616 *
1617 * @throws FileNotFoundException Throws FileNotFoundException if there is
1618 * no file associated with the given URI or the mode is invalid.
1619 * @throws SecurityException Throws SecurityException if the caller does
1620 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001621 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 * @see #openAssetFile(Uri, String)
1623 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001624 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001625 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001626 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001627 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 throws FileNotFoundException {
1629 throw new FileNotFoundException("No files supported by provider at "
1630 + uri);
1631 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001634 * Override this to handle requests to open a file blob.
1635 * The default implementation always throws {@link FileNotFoundException}.
1636 * This method can be called from multiple threads, as described in
1637 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1638 * and Threads</a>.
1639 *
1640 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1641 * to the caller. This way large data (such as images and documents) can be
1642 * returned without copying the content.
1643 *
1644 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1645 * their responsibility to close it when done. That is, the implementation
1646 * of this method should create a new ParcelFileDescriptor for each call.
1647 * <p>
1648 * If opened with the exclusive "r" or "w" modes, the returned
1649 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1650 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1651 * supports seeking.
1652 * <p>
1653 * If you need to detect when the returned ParcelFileDescriptor has been
1654 * closed, or if the remote process has crashed or encountered some other
1655 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1656 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1657 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1658 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1659 *
1660 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1661 * to return the appropriate MIME type for the data returned here with
1662 * the same URI. This will allow intent resolution to automatically determine the data MIME
1663 * type and select the appropriate matching targets as part of its operation.</p>
1664 *
1665 * <p class="note">For better interoperability with other applications, it is recommended
1666 * that for any URIs that can be opened, you also support queries on them
1667 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1668 * You may also want to support other common columns if you have additional meta-data
1669 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1670 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1671 *
1672 * @param uri The URI whose file is to be opened.
1673 * @param mode Access mode for the file. May be "r" for read-only access,
1674 * "w" for write-only access, "rw" for read and write access, or
1675 * "rwt" for read and write access that truncates any existing
1676 * file.
1677 * @param signal A signal to cancel the operation in progress, or
1678 * {@code null} if none. For example, if you are downloading a
1679 * file from the network to service a "rw" mode request, you
1680 * should periodically call
1681 * {@link CancellationSignal#throwIfCanceled()} to check whether
1682 * the client has canceled the request and abort the download.
1683 *
1684 * @return Returns a new ParcelFileDescriptor which you can use to access
1685 * the file.
1686 *
1687 * @throws FileNotFoundException Throws FileNotFoundException if there is
1688 * no file associated with the given URI or the mode is invalid.
1689 * @throws SecurityException Throws SecurityException if the caller does
1690 * not have permission to access the file.
1691 *
1692 * @see #openAssetFile(Uri, String)
1693 * @see #openFileHelper(Uri, String)
1694 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001695 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001696 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001697 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001698 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1699 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001700 return openFile(uri, mode);
1701 }
1702
1703 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 * This is like {@link #openFile}, but can be implemented by providers
1705 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001706 * inside of their .apk.
1707 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001708 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1709 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001710 *
1711 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001712 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001713 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1715 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1716 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001717 * <p>
1718 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1719 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001720 *
1721 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 * should create the AssetFileDescriptor with
1723 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001724 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001726 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1727 * to return the appropriate MIME type for the data returned here with
1728 * the same URI. This will allow intent resolution to automatically determine the data MIME
1729 * type and select the appropriate matching targets as part of its operation.</p>
1730 *
1731 * <p class="note">For better interoperability with other applications, it is recommended
1732 * that for any URIs that can be opened, you also support queries on them
1733 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1734 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 * @param uri The URI whose file is to be opened.
1736 * @param mode Access mode for the file. May be "r" for read-only access,
1737 * "w" for write-only access (erasing whatever data is currently in
1738 * the file), "wa" for write-only access to append to any existing data,
1739 * "rw" for read and write access on any existing data, and "rwt" for read
1740 * and write access that truncates any existing file.
1741 *
1742 * @return Returns a new AssetFileDescriptor which you can use to access
1743 * the file.
1744 *
1745 * @throws FileNotFoundException Throws FileNotFoundException if there is
1746 * no file associated with the given URI or the mode is invalid.
1747 * @throws SecurityException Throws SecurityException if the caller does
1748 * not have permission to access the file.
Steve McKayea93fe72016-12-02 11:35:35 -08001749 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 * @see #openFile(Uri, String)
1751 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001752 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001754 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 throws FileNotFoundException {
1756 ParcelFileDescriptor fd = openFile(uri, mode);
1757 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1758 }
1759
1760 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001761 * This is like {@link #openFile}, but can be implemented by providers
1762 * that need to be able to return sub-sections of files, often assets
1763 * inside of their .apk.
1764 * This method can be called from multiple threads, as described in
1765 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1766 * and Threads</a>.
1767 *
1768 * <p>If you implement this, your clients must be able to deal with such
1769 * file slices, either directly with
1770 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1771 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1772 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1773 * methods.
1774 * <p>
1775 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1776 * streaming of data.
1777 *
1778 * <p class="note">If you are implementing this to return a full file, you
1779 * should create the AssetFileDescriptor with
1780 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1781 * applications that cannot handle sub-sections of files.</p>
1782 *
1783 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1784 * to return the appropriate MIME type for the data returned here with
1785 * the same URI. This will allow intent resolution to automatically determine the data MIME
1786 * type and select the appropriate matching targets as part of its operation.</p>
1787 *
1788 * <p class="note">For better interoperability with other applications, it is recommended
1789 * that for any URIs that can be opened, you also support queries on them
1790 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1791 *
1792 * @param uri The URI whose file is to be opened.
1793 * @param mode Access mode for the file. May be "r" for read-only access,
1794 * "w" for write-only access (erasing whatever data is currently in
1795 * the file), "wa" for write-only access to append to any existing data,
1796 * "rw" for read and write access on any existing data, and "rwt" for read
1797 * and write access that truncates any existing file.
1798 * @param signal A signal to cancel the operation in progress, or
1799 * {@code null} if none. For example, if you are downloading a
1800 * file from the network to service a "rw" mode request, you
1801 * should periodically call
1802 * {@link CancellationSignal#throwIfCanceled()} to check whether
1803 * the client has canceled the request and abort the download.
1804 *
1805 * @return Returns a new AssetFileDescriptor which you can use to access
1806 * the file.
1807 *
1808 * @throws FileNotFoundException Throws FileNotFoundException if there is
1809 * no file associated with the given URI or the mode is invalid.
1810 * @throws SecurityException Throws SecurityException if the caller does
1811 * not have permission to access the file.
1812 *
1813 * @see #openFile(Uri, String)
1814 * @see #openFileHelper(Uri, String)
1815 * @see #getType(android.net.Uri)
1816 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001817 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001818 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1819 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001820 return openAssetFile(uri, mode);
1821 }
1822
1823 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 * Convenience for subclasses that wish to implement {@link #openFile}
1825 * by looking up a column named "_data" at the given URI.
1826 *
1827 * @param uri The URI to be opened.
1828 * @param mode The file mode. May be "r" for read-only access,
1829 * "w" for write-only access (erasing whatever data is currently in
1830 * the file), "wa" for write-only access to append to any existing data,
1831 * "rw" for read and write access on any existing data, and "rwt" for read
1832 * and write access that truncates any existing file.
1833 *
1834 * @return Returns a new ParcelFileDescriptor that can be used by the
1835 * client to access the file.
1836 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001837 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1838 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1840 int count = (c != null) ? c.getCount() : 0;
1841 if (count != 1) {
1842 // If there is not exactly one result, throw an appropriate
1843 // exception.
1844 if (c != null) {
1845 c.close();
1846 }
1847 if (count == 0) {
1848 throw new FileNotFoundException("No entry for " + uri);
1849 }
1850 throw new FileNotFoundException("Multiple items at " + uri);
1851 }
1852
1853 c.moveToFirst();
1854 int i = c.getColumnIndex("_data");
1855 String path = (i >= 0 ? c.getString(i) : null);
1856 c.close();
1857 if (path == null) {
1858 throw new FileNotFoundException("Column _data not found.");
1859 }
1860
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001861 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 return ParcelFileDescriptor.open(new File(path), modeBits);
1863 }
1864
1865 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001866 * Called by a client to determine the types of data streams that this
1867 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001868 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001869 * of a particular type, return that MIME type if it matches the given
1870 * mimeTypeFilter. If it can perform type conversions, return an array
1871 * of all supported MIME types that match mimeTypeFilter.
1872 *
1873 * @param uri The data in the content provider being queried.
1874 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001875 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001876 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001877 * given mimeTypeFilter. Otherwise returns an array of all available
1878 * concrete MIME types.
1879 *
1880 * @see #getType(Uri)
1881 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001882 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001883 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07001884 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07001885 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001886 return null;
1887 }
1888
1889 /**
1890 * Called by a client to open a read-only stream containing data of a
1891 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1892 * except the file can only be read-only and the content provider may
1893 * perform data conversions to generate data of the desired type.
1894 *
1895 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001896 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001897 * {@link #openAssetFile(Uri, String)}.
1898 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001899 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001900 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001901 * <p>
1902 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1903 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001904 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001905 * <p class="note">For better interoperability with other applications, it is recommended
1906 * that for any URIs that can be opened, you also support queries on them
1907 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1908 * You may also want to support other common columns if you have additional meta-data
1909 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1910 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1911 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001912 * @param uri The data in the content provider being queried.
1913 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001914 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001915 * requirements; in this case the content provider will pick its best
1916 * type matching the pattern.
1917 * @param opts Additional options from the client. The definitions of
1918 * these are specific to the content provider being called.
1919 *
1920 * @return Returns a new AssetFileDescriptor from which the client can
1921 * read data of the desired type.
1922 *
1923 * @throws FileNotFoundException Throws FileNotFoundException if there is
1924 * no file associated with the given URI or the mode is invalid.
1925 * @throws SecurityException Throws SecurityException if the caller does
1926 * not have permission to access the data.
1927 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1928 * content provider does not support the requested MIME type.
1929 *
1930 * @see #getStreamTypes(Uri, String)
1931 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001932 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001933 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001934 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1935 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001936 if ("*/*".equals(mimeTypeFilter)) {
1937 // If they can take anything, the untyped open call is good enough.
1938 return openAssetFile(uri, "r");
1939 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001940 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001941 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001942 // Use old untyped open call if this provider has a type for this
1943 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001944 return openAssetFile(uri, "r");
1945 }
1946 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1947 }
1948
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001949
1950 /**
1951 * Called by a client to open a read-only stream containing data of a
1952 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1953 * except the file can only be read-only and the content provider may
1954 * perform data conversions to generate data of the desired type.
1955 *
1956 * <p>The default implementation compares the given mimeType against the
1957 * result of {@link #getType(Uri)} and, if they match, simply calls
1958 * {@link #openAssetFile(Uri, String)}.
1959 *
1960 * <p>See {@link ClipData} for examples of the use and implementation
1961 * of this method.
1962 * <p>
1963 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1964 * streaming of data.
1965 *
1966 * <p class="note">For better interoperability with other applications, it is recommended
1967 * that for any URIs that can be opened, you also support queries on them
1968 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1969 * You may also want to support other common columns if you have additional meta-data
1970 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1971 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1972 *
1973 * @param uri The data in the content provider being queried.
1974 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001975 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001976 * requirements; in this case the content provider will pick its best
1977 * type matching the pattern.
1978 * @param opts Additional options from the client. The definitions of
1979 * these are specific to the content provider being called.
1980 * @param signal A signal to cancel the operation in progress, or
1981 * {@code null} if none. For example, if you are downloading a
1982 * file from the network to service a "rw" mode request, you
1983 * should periodically call
1984 * {@link CancellationSignal#throwIfCanceled()} to check whether
1985 * the client has canceled the request and abort the download.
1986 *
1987 * @return Returns a new AssetFileDescriptor from which the client can
1988 * read data of the desired type.
1989 *
1990 * @throws FileNotFoundException Throws FileNotFoundException if there is
1991 * no file associated with the given URI or the mode is invalid.
1992 * @throws SecurityException Throws SecurityException if the caller does
1993 * not have permission to access the data.
1994 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1995 * content provider does not support the requested MIME type.
1996 *
1997 * @see #getStreamTypes(Uri, String)
1998 * @see #openAssetFile(Uri, String)
1999 * @see ClipDescription#compareMimeTypes(String, String)
2000 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002001 @Override
Jeff Sharkey673db442015-06-11 19:30:57 -07002002 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
2003 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
2004 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07002005 return openTypedAssetFile(uri, mimeTypeFilter, opts);
2006 }
2007
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002008 /**
2009 * Interface to write a stream of data to a pipe. Use with
2010 * {@link ContentProvider#openPipeHelper}.
2011 */
2012 public interface PipeDataWriter<T> {
2013 /**
2014 * Called from a background thread to stream data out to a pipe.
2015 * Note that the pipe is blocking, so this thread can block on
2016 * writes for an arbitrary amount of time if the client is slow
2017 * at reading.
2018 *
2019 * @param output The pipe where data should be written. This will be
2020 * closed for you upon returning from this function.
2021 * @param uri The URI whose data is to be written.
2022 * @param mimeType The desired type of data to be written.
2023 * @param opts Options supplied by caller.
2024 * @param args Your own custom arguments.
2025 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002026 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
2027 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002028 }
2029
2030 /**
2031 * A helper function for implementing {@link #openTypedAssetFile}, for
2032 * creating a data pipe and background thread allowing you to stream
2033 * generated data back to the client. This function returns a new
2034 * ParcelFileDescriptor that should be returned to the caller (the caller
2035 * is responsible for closing it).
2036 *
2037 * @param uri The URI whose data is to be written.
2038 * @param mimeType The desired type of data to be written.
2039 * @param opts Options supplied by caller.
2040 * @param args Your own custom arguments.
2041 * @param func Interface implementing the function that will actually
2042 * stream the data.
2043 * @return Returns a new ParcelFileDescriptor holding the read side of
2044 * the pipe. This should be returned to the caller for reading; the caller
2045 * is responsible for closing it when done.
2046 */
Jeff Sharkey673db442015-06-11 19:30:57 -07002047 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
2048 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
2049 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002050 try {
2051 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
2052
2053 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
2054 @Override
2055 protected Object doInBackground(Object... params) {
2056 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
2057 try {
2058 fds[1].close();
2059 } catch (IOException e) {
2060 Log.w(TAG, "Failure closing pipe", e);
2061 }
2062 return null;
2063 }
2064 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08002065 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07002066
2067 return fds[0];
2068 } catch (IOException e) {
2069 throw new FileNotFoundException("failure making pipe");
2070 }
2071 }
2072
2073 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 * Returns true if this instance is a temporary content provider.
2075 * @return true if this instance is a temporary content provider
2076 */
2077 protected boolean isTemporary() {
2078 return false;
2079 }
2080
2081 /**
2082 * Returns the Binder object for this provider.
2083 *
2084 * @return the Binder object for this provider
2085 * @hide
2086 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002087 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 public IContentProvider getIContentProvider() {
2089 return mTransport;
2090 }
2091
2092 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002093 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
2094 * when directly instantiating the provider for testing.
2095 * @hide
2096 */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002097 @UnsupportedAppUsage
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002098 public void attachInfoForTesting(Context context, ProviderInfo info) {
2099 attachInfo(context, info, true);
2100 }
2101
2102 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 * After being instantiated, this is called to tell the content provider
2104 * about itself.
2105 *
2106 * @param context The context this provider is running in
2107 * @param info Registered information about this content provider
2108 */
2109 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002110 attachInfo(context, info, false);
2111 }
2112
2113 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002114 mNoPerms = testing;
Jeff Sharkey497789e2019-02-15 19:41:30 -07002115 mCallingPackage = new ThreadLocal<>();
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08002116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 /*
2118 * Only allow it to be set once, so after the content service gives
2119 * this to us clients can't change it.
2120 */
2121 if (mContext == null) {
2122 mContext = context;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002123 if (context != null && mTransport != null) {
Jeff Sharkey10cb3122013-09-17 15:18:43 -07002124 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
2125 Context.APP_OPS_SERVICE);
2126 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002127 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 if (info != null) {
2129 setReadPermission(info.readPermission);
2130 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07002131 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07002132 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07002133 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002134 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 }
Jeff Sharkey22e834f2019-08-08 15:21:33 -06002136 if (Build.IS_DEBUGGABLE) {
2137 setTransportLoggingEnabled(Log.isLoggable(getClass().getSimpleName(),
2138 Log.VERBOSE));
2139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002140 ContentProvider.this.onCreate();
2141 }
2142 }
Fred Quintanace31b232009-05-04 16:01:15 -07002143
2144 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07002145 * Override this to handle requests to perform a batch of operations, or the
2146 * default implementation will iterate over the operations and call
2147 * {@link ContentProviderOperation#apply} on each of them.
2148 * If all calls to {@link ContentProviderOperation#apply} succeed
2149 * then a {@link ContentProviderResult} array with as many
2150 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002151 * fail, it is up to the implementation how many of the others take effect.
2152 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08002153 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
2154 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002155 *
Fred Quintanace31b232009-05-04 16:01:15 -07002156 * @param operations the operations to apply
2157 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07002158 * @throws OperationApplicationException thrown if any operation fails.
2159 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07002160 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002161 @Override
2162 public @NonNull ContentProviderResult[] applyBatch(@NonNull String authority,
2163 @NonNull ArrayList<ContentProviderOperation> operations)
2164 throws OperationApplicationException {
2165 return applyBatch(operations);
2166 }
2167
Jeff Sharkey673db442015-06-11 19:30:57 -07002168 public @NonNull ContentProviderResult[] applyBatch(
2169 @NonNull ArrayList<ContentProviderOperation> operations)
2170 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07002171 final int numOperations = operations.size();
2172 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
2173 for (int i = 0; i < numOperations; i++) {
2174 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07002175 }
2176 return results;
2177 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002178
2179 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002180 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002181 * interfaces that are cheaper and/or unnatural for a table-like
2182 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002183 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07002184 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
2185 * on this entry into the content provider besides the basic ability for the application
2186 * to get access to the provider at all. For example, it has no idea whether the call
2187 * being executed may read or write data in the provider, so can't enforce those
2188 * individual permissions. Any implementation of this method <strong>must</strong>
2189 * do its own permission checks on incoming calls to make sure they are allowed.</p>
2190 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08002191 * @param method method name to call. Opaque to framework, but should not be {@code null}.
2192 * @param arg provider-defined String argument. May be {@code null}.
2193 * @param extras provider-defined Bundle argument. May be {@code null}.
2194 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08002195 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002196 */
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002197 @Override
2198 public @Nullable Bundle call(@NonNull String authority, @NonNull String method,
2199 @Nullable String arg, @Nullable Bundle extras) {
2200 return call(method, arg, extras);
2201 }
2202
Jeff Sharkey673db442015-06-11 19:30:57 -07002203 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
2204 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002205 return null;
2206 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002207
2208 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002209 * Implement this to shut down the ContentProvider instance. You can then
2210 * invoke this method in unit tests.
Steve McKayea93fe72016-12-02 11:35:35 -08002211 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002212 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002213 * Android normally handles ContentProvider startup and shutdown
2214 * automatically. You do not need to start up or shut down a
2215 * ContentProvider. When you invoke a test method on a ContentProvider,
2216 * however, a ContentProvider instance is started and keeps running after
2217 * the test finishes, even if a succeeding test instantiates another
2218 * ContentProvider. A conflict develops because the two instances are
2219 * usually running against the same underlying data source (for example, an
2220 * sqlite database).
2221 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002222 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07002223 * Implementing shutDown() avoids this conflict by providing a way to
2224 * terminate the ContentProvider. This method can also prevent memory leaks
2225 * from multiple instantiations of the ContentProvider, and it can ensure
2226 * unit test isolation by allowing you to completely clean up the test
2227 * fixture before moving on to the next test.
2228 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07002229 */
2230 public void shutdown() {
2231 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
2232 "connections are gracefully shutdown");
2233 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08002234
2235 /**
2236 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07002237 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08002238 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08002239 * @param fd The raw file descriptor that the dump is being sent to.
2240 * @param writer The PrintWriter to which you should dump your state. This will be
2241 * closed for you after you return.
2242 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08002243 */
2244 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2245 writer.println("nothing to dump");
2246 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002247
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002248 private void validateIncomingAuthority(String authority) throws SecurityException {
2249 if (!matchesOurAuthorities(getAuthorityWithoutUserId(authority))) {
2250 String message = "The authority " + authority + " does not match the one of the "
2251 + "contentProvider: ";
2252 if (mAuthority != null) {
2253 message += mAuthority;
2254 } else {
2255 message += Arrays.toString(mAuthorities);
2256 }
2257 throw new SecurityException(message);
2258 }
2259 }
2260
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002261 /** @hide */
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002262 @VisibleForTesting
2263 public Uri validateIncomingUri(Uri uri) throws SecurityException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +01002264 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01002265 if (!mSingleUser) {
2266 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2267 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
2268 throw new SecurityException("trying to query a ContentProvider in user "
2269 + mContext.getUserId() + " with a uri belonging to user " + userId);
2270 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002271 }
Jeff Sharkey633a13e2018-12-07 12:00:45 -07002272 validateIncomingAuthority(auth);
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002273
2274 // Normalize the path by removing any empty path segments, which can be
2275 // a source of security issues.
2276 final String encodedPath = uri.getEncodedPath();
2277 if (encodedPath != null && encodedPath.indexOf("//") != -1) {
Jeff Sharkey4a7b6ac2018-10-03 10:33:46 -06002278 final Uri normalized = uri.buildUpon()
2279 .encodedPath(encodedPath.replaceAll("//+", "/")).build();
2280 Log.w(TAG, "Normalized " + uri + " to " + normalized
2281 + " to avoid possible security issues");
2282 return normalized;
Jeff Sharkeyc4156e02018-09-24 13:23:57 -06002283 } else {
2284 return uri;
2285 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002286 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002287
2288 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01002289 private Uri maybeGetUriWithoutUserId(Uri uri) {
2290 if (mSingleUser) {
2291 return uri;
2292 }
2293 return getUriWithoutUserId(uri);
2294 }
2295
2296 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002297 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
2298 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002299 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002300 if (end == -1) return defaultUserId;
2301 String userIdString = auth.substring(0, end);
2302 try {
2303 return Integer.parseInt(userIdString);
2304 } catch (NumberFormatException e) {
2305 Log.w(TAG, "Error parsing userId.", e);
2306 return UserHandle.USER_NULL;
2307 }
2308 }
2309
2310 /** @hide */
2311 public static int getUserIdFromAuthority(String auth) {
2312 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
2313 }
2314
2315 /** @hide */
2316 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
2317 if (uri == null) return defaultUserId;
2318 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
2319 }
2320
2321 /** @hide */
2322 public static int getUserIdFromUri(Uri uri) {
2323 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
2324 }
2325
2326 /**
2327 * Removes userId part from authority string. Expects format:
2328 * userId@some.authority
2329 * If there is no userId in the authority, it symply returns the argument
2330 * @hide
2331 */
2332 public static String getAuthorityWithoutUserId(String auth) {
2333 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01002334 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002335 return auth.substring(end+1);
2336 }
2337
2338 /** @hide */
2339 public static Uri getUriWithoutUserId(Uri uri) {
2340 if (uri == null) return null;
2341 Uri.Builder builder = uri.buildUpon();
2342 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
2343 return builder.build();
2344 }
2345
2346 /** @hide */
2347 public static boolean uriHasUserId(Uri uri) {
2348 if (uri == null) return false;
2349 return !TextUtils.isEmpty(uri.getUserInfo());
2350 }
2351
2352 /** @hide */
Mathew Inwood5c0d3542018-08-14 13:54:31 +01002353 @UnsupportedAppUsage
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002354 public static Uri maybeAddUserId(Uri uri, int userId) {
2355 if (uri == null) return null;
2356 if (userId != UserHandle.USER_CURRENT
Jason Monkd18651f2017-10-05 14:18:49 -04002357 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +01002358 if (!uriHasUserId(uri)) {
2359 //We don't add the user Id if there's already one
2360 Uri.Builder builder = uri.buildUpon();
2361 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
2362 return builder.build();
2363 }
2364 }
2365 return uri;
2366 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08002367}