blob: 49b58536b3edbd06ebbd35e8fe96f4e98e4a3090 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.content;
18
Nicolas Prevot504d78e2014-06-26 10:07:33 +010019import static android.Manifest.permission.INTERACT_ACROSS_USERS;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070020import static android.app.AppOpsManager.MODE_ALLOWED;
21import static android.app.AppOpsManager.MODE_ERRORED;
22import static android.app.AppOpsManager.MODE_IGNORED;
23import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070024
Jeff Sharkey673db442015-06-11 19:30:57 -070025import android.annotation.NonNull;
Scott Kennedy9f78f652015-03-01 15:29:25 -080026import android.annotation.Nullable;
Dianne Hackborn35654b62013-01-14 17:38:02 -080027import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070028import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.pm.ProviderInfo;
30import android.content.res.AssetFileDescriptor;
31import android.content.res.Configuration;
32import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070033import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.database.SQLException;
35import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070036import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080038import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070039import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080040import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070041import android.os.ICancellationSignal;
42import android.os.OperationCanceledException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070044import android.os.Process;
Ben Lin1cf454f2016-11-10 13:50:54 -080045import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070046import android.os.UserHandle;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010047import android.text.TextUtils;
Jeff Sharkey0e621c32015-07-24 15:10:20 -070048import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049
50import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080051import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070053import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080054import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070055import java.util.ArrayList;
Andreas Gampee6748ce2015-12-11 18:00:38 -080056import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057
58/**
59 * Content providers are one of the primary building blocks of Android applications, providing
60 * content to applications. They encapsulate data and provide it to applications through the single
61 * {@link ContentResolver} interface. A content provider is only required if you need to share
62 * data between multiple applications. For example, the contacts data is used by multiple
63 * applications and must be stored in a content provider. If you don't need to share data amongst
64 * multiple applications you can use a database directly via
65 * {@link android.database.sqlite.SQLiteDatabase}.
66 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 * <p>When a request is made via
68 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
69 * request to the content provider registered with the authority. The content provider can interpret
70 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
71 * URIs.</p>
72 *
73 * <p>The primary methods that need to be implemented are:
74 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070075 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 * <li>{@link #query} which returns data to the caller</li>
77 * <li>{@link #insert} which inserts new data into the content provider</li>
78 * <li>{@link #update} which updates existing data in the content provider</li>
79 * <li>{@link #delete} which deletes data from the content provider</li>
80 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
81 * </ul></p>
82 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070083 * <p class="caution">Data access methods (such as {@link #insert} and
84 * {@link #update}) may be called from many threads at once, and must be thread-safe.
85 * Other methods (such as {@link #onCreate}) are only called from the application
86 * main thread, and must avoid performing lengthy operations. See the method
87 * descriptions for their expected thread behavior.</p>
88 *
89 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
90 * ContentProvider instance, so subclasses don't have to worry about the details of
91 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070092 *
93 * <div class="special reference">
94 * <h3>Developer Guides</h3>
95 * <p>For more information about using content providers, read the
96 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
97 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -070099public abstract class ContentProvider implements ComponentCallbacks2 {
Vasu Nori0c9e14a2010-08-04 13:31:48 -0700100 private static final String TAG = "ContentProvider";
101
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900102 /*
103 * Note: if you add methods to ContentProvider, you must add similar methods to
104 * MockContentProvider.
105 */
106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700108 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100109
110 // Since most Providers have only one authority, we keep both a String and a String[] to improve
111 // performance.
112 private String mAuthority;
113 private String[] mAuthorities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 private String mReadPermission;
115 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700116 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700117 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800118 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700119 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700121 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<String>();
122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 private Transport mTransport = new Transport();
124
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700125 /**
126 * Construct a ContentProvider instance. Content providers must be
127 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
128 * in the manifest</a>, accessed with {@link ContentResolver}, and created
129 * automatically by the system, so applications usually do not create
130 * ContentProvider instances directly.
131 *
132 * <p>At construction time, the object is uninitialized, and most fields and
133 * methods are unavailable. Subclasses should initialize themselves in
134 * {@link #onCreate}, not the constructor.
135 *
136 * <p>Content providers are created on the application main thread at
137 * application launch time. The constructor must not perform lengthy
138 * operations, or application startup will be delayed.
139 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900140 public ContentProvider() {
141 }
142
143 /**
144 * Constructor just for mocking.
145 *
146 * @param context A Context object which should be some mock instance (like the
147 * instance of {@link android.test.mock.MockContext}).
148 * @param readPermission The read permision you want this instance should have in the
149 * test, which is available via {@link #getReadPermission()}.
150 * @param writePermission The write permission you want this instance should have
151 * in the test, which is available via {@link #getWritePermission()}.
152 * @param pathPermissions The PathPermissions you want this instance should have
153 * in the test, which is available via {@link #getPathPermissions()}.
154 * @hide
155 */
156 public ContentProvider(
157 Context context,
158 String readPermission,
159 String writePermission,
160 PathPermission[] pathPermissions) {
161 mContext = context;
162 mReadPermission = readPermission;
163 mWritePermission = writePermission;
164 mPathPermissions = pathPermissions;
165 }
166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 /**
168 * Given an IContentProvider, try to coerce it back to the real
169 * ContentProvider object if it is running in the local process. This can
170 * be used if you know you are running in the same process as a provider,
171 * and want to get direct access to its implementation details. Most
172 * clients should not nor have a reason to use it.
173 *
174 * @param abstractInterface The ContentProvider interface that is to be
175 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800176 * @return If the IContentProvider is non-{@code null} and local, returns its actual
177 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 * @hide
179 */
180 public static ContentProvider coerceToLocalContentProvider(
181 IContentProvider abstractInterface) {
182 if (abstractInterface instanceof Transport) {
183 return ((Transport)abstractInterface).getContentProvider();
184 }
185 return null;
186 }
187
188 /**
189 * Binder object that deals with remoting.
190 *
191 * @hide
192 */
193 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800194 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800195 int mReadOp = AppOpsManager.OP_NONE;
196 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 ContentProvider getContentProvider() {
199 return ContentProvider.this;
200 }
201
Jeff Brownd2183652011-10-09 12:39:53 -0700202 @Override
203 public String getProviderName() {
204 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 }
206
Jeff Brown75ea64f2012-01-25 19:37:13 -0800207 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800208 public Cursor query(String callingPkg, Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800209 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800210 ICancellationSignal cancellationSignal) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100211 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100212 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800213 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700214 // The caller has no access to the data, so return an empty cursor with
215 // the columns in the requested order. The caller may ask for an invalid
216 // column and we would not catch that but this is not a problem in practice.
217 // We do not call ContentProvider#query with a modified where clause since
218 // the implementation is not guaranteed to be backed by a SQL database, hence
219 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700220 if (projection != null) {
221 return new MatrixCursor(projection, 0);
222 }
223
224 // Null projection means all columns but we have no idea which they are.
225 // However, the caller may be expecting to access them my index. Hence,
226 // we have to execute the query as if allowed to get a cursor with the
227 // columns. We then use the column names to return an empty cursor.
228 Cursor cursor = ContentProvider.this.query(uri, projection, selection,
229 selectionArgs, sortOrder, CancellationSignal.fromTransport(
230 cancellationSignal));
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700231 if (cursor == null) {
232 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700233 }
234
235 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700236 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800237 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700238 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700239 try {
240 return ContentProvider.this.query(
241 uri, projection, selection, selectionArgs, sortOrder,
242 CancellationSignal.fromTransport(cancellationSignal));
243 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700244 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 }
247
Jeff Brown75ea64f2012-01-25 19:37:13 -0800248 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100250 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100251 uri = maybeGetUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 return ContentProvider.this.getType(uri);
253 }
254
Jeff Brown75ea64f2012-01-25 19:37:13 -0800255 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800256 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100257 validateIncomingUri(uri);
258 int userId = getUserIdFromUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100259 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800260 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800261 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800262 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700263 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700264 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100265 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700266 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700267 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 }
270
Jeff Brown75ea64f2012-01-25 19:37:13 -0800271 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800272 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100273 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100274 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800275 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800276 return 0;
277 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700278 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700279 try {
280 return ContentProvider.this.bulkInsert(uri, initialValues);
281 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700282 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 }
285
Jeff Brown75ea64f2012-01-25 19:37:13 -0800286 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800287 public ContentProviderResult[] applyBatch(String callingPkg,
288 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700289 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100290 int numOperations = operations.size();
291 final int[] userIds = new int[numOperations];
292 for (int i = 0; i < numOperations; i++) {
293 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100294 Uri uri = operation.getUri();
295 validateIncomingUri(uri);
296 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100297 if (userIds[i] != UserHandle.USER_CURRENT) {
298 // Removing the user id from the uri.
299 operation = new ContentProviderOperation(operation, true);
300 operations.set(i, operation);
301 }
Fred Quintana89437372009-05-15 15:10:40 -0700302 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800303 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800304 != AppOpsManager.MODE_ALLOWED) {
305 throw new OperationApplicationException("App op not allowed", 0);
306 }
Fred Quintana89437372009-05-15 15:10:40 -0700307 }
Fred Quintana89437372009-05-15 15:10:40 -0700308 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800309 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800310 != AppOpsManager.MODE_ALLOWED) {
311 throw new OperationApplicationException("App op not allowed", 0);
312 }
Fred Quintana89437372009-05-15 15:10:40 -0700313 }
314 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700315 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700316 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100317 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800318 if (results != null) {
319 for (int i = 0; i < results.length ; i++) {
320 if (userIds[i] != UserHandle.USER_CURRENT) {
321 // Adding the userId to the uri.
322 results[i] = new ContentProviderResult(results[i], userIds[i]);
323 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100324 }
325 }
326 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700327 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700328 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700329 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700330 }
331
Jeff Brown75ea64f2012-01-25 19:37:13 -0800332 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800333 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100334 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100335 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800336 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800337 return 0;
338 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700339 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700340 try {
341 return ContentProvider.this.delete(uri, selection, selectionArgs);
342 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700343 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 }
346
Jeff Brown75ea64f2012-01-25 19:37:13 -0800347 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800348 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100350 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100351 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800352 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800353 return 0;
354 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700355 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700356 try {
357 return ContentProvider.this.update(uri, values, selection, selectionArgs);
358 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700359 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 }
362
Jeff Brown75ea64f2012-01-25 19:37:13 -0800363 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700364 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800365 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
366 IBinder callerToken) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100367 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100368 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800369 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700370 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700371 try {
372 return ContentProvider.this.openFile(
373 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
374 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700375 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 }
378
Jeff Brown75ea64f2012-01-25 19:37:13 -0800379 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700380 public AssetFileDescriptor openAssetFile(
381 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100383 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100384 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800385 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700386 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700387 try {
388 return ContentProvider.this.openAssetFile(
389 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
390 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700391 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393 }
394
Jeff Brown75ea64f2012-01-25 19:37:13 -0800395 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800396 public Bundle call(
397 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600398 Bundle.setDefusable(extras, true);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700399 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700400 try {
401 return ContentProvider.this.call(method, arg, extras);
402 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700403 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700404 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800405 }
406
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700407 @Override
408 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100409 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100410 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700411 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
412 }
413
414 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800415 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700416 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Jeff Sharkeya04c7a72016-03-18 12:20:36 -0600417 Bundle.setDefusable(opts, true);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100418 validateIncomingUri(uri);
Robin Lee2ab02e22016-07-28 18:41:23 +0100419 uri = maybeGetUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800420 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700421 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700422 try {
423 return ContentProvider.this.openTypedAssetFile(
424 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
425 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700426 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700427 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700428 }
429
Jeff Brown75ea64f2012-01-25 19:37:13 -0800430 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700431 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800432 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800433 }
434
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700435 @Override
436 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100437 validateIncomingUri(uri);
438 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100439 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800440 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700441 return null;
442 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700443 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700444 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100445 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700446 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700447 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700448 }
449 }
450
451 @Override
452 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100453 validateIncomingUri(uri);
454 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100455 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800456 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700457 return null;
458 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700459 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700460 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100461 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700462 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700463 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700464 }
465 }
466
Ben Lin1cf454f2016-11-10 13:50:54 -0800467 @Override
468 public boolean refresh(String callingPkg, Uri uri, Bundle args,
469 ICancellationSignal cancellationSignal) throws RemoteException {
470 validateIncomingUri(uri);
471 uri = getUriWithoutUserId(uri);
472 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
473 return false;
474 }
475 final String original = setCallingPackage(callingPkg);
476 try {
477 return ContentProvider.this.refresh(uri, args,
478 CancellationSignal.fromTransport(cancellationSignal));
479 } finally {
480 setCallingPackage(original);
481 }
482 }
483
Dianne Hackbornff170242014-11-19 10:59:01 -0800484 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
485 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800486 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800487 if (enforceWritePermission(callingPkg, uri, callerToken)
488 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800489 throw new FileNotFoundException("App op not allowed");
490 }
491 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800492 if (enforceReadPermission(callingPkg, uri, callerToken)
493 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800494 throw new FileNotFoundException("App op not allowed");
495 }
496 }
497 }
498
Dianne Hackbornff170242014-11-19 10:59:01 -0800499 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
500 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700501 final int mode = enforceReadPermissionInner(uri, callingPkg, callerToken);
502 if (mode != MODE_ALLOWED) {
503 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800504 }
Svet Ganov99b60432015-06-27 13:15:22 -0700505
506 if (mReadOp != AppOpsManager.OP_NONE) {
507 return mAppOpsManager.noteProxyOp(mReadOp, callingPkg);
508 }
509
Dianne Hackborn35654b62013-01-14 17:38:02 -0800510 return AppOpsManager.MODE_ALLOWED;
511 }
512
Dianne Hackbornff170242014-11-19 10:59:01 -0800513 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
514 throws SecurityException {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700515 final int mode = enforceWritePermissionInner(uri, callingPkg, callerToken);
516 if (mode != MODE_ALLOWED) {
517 return mode;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800518 }
Svet Ganov99b60432015-06-27 13:15:22 -0700519
520 if (mWriteOp != AppOpsManager.OP_NONE) {
521 return mAppOpsManager.noteProxyOp(mWriteOp, callingPkg);
522 }
523
Dianne Hackborn35654b62013-01-14 17:38:02 -0800524 return AppOpsManager.MODE_ALLOWED;
525 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700526 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800527
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100528 boolean checkUser(int pid, int uid, Context context) {
529 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700530 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100531 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
532 == PERMISSION_GRANTED;
533 }
534
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700535 /**
536 * Verify that calling app holds both the given permission and any app-op
537 * associated with that permission.
538 */
539 private int checkPermissionAndAppOp(String permission, String callingPkg,
540 IBinder callerToken) {
541 if (getContext().checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid(),
542 callerToken) != PERMISSION_GRANTED) {
543 return MODE_ERRORED;
544 }
545
546 final int permOp = AppOpsManager.permissionToOpCode(permission);
547 if (permOp != AppOpsManager.OP_NONE) {
548 return mTransport.mAppOpsManager.noteProxyOp(permOp, callingPkg);
549 }
550
551 return MODE_ALLOWED;
552 }
553
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700554 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700555 protected int enforceReadPermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800556 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700557 final Context context = getContext();
558 final int pid = Binder.getCallingPid();
559 final int uid = Binder.getCallingUid();
560 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700561 int strongestMode = MODE_ALLOWED;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700562
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700563 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700564 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700565 }
566
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100567 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700568 final String componentPerm = getReadPermission();
569 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700570 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
571 if (mode == MODE_ALLOWED) {
572 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700573 } else {
574 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700575 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700576 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700577 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700578
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700579 // track if unprotected read is allowed; any denied
580 // <path-permission> below removes this ability
581 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700582
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700583 final PathPermission[] pps = getPathPermissions();
584 if (pps != null) {
585 final String path = uri.getPath();
586 for (PathPermission pp : pps) {
587 final String pathPerm = pp.getReadPermission();
588 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700589 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
590 if (mode == MODE_ALLOWED) {
591 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700592 } else {
593 // any denied <path-permission> means we lose
594 // default <provider> access.
595 allowDefaultRead = false;
596 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700597 strongestMode = Math.max(strongestMode, mode);
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700598 }
599 }
600 }
601 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700602
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700603 // if we passed <path-permission> checks above, and no default
604 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700605 if (allowDefaultRead) return MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700607
608 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800609 final int callingUserId = UserHandle.getUserId(uid);
610 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
611 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800612 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
613 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700614 return MODE_ALLOWED;
615 }
616
617 // If the worst denial we found above was ignored, then pass that
618 // ignored through; otherwise we assume it should be a real error below.
619 if (strongestMode == MODE_IGNORED) {
620 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700621 }
622
623 final String failReason = mExported
624 ? " requires " + missingPerm + ", or grantUriPermission()"
625 : " requires the provider be exported, or grantUriPermission()";
626 throw new SecurityException("Permission Denial: reading "
627 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
628 + ", uid=" + uid + failReason);
629 }
630
631 /** {@hide} */
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700632 protected int enforceWritePermissionInner(Uri uri, String callingPkg, IBinder callerToken)
Dianne Hackbornff170242014-11-19 10:59:01 -0800633 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700634 final Context context = getContext();
635 final int pid = Binder.getCallingPid();
636 final int uid = Binder.getCallingUid();
637 String missingPerm = null;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700638 int strongestMode = MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700639
640 if (UserHandle.isSameApp(uid, mMyUid)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700641 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700642 }
643
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100644 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700645 final String componentPerm = getWritePermission();
646 if (componentPerm != null) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700647 final int mode = checkPermissionAndAppOp(componentPerm, callingPkg, callerToken);
648 if (mode == MODE_ALLOWED) {
649 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700650 } else {
651 missingPerm = componentPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700652 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700653 }
654 }
655
656 // track if unprotected write is allowed; any denied
657 // <path-permission> below removes this ability
658 boolean allowDefaultWrite = (componentPerm == null);
659
660 final PathPermission[] pps = getPathPermissions();
661 if (pps != null) {
662 final String path = uri.getPath();
663 for (PathPermission pp : pps) {
664 final String pathPerm = pp.getWritePermission();
665 if (pathPerm != null && pp.match(path)) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700666 final int mode = checkPermissionAndAppOp(pathPerm, callingPkg, callerToken);
667 if (mode == MODE_ALLOWED) {
668 return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700669 } else {
670 // any denied <path-permission> means we lose
671 // default <provider> access.
672 allowDefaultWrite = false;
673 missingPerm = pathPerm;
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700674 strongestMode = Math.max(strongestMode, mode);
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700675 }
676 }
677 }
678 }
679
680 // if we passed <path-permission> checks above, and no default
681 // <provider> permission, then allow access.
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700682 if (allowDefaultWrite) return MODE_ALLOWED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700683 }
684
685 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800686 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
687 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey0e621c32015-07-24 15:10:20 -0700688 return MODE_ALLOWED;
689 }
690
691 // If the worst denial we found above was ignored, then pass that
692 // ignored through; otherwise we assume it should be a real error below.
693 if (strongestMode == MODE_IGNORED) {
694 return MODE_IGNORED;
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700695 }
696
697 final String failReason = mExported
698 ? " requires " + missingPerm + ", or grantUriPermission()"
699 : " requires the provider be exported, or grantUriPermission()";
700 throw new SecurityException("Permission Denial: writing "
701 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
702 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 }
704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700706 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800707 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 * constructor.
709 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700710 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 return mContext;
712 }
713
714 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700715 * Set the calling package, returning the current value (or {@code null})
716 * which can be used later to restore the previous state.
717 */
718 private String setCallingPackage(String callingPackage) {
719 final String original = mCallingPackage.get();
720 mCallingPackage.set(callingPackage);
721 return original;
722 }
723
724 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700725 * Return the package name of the caller that initiated the request being
726 * processed on the current thread. The returned package will have been
727 * verified to belong to the calling UID. Returns {@code null} if not
728 * currently processing a request.
729 * <p>
730 * This will always return {@code null} when processing
731 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
732 *
733 * @see Binder#getCallingUid()
734 * @see Context#grantUriPermission(String, Uri, int)
735 * @throws SecurityException if the calling package doesn't belong to the
736 * calling UID.
737 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700738 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700739 final String pkg = mCallingPackage.get();
740 if (pkg != null) {
741 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
742 }
743 return pkg;
744 }
745
746 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100747 * Change the authorities of the ContentProvider.
748 * This is normally set for you from its manifest information when the provider is first
749 * created.
750 * @hide
751 * @param authorities the semi-colon separated authorities of the ContentProvider.
752 */
753 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100754 if (authorities != null) {
755 if (authorities.indexOf(';') == -1) {
756 mAuthority = authorities;
757 mAuthorities = null;
758 } else {
759 mAuthority = null;
760 mAuthorities = authorities.split(";");
761 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100762 }
763 }
764
765 /** @hide */
766 protected final boolean matchesOurAuthorities(String authority) {
767 if (mAuthority != null) {
768 return mAuthority.equals(authority);
769 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100770 if (mAuthorities != null) {
771 int length = mAuthorities.length;
772 for (int i = 0; i < length; i++) {
773 if (mAuthorities[i].equals(authority)) return true;
774 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100775 }
776 return false;
777 }
778
779
780 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 * Change the permission required to read data from the content
782 * provider. This is normally set for you from its manifest information
783 * when the provider is first created.
784 *
785 * @param permission Name of the permission required for read-only access.
786 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700787 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 mReadPermission = permission;
789 }
790
791 /**
792 * Return the name of the permission required for read-only access to
793 * this content provider. This method can be called from multiple
794 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800795 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
796 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700798 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 return mReadPermission;
800 }
801
802 /**
803 * Change the permission required to read and write data in the content
804 * provider. This is normally set for you from its manifest information
805 * when the provider is first created.
806 *
807 * @param permission Name of the permission required for read/write access.
808 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700809 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 mWritePermission = permission;
811 }
812
813 /**
814 * Return the name of the permission required for read/write access to
815 * this content provider. This method can be called from multiple
816 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800817 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
818 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700820 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 return mWritePermission;
822 }
823
824 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700825 * Change the path-based permission required to read and/or write data in
826 * the content provider. This is normally set for you from its manifest
827 * information when the provider is first created.
828 *
829 * @param permissions Array of path permission descriptions.
830 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700831 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700832 mPathPermissions = permissions;
833 }
834
835 /**
836 * Return the path-based permissions required for read and/or write access to
837 * this content provider. This method can be called from multiple
838 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800839 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
840 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700841 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700842 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700843 return mPathPermissions;
844 }
845
Dianne Hackborn35654b62013-01-14 17:38:02 -0800846 /** @hide */
847 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800848 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800849 mTransport.mReadOp = readOp;
850 mTransport.mWriteOp = writeOp;
851 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800852 }
853
Dianne Hackborn961321f2013-02-05 17:22:41 -0800854 /** @hide */
855 public AppOpsManager getAppOpsManager() {
856 return mTransport.mAppOpsManager;
857 }
858
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700859 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700860 * Implement this to initialize your content provider on startup.
861 * This method is called for all registered content providers on the
862 * application main thread at application launch time. It must not perform
863 * lengthy operations, or application startup will be delayed.
864 *
865 * <p>You should defer nontrivial initialization (such as opening,
866 * upgrading, and scanning databases) until the content provider is used
867 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
868 * keeps application startup fast, avoids unnecessary work if the provider
869 * turns out not to be needed, and stops database errors (such as a full
870 * disk) from halting application launch.
871 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700872 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700873 * is a helpful utility class that makes it easy to manage databases,
874 * and will automatically defer opening until first use. If you do use
875 * SQLiteOpenHelper, make sure to avoid calling
876 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
877 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
878 * from this method. (Instead, override
879 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
880 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 *
882 * @return true if the provider was successfully loaded, false otherwise
883 */
884 public abstract boolean onCreate();
885
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700886 /**
887 * {@inheritDoc}
888 * This method is always called on the application main thread, and must
889 * not perform lengthy operations.
890 *
891 * <p>The default content provider implementation does nothing.
892 * Override this method to take appropriate action.
893 * (Content providers do not usually care about things like screen
894 * orientation, but may want to know about locale changes.)
895 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 public void onConfigurationChanged(Configuration newConfig) {
897 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700898
899 /**
900 * {@inheritDoc}
901 * This method is always called on the application main thread, and must
902 * not perform lengthy operations.
903 *
904 * <p>The default content provider implementation does nothing.
905 * Subclasses may override this method to take appropriate action.
906 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 public void onLowMemory() {
908 }
909
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700910 public void onTrimMemory(int level) {
911 }
912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700914 * Implement this to handle query requests from clients.
915 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800916 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
917 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 * <p>
919 * Example client call:<p>
920 * <pre>// Request a specific record.
921 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000922 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 projection, // Which columns to return.
924 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000925 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 People.NAME + " ASC"); // Sort order.</pre>
927 * Example implementation:<p>
928 * <pre>// SQLiteQueryBuilder is a helper class that creates the
929 // proper SQL syntax for us.
930 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
931
932 // Set the table we're querying.
933 qBuilder.setTables(DATABASE_TABLE_NAME);
934
935 // If the query ends in a specific record number, we're
936 // being asked for a specific record, so set the
937 // WHERE clause in our query.
938 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
939 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
940 }
941
942 // Make the query.
943 Cursor c = qBuilder.query(mDb,
944 projection,
945 selection,
946 selectionArgs,
947 groupBy,
948 having,
949 sortOrder);
950 c.setNotificationUri(getContext().getContentResolver(), uri);
951 return c;</pre>
952 *
953 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000954 * if the client is requesting a specific record, the URI will end in a record number
955 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
956 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800958 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800960 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000961 * @param selectionArgs You may include ?s in selection, which will be replaced by
962 * the values from selectionArgs, in order that they appear in the selection.
963 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800965 * If {@code null} then the provider is free to define the sort order.
966 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700968 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
969 @Nullable String selection, @Nullable String[] selectionArgs,
970 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971
Fred Quintana5bba6322009-10-05 14:21:12 -0700972 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800973 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800974 * This method can be called from multiple threads, as described in
975 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
976 * and Threads</a>.
977 * <p>
978 * Example client call:<p>
979 * <pre>// Request a specific record.
980 * Cursor managedCursor = managedQuery(
981 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
982 projection, // Which columns to return.
983 null, // WHERE clause.
984 null, // WHERE clause value substitution
985 People.NAME + " ASC"); // Sort order.</pre>
986 * Example implementation:<p>
987 * <pre>// SQLiteQueryBuilder is a helper class that creates the
988 // proper SQL syntax for us.
989 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
990
991 // Set the table we're querying.
992 qBuilder.setTables(DATABASE_TABLE_NAME);
993
994 // If the query ends in a specific record number, we're
995 // being asked for a specific record, so set the
996 // WHERE clause in our query.
997 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
998 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
999 }
1000
1001 // Make the query.
1002 Cursor c = qBuilder.query(mDb,
1003 projection,
1004 selection,
1005 selectionArgs,
1006 groupBy,
1007 having,
1008 sortOrder);
1009 c.setNotificationUri(getContext().getContentResolver(), uri);
1010 return c;</pre>
1011 * <p>
1012 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -08001013 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
1014 * signal to ensure correct operation on older versions of the Android Framework in
1015 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001016 *
1017 * @param uri The URI to query. This will be the full URI sent by the client;
1018 * if the client is requesting a specific record, the URI will end in a record number
1019 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
1020 * that _id value.
1021 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001022 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001023 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001024 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001025 * @param selectionArgs You may include ?s in selection, which will be replaced by
1026 * the values from selectionArgs, in order that they appear in the selection.
1027 * The values will be bound as Strings.
1028 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001029 * If {@code null} then the provider is free to define the sort order.
1030 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001031 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
1032 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001033 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -08001034 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001035 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
1036 @Nullable String selection, @Nullable String[] selectionArgs,
1037 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -08001038 return query(uri, projection, selection, selectionArgs, sortOrder);
1039 }
1040
1041 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001042 * Implement this to handle requests for the MIME type of the data at the
1043 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 * <code>vnd.android.cursor.item</code> for a single record,
1045 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001046 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001047 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1048 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07001050 * <p>Note that there are no permissions needed for an application to
1051 * access this information; if your content provider requires read and/or
1052 * write permissions, or is not exported, all applications can still call
1053 * this method regardless of their access permissions. This allows them
1054 * to retrieve the MIME type for a URI when dispatching intents.
1055 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001057 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001059 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060
1061 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001062 * Implement this to support canonicalization of URIs that refer to your
1063 * content provider. A canonical URI is one that can be transported across
1064 * devices, backup/restore, and other contexts, and still be able to refer
1065 * to the same data item. Typically this is implemented by adding query
1066 * params to the URI allowing the content provider to verify that an incoming
1067 * canonical URI references the same data as it was originally intended for and,
1068 * if it doesn't, to find that data (if it exists) in the current environment.
1069 *
1070 * <p>For example, if the content provider holds people and a normal URI in it
1071 * is created with a row index into that people database, the cananical representation
1072 * may have an additional query param at the end which specifies the name of the
1073 * person it is intended for. Later calls into the provider with that URI will look
1074 * up the row of that URI's base index and, if it doesn't match or its entry's
1075 * name doesn't match the name in the query param, perform a query on its database
1076 * to find the correct row to operate on.</p>
1077 *
1078 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1079 * URIs (including this one) must perform this verification and recovery of any
1080 * canonical URIs they receive. In addition, you must also implement
1081 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1082 *
1083 * <p>The default implementation of this method returns null, indicating that
1084 * canonical URIs are not supported.</p>
1085 *
1086 * @param url The Uri to canonicalize.
1087 *
1088 * @return Return the canonical representation of <var>url</var>, or null if
1089 * canonicalization of that Uri is not supported.
1090 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001091 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001092 return null;
1093 }
1094
1095 /**
1096 * Remove canonicalization from canonical URIs previously returned by
1097 * {@link #canonicalize}. For example, if your implementation is to add
1098 * a query param to canonicalize a URI, this method can simply trip any
1099 * query params on the URI. The default implementation always returns the
1100 * same <var>url</var> that was passed in.
1101 *
1102 * @param url The Uri to remove any canonicalization from.
1103 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001104 * @return Return the non-canonical representation of <var>url</var>, return
1105 * the <var>url</var> as-is if there is nothing to do, or return null if
1106 * the data identified by the canonical representation can not be found in
1107 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001108 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001109 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001110 return url;
1111 }
1112
1113 /**
Ben Lin1cf454f2016-11-10 13:50:54 -08001114 * Implement this to support refresh of content identified by {@code uri}. By default, this
1115 * method returns false; providers who wish to implement this should return true to signal the
1116 * client that the provider has tried refreshing with its own implementation.
1117 * <p>
1118 * This allows clients to request an explicit refresh of content identified by {@code uri}.
1119 * <p>
1120 * Client code should only invoke this method when there is a strong indication (such as a user
1121 * initiated pull to refresh gesture) that the content is stale.
1122 * <p>
1123 * Remember to send {@link ContentResolver#notifyChange(Uri, android.database.ContentObserver)}
1124 * notifications when content changes.
1125 *
1126 * @param uri The Uri identifying the data to refresh.
1127 * @param args Additional options from the client. The definitions of these are specific to the
1128 * content provider being called.
1129 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if
1130 * none. For example, if you called refresh on a particular uri, you should call
1131 * {@link CancellationSignal#throwIfCanceled()} to check whether the client has
1132 * canceled the refresh request.
1133 * @return true if the provider actually tried refreshing.
1134 * @hide
1135 */
1136 public boolean refresh(Uri uri, @Nullable Bundle args,
1137 @Nullable CancellationSignal cancellationSignal) {
1138 return false;
1139 }
1140
1141 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001142 * @hide
1143 * Implementation when a caller has performed an insert on the content
1144 * provider, but that call has been rejected for the operation given
1145 * to {@link #setAppOps(int, int)}. The default implementation simply
1146 * returns a dummy URI that is the base URI with a 0 path element
1147 * appended.
1148 */
1149 public Uri rejectInsert(Uri uri, ContentValues values) {
1150 // If not allowed, we need to return some reasonable URI. Maybe the
1151 // content provider should be responsible for this, but for now we
1152 // will just return the base URI with a dummy '0' tagged on to it.
1153 // You shouldn't be able to read if you can't write, anyway, so it
1154 // shouldn't matter much what is returned.
1155 return uri.buildUpon().appendPath("0").build();
1156 }
1157
1158 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001159 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1161 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001162 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001163 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1164 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001165 * @param uri The content:// URI of the insertion request. This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001167 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 * @return The URI for the newly inserted item.
1169 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001170 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171
1172 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001173 * Override this to handle requests to insert a set of new rows, or the
1174 * default implementation will iterate over the values and call
1175 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1177 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001178 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001179 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1180 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 *
1182 * @param uri The content:// URI of the insertion request.
1183 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001184 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 * @return The number of values that were inserted.
1186 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001187 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 int numValues = values.length;
1189 for (int i = 0; i < numValues; i++) {
1190 insert(uri, values[i]);
1191 }
1192 return numValues;
1193 }
1194
1195 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001196 * Implement this to handle requests to delete one or more rows.
1197 * The implementation should apply the selection clause when performing
1198 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001199 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001201 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001202 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1203 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 *
1205 * <p>The implementation is responsible for parsing out a row ID at the end
1206 * of the URI, if a specific row is being deleted. That is, the client would
1207 * pass in <code>content://contacts/people/22</code> and the implementation is
1208 * responsible for parsing the record number (22) when creating a SQL statement.
1209 *
1210 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1211 * @param selection An optional restriction to apply to rows when deleting.
1212 * @return The number of rows affected.
1213 * @throws SQLException
1214 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001215 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1216 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217
1218 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001219 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001220 * The implementation should update all rows matching the selection
1221 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1223 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001224 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001225 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1226 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 *
1228 * @param uri The URI to query. This can potentially have a record ID if this
1229 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001230 * @param values A set of column_name/value pairs to update in the database.
1231 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 * @param selection An optional filter to match rows to update.
1233 * @return the number of rows affected.
1234 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001235 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001236 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237
1238 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001239 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001240 * The default implementation always throws {@link FileNotFoundException}.
1241 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001242 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1243 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001244 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001245 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1246 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001247 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 *
1249 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1250 * their responsibility to close it when done. That is, the implementation
1251 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001252 * <p>
1253 * If opened with the exclusive "r" or "w" modes, the returned
1254 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1255 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1256 * supports seeking.
1257 * <p>
1258 * If you need to detect when the returned ParcelFileDescriptor has been
1259 * closed, or if the remote process has crashed or encountered some other
1260 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1261 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1262 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1263 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001265 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1266 * to return the appropriate MIME type for the data returned here with
1267 * the same URI. This will allow intent resolution to automatically determine the data MIME
1268 * type and select the appropriate matching targets as part of its operation.</p>
1269 *
1270 * <p class="note">For better interoperability with other applications, it is recommended
1271 * that for any URIs that can be opened, you also support queries on them
1272 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1273 * You may also want to support other common columns if you have additional meta-data
1274 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1275 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1276 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 * @param uri The URI whose file is to be opened.
1278 * @param mode Access mode for the file. May be "r" for read-only access,
1279 * "rw" for read and write access, or "rwt" for read and write access
1280 * that truncates any existing file.
1281 *
1282 * @return Returns a new ParcelFileDescriptor which you can use to access
1283 * the file.
1284 *
1285 * @throws FileNotFoundException Throws FileNotFoundException if there is
1286 * no file associated with the given URI or the mode is invalid.
1287 * @throws SecurityException Throws SecurityException if the caller does
1288 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001289 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 * @see #openAssetFile(Uri, String)
1291 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001292 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001293 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001294 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001295 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 throws FileNotFoundException {
1297 throw new FileNotFoundException("No files supported by provider at "
1298 + uri);
1299 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001302 * Override this to handle requests to open a file blob.
1303 * The default implementation always throws {@link FileNotFoundException}.
1304 * This method can be called from multiple threads, as described in
1305 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1306 * and Threads</a>.
1307 *
1308 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1309 * to the caller. This way large data (such as images and documents) can be
1310 * returned without copying the content.
1311 *
1312 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1313 * their responsibility to close it when done. That is, the implementation
1314 * of this method should create a new ParcelFileDescriptor for each call.
1315 * <p>
1316 * If opened with the exclusive "r" or "w" modes, the returned
1317 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1318 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1319 * supports seeking.
1320 * <p>
1321 * If you need to detect when the returned ParcelFileDescriptor has been
1322 * closed, or if the remote process has crashed or encountered some other
1323 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1324 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1325 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1326 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1327 *
1328 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1329 * to return the appropriate MIME type for the data returned here with
1330 * the same URI. This will allow intent resolution to automatically determine the data MIME
1331 * type and select the appropriate matching targets as part of its operation.</p>
1332 *
1333 * <p class="note">For better interoperability with other applications, it is recommended
1334 * that for any URIs that can be opened, you also support queries on them
1335 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1336 * You may also want to support other common columns if you have additional meta-data
1337 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1338 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1339 *
1340 * @param uri The URI whose file is to be opened.
1341 * @param mode Access mode for the file. May be "r" for read-only access,
1342 * "w" for write-only access, "rw" for read and write access, or
1343 * "rwt" for read and write access that truncates any existing
1344 * file.
1345 * @param signal A signal to cancel the operation in progress, or
1346 * {@code null} if none. For example, if you are downloading a
1347 * file from the network to service a "rw" mode request, you
1348 * should periodically call
1349 * {@link CancellationSignal#throwIfCanceled()} to check whether
1350 * the client has canceled the request and abort the download.
1351 *
1352 * @return Returns a new ParcelFileDescriptor which you can use to access
1353 * the file.
1354 *
1355 * @throws FileNotFoundException Throws FileNotFoundException if there is
1356 * no file associated with the given URI or the mode is invalid.
1357 * @throws SecurityException Throws SecurityException if the caller does
1358 * not have permission to access the file.
1359 *
1360 * @see #openAssetFile(Uri, String)
1361 * @see #openFileHelper(Uri, String)
1362 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001363 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001364 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001365 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1366 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001367 return openFile(uri, mode);
1368 }
1369
1370 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 * This is like {@link #openFile}, but can be implemented by providers
1372 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001373 * inside of their .apk.
1374 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001375 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1376 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001377 *
1378 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001379 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001380 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1382 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1383 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001384 * <p>
1385 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1386 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001387 *
1388 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 * should create the AssetFileDescriptor with
1390 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001391 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001393 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1394 * to return the appropriate MIME type for the data returned here with
1395 * the same URI. This will allow intent resolution to automatically determine the data MIME
1396 * type and select the appropriate matching targets as part of its operation.</p>
1397 *
1398 * <p class="note">For better interoperability with other applications, it is recommended
1399 * that for any URIs that can be opened, you also support queries on them
1400 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1401 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 * @param uri The URI whose file is to be opened.
1403 * @param mode Access mode for the file. May be "r" for read-only access,
1404 * "w" for write-only access (erasing whatever data is currently in
1405 * the file), "wa" for write-only access to append to any existing data,
1406 * "rw" for read and write access on any existing data, and "rwt" for read
1407 * and write access that truncates any existing file.
1408 *
1409 * @return Returns a new AssetFileDescriptor which you can use to access
1410 * the file.
1411 *
1412 * @throws FileNotFoundException Throws FileNotFoundException if there is
1413 * no file associated with the given URI or the mode is invalid.
1414 * @throws SecurityException Throws SecurityException if the caller does
1415 * not have permission to access the file.
1416 *
1417 * @see #openFile(Uri, String)
1418 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001419 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001421 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 throws FileNotFoundException {
1423 ParcelFileDescriptor fd = openFile(uri, mode);
1424 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1425 }
1426
1427 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001428 * This is like {@link #openFile}, but can be implemented by providers
1429 * that need to be able to return sub-sections of files, often assets
1430 * inside of their .apk.
1431 * This method can be called from multiple threads, as described in
1432 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1433 * and Threads</a>.
1434 *
1435 * <p>If you implement this, your clients must be able to deal with such
1436 * file slices, either directly with
1437 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1438 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1439 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1440 * methods.
1441 * <p>
1442 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1443 * streaming of data.
1444 *
1445 * <p class="note">If you are implementing this to return a full file, you
1446 * should create the AssetFileDescriptor with
1447 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1448 * applications that cannot handle sub-sections of files.</p>
1449 *
1450 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1451 * to return the appropriate MIME type for the data returned here with
1452 * the same URI. This will allow intent resolution to automatically determine the data MIME
1453 * type and select the appropriate matching targets as part of its operation.</p>
1454 *
1455 * <p class="note">For better interoperability with other applications, it is recommended
1456 * that for any URIs that can be opened, you also support queries on them
1457 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1458 *
1459 * @param uri The URI whose file is to be opened.
1460 * @param mode Access mode for the file. May be "r" for read-only access,
1461 * "w" for write-only access (erasing whatever data is currently in
1462 * the file), "wa" for write-only access to append to any existing data,
1463 * "rw" for read and write access on any existing data, and "rwt" for read
1464 * and write access that truncates any existing file.
1465 * @param signal A signal to cancel the operation in progress, or
1466 * {@code null} if none. For example, if you are downloading a
1467 * file from the network to service a "rw" mode request, you
1468 * should periodically call
1469 * {@link CancellationSignal#throwIfCanceled()} to check whether
1470 * the client has canceled the request and abort the download.
1471 *
1472 * @return Returns a new AssetFileDescriptor which you can use to access
1473 * the file.
1474 *
1475 * @throws FileNotFoundException Throws FileNotFoundException if there is
1476 * no file associated with the given URI or the mode is invalid.
1477 * @throws SecurityException Throws SecurityException if the caller does
1478 * not have permission to access the file.
1479 *
1480 * @see #openFile(Uri, String)
1481 * @see #openFileHelper(Uri, String)
1482 * @see #getType(android.net.Uri)
1483 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001484 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1485 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001486 return openAssetFile(uri, mode);
1487 }
1488
1489 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 * Convenience for subclasses that wish to implement {@link #openFile}
1491 * by looking up a column named "_data" at the given URI.
1492 *
1493 * @param uri The URI to be opened.
1494 * @param mode The file mode. May be "r" for read-only access,
1495 * "w" for write-only access (erasing whatever data is currently in
1496 * the file), "wa" for write-only access to append to any existing data,
1497 * "rw" for read and write access on any existing data, and "rwt" for read
1498 * and write access that truncates any existing file.
1499 *
1500 * @return Returns a new ParcelFileDescriptor that can be used by the
1501 * client to access the file.
1502 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001503 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1504 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1506 int count = (c != null) ? c.getCount() : 0;
1507 if (count != 1) {
1508 // If there is not exactly one result, throw an appropriate
1509 // exception.
1510 if (c != null) {
1511 c.close();
1512 }
1513 if (count == 0) {
1514 throw new FileNotFoundException("No entry for " + uri);
1515 }
1516 throw new FileNotFoundException("Multiple items at " + uri);
1517 }
1518
1519 c.moveToFirst();
1520 int i = c.getColumnIndex("_data");
1521 String path = (i >= 0 ? c.getString(i) : null);
1522 c.close();
1523 if (path == null) {
1524 throw new FileNotFoundException("Column _data not found.");
1525 }
1526
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001527 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 return ParcelFileDescriptor.open(new File(path), modeBits);
1529 }
1530
1531 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001532 * Called by a client to determine the types of data streams that this
1533 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001534 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001535 * of a particular type, return that MIME type if it matches the given
1536 * mimeTypeFilter. If it can perform type conversions, return an array
1537 * of all supported MIME types that match mimeTypeFilter.
1538 *
1539 * @param uri The data in the content provider being queried.
1540 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001541 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001542 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001543 * given mimeTypeFilter. Otherwise returns an array of all available
1544 * concrete MIME types.
1545 *
1546 * @see #getType(Uri)
1547 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001548 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001549 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001550 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001551 return null;
1552 }
1553
1554 /**
1555 * Called by a client to open a read-only stream containing data of a
1556 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1557 * except the file can only be read-only and the content provider may
1558 * perform data conversions to generate data of the desired type.
1559 *
1560 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001561 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001562 * {@link #openAssetFile(Uri, String)}.
1563 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001564 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001565 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001566 * <p>
1567 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1568 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001569 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001570 * <p class="note">For better interoperability with other applications, it is recommended
1571 * that for any URIs that can be opened, you also support queries on them
1572 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1573 * You may also want to support other common columns if you have additional meta-data
1574 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1575 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1576 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001577 * @param uri The data in the content provider being queried.
1578 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001579 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001580 * requirements; in this case the content provider will pick its best
1581 * type matching the pattern.
1582 * @param opts Additional options from the client. The definitions of
1583 * these are specific to the content provider being called.
1584 *
1585 * @return Returns a new AssetFileDescriptor from which the client can
1586 * read data of the desired type.
1587 *
1588 * @throws FileNotFoundException Throws FileNotFoundException if there is
1589 * no file associated with the given URI or the mode is invalid.
1590 * @throws SecurityException Throws SecurityException if the caller does
1591 * not have permission to access the data.
1592 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1593 * content provider does not support the requested MIME type.
1594 *
1595 * @see #getStreamTypes(Uri, String)
1596 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001597 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001598 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001599 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1600 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001601 if ("*/*".equals(mimeTypeFilter)) {
1602 // If they can take anything, the untyped open call is good enough.
1603 return openAssetFile(uri, "r");
1604 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001605 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001606 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001607 // Use old untyped open call if this provider has a type for this
1608 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001609 return openAssetFile(uri, "r");
1610 }
1611 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1612 }
1613
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001614
1615 /**
1616 * Called by a client to open a read-only stream containing data of a
1617 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1618 * except the file can only be read-only and the content provider may
1619 * perform data conversions to generate data of the desired type.
1620 *
1621 * <p>The default implementation compares the given mimeType against the
1622 * result of {@link #getType(Uri)} and, if they match, simply calls
1623 * {@link #openAssetFile(Uri, String)}.
1624 *
1625 * <p>See {@link ClipData} for examples of the use and implementation
1626 * of this method.
1627 * <p>
1628 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1629 * streaming of data.
1630 *
1631 * <p class="note">For better interoperability with other applications, it is recommended
1632 * that for any URIs that can be opened, you also support queries on them
1633 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1634 * You may also want to support other common columns if you have additional meta-data
1635 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1636 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1637 *
1638 * @param uri The data in the content provider being queried.
1639 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001640 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001641 * requirements; in this case the content provider will pick its best
1642 * type matching the pattern.
1643 * @param opts Additional options from the client. The definitions of
1644 * these are specific to the content provider being called.
1645 * @param signal A signal to cancel the operation in progress, or
1646 * {@code null} if none. For example, if you are downloading a
1647 * file from the network to service a "rw" mode request, you
1648 * should periodically call
1649 * {@link CancellationSignal#throwIfCanceled()} to check whether
1650 * the client has canceled the request and abort the download.
1651 *
1652 * @return Returns a new AssetFileDescriptor from which the client can
1653 * read data of the desired type.
1654 *
1655 * @throws FileNotFoundException Throws FileNotFoundException if there is
1656 * no file associated with the given URI or the mode is invalid.
1657 * @throws SecurityException Throws SecurityException if the caller does
1658 * not have permission to access the data.
1659 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1660 * content provider does not support the requested MIME type.
1661 *
1662 * @see #getStreamTypes(Uri, String)
1663 * @see #openAssetFile(Uri, String)
1664 * @see ClipDescription#compareMimeTypes(String, String)
1665 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001666 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1667 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1668 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001669 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1670 }
1671
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001672 /**
1673 * Interface to write a stream of data to a pipe. Use with
1674 * {@link ContentProvider#openPipeHelper}.
1675 */
1676 public interface PipeDataWriter<T> {
1677 /**
1678 * Called from a background thread to stream data out to a pipe.
1679 * Note that the pipe is blocking, so this thread can block on
1680 * writes for an arbitrary amount of time if the client is slow
1681 * at reading.
1682 *
1683 * @param output The pipe where data should be written. This will be
1684 * closed for you upon returning from this function.
1685 * @param uri The URI whose data is to be written.
1686 * @param mimeType The desired type of data to be written.
1687 * @param opts Options supplied by caller.
1688 * @param args Your own custom arguments.
1689 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001690 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1691 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001692 }
1693
1694 /**
1695 * A helper function for implementing {@link #openTypedAssetFile}, for
1696 * creating a data pipe and background thread allowing you to stream
1697 * generated data back to the client. This function returns a new
1698 * ParcelFileDescriptor that should be returned to the caller (the caller
1699 * is responsible for closing it).
1700 *
1701 * @param uri The URI whose data is to be written.
1702 * @param mimeType The desired type of data to be written.
1703 * @param opts Options supplied by caller.
1704 * @param args Your own custom arguments.
1705 * @param func Interface implementing the function that will actually
1706 * stream the data.
1707 * @return Returns a new ParcelFileDescriptor holding the read side of
1708 * the pipe. This should be returned to the caller for reading; the caller
1709 * is responsible for closing it when done.
1710 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001711 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1712 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1713 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001714 try {
1715 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1716
1717 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1718 @Override
1719 protected Object doInBackground(Object... params) {
1720 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1721 try {
1722 fds[1].close();
1723 } catch (IOException e) {
1724 Log.w(TAG, "Failure closing pipe", e);
1725 }
1726 return null;
1727 }
1728 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001729 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001730
1731 return fds[0];
1732 } catch (IOException e) {
1733 throw new FileNotFoundException("failure making pipe");
1734 }
1735 }
1736
1737 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 * Returns true if this instance is a temporary content provider.
1739 * @return true if this instance is a temporary content provider
1740 */
1741 protected boolean isTemporary() {
1742 return false;
1743 }
1744
1745 /**
1746 * Returns the Binder object for this provider.
1747 *
1748 * @return the Binder object for this provider
1749 * @hide
1750 */
1751 public IContentProvider getIContentProvider() {
1752 return mTransport;
1753 }
1754
1755 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001756 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1757 * when directly instantiating the provider for testing.
1758 * @hide
1759 */
1760 public void attachInfoForTesting(Context context, ProviderInfo info) {
1761 attachInfo(context, info, true);
1762 }
1763
1764 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 * After being instantiated, this is called to tell the content provider
1766 * about itself.
1767 *
1768 * @param context The context this provider is running in
1769 * @param info Registered information about this content provider
1770 */
1771 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001772 attachInfo(context, info, false);
1773 }
1774
1775 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001776 mNoPerms = testing;
1777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 /*
1779 * Only allow it to be set once, so after the content service gives
1780 * this to us clients can't change it.
1781 */
1782 if (mContext == null) {
1783 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001784 if (context != null) {
1785 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1786 Context.APP_OPS_SERVICE);
1787 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001788 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 if (info != null) {
1790 setReadPermission(info.readPermission);
1791 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001792 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001793 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001794 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001795 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 }
1797 ContentProvider.this.onCreate();
1798 }
1799 }
Fred Quintanace31b232009-05-04 16:01:15 -07001800
1801 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001802 * Override this to handle requests to perform a batch of operations, or the
1803 * default implementation will iterate over the operations and call
1804 * {@link ContentProviderOperation#apply} on each of them.
1805 * If all calls to {@link ContentProviderOperation#apply} succeed
1806 * then a {@link ContentProviderResult} array with as many
1807 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001808 * fail, it is up to the implementation how many of the others take effect.
1809 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001810 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1811 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001812 *
Fred Quintanace31b232009-05-04 16:01:15 -07001813 * @param operations the operations to apply
1814 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001815 * @throws OperationApplicationException thrown if any operation fails.
1816 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001817 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001818 public @NonNull ContentProviderResult[] applyBatch(
1819 @NonNull ArrayList<ContentProviderOperation> operations)
1820 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001821 final int numOperations = operations.size();
1822 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1823 for (int i = 0; i < numOperations; i++) {
1824 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001825 }
1826 return results;
1827 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001828
1829 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001830 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001831 * interfaces that are cheaper and/or unnatural for a table-like
1832 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001833 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001834 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1835 * on this entry into the content provider besides the basic ability for the application
1836 * to get access to the provider at all. For example, it has no idea whether the call
1837 * being executed may read or write data in the provider, so can't enforce those
1838 * individual permissions. Any implementation of this method <strong>must</strong>
1839 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1840 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001841 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1842 * @param arg provider-defined String argument. May be {@code null}.
1843 * @param extras provider-defined Bundle argument. May be {@code null}.
1844 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001845 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001846 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001847 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
1848 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001849 return null;
1850 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001851
1852 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001853 * Implement this to shut down the ContentProvider instance. You can then
1854 * invoke this method in unit tests.
1855 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001856 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001857 * Android normally handles ContentProvider startup and shutdown
1858 * automatically. You do not need to start up or shut down a
1859 * ContentProvider. When you invoke a test method on a ContentProvider,
1860 * however, a ContentProvider instance is started and keeps running after
1861 * the test finishes, even if a succeeding test instantiates another
1862 * ContentProvider. A conflict develops because the two instances are
1863 * usually running against the same underlying data source (for example, an
1864 * sqlite database).
1865 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001866 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001867 * Implementing shutDown() avoids this conflict by providing a way to
1868 * terminate the ContentProvider. This method can also prevent memory leaks
1869 * from multiple instantiations of the ContentProvider, and it can ensure
1870 * unit test isolation by allowing you to completely clean up the test
1871 * fixture before moving on to the next test.
1872 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001873 */
1874 public void shutdown() {
1875 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1876 "connections are gracefully shutdown");
1877 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001878
1879 /**
1880 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001881 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001882 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001883 * @param fd The raw file descriptor that the dump is being sent to.
1884 * @param writer The PrintWriter to which you should dump your state. This will be
1885 * closed for you after you return.
1886 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001887 */
1888 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1889 writer.println("nothing to dump");
1890 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001891
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001892 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001893 private void validateIncomingUri(Uri uri) throws SecurityException {
1894 String auth = uri.getAuthority();
Robin Lee2ab02e22016-07-28 18:41:23 +01001895 if (!mSingleUser) {
1896 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1897 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
1898 throw new SecurityException("trying to query a ContentProvider in user "
1899 + mContext.getUserId() + " with a uri belonging to user " + userId);
1900 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001901 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001902 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
1903 String message = "The authority of the uri " + uri + " does not match the one of the "
1904 + "contentProvider: ";
1905 if (mAuthority != null) {
1906 message += mAuthority;
1907 } else {
Andreas Gampee6748ce2015-12-11 18:00:38 -08001908 message += Arrays.toString(mAuthorities);
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001909 }
1910 throw new SecurityException(message);
1911 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001912 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001913
1914 /** @hide */
Robin Lee2ab02e22016-07-28 18:41:23 +01001915 private Uri maybeGetUriWithoutUserId(Uri uri) {
1916 if (mSingleUser) {
1917 return uri;
1918 }
1919 return getUriWithoutUserId(uri);
1920 }
1921
1922 /** @hide */
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001923 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1924 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001925 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001926 if (end == -1) return defaultUserId;
1927 String userIdString = auth.substring(0, end);
1928 try {
1929 return Integer.parseInt(userIdString);
1930 } catch (NumberFormatException e) {
1931 Log.w(TAG, "Error parsing userId.", e);
1932 return UserHandle.USER_NULL;
1933 }
1934 }
1935
1936 /** @hide */
1937 public static int getUserIdFromAuthority(String auth) {
1938 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1939 }
1940
1941 /** @hide */
1942 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1943 if (uri == null) return defaultUserId;
1944 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1945 }
1946
1947 /** @hide */
1948 public static int getUserIdFromUri(Uri uri) {
1949 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1950 }
1951
1952 /**
1953 * Removes userId part from authority string. Expects format:
1954 * userId@some.authority
1955 * If there is no userId in the authority, it symply returns the argument
1956 * @hide
1957 */
1958 public static String getAuthorityWithoutUserId(String auth) {
1959 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001960 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001961 return auth.substring(end+1);
1962 }
1963
1964 /** @hide */
1965 public static Uri getUriWithoutUserId(Uri uri) {
1966 if (uri == null) return null;
1967 Uri.Builder builder = uri.buildUpon();
1968 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1969 return builder.build();
1970 }
1971
1972 /** @hide */
1973 public static boolean uriHasUserId(Uri uri) {
1974 if (uri == null) return false;
1975 return !TextUtils.isEmpty(uri.getUserInfo());
1976 }
1977
1978 /** @hide */
1979 public static Uri maybeAddUserId(Uri uri, int userId) {
1980 if (uri == null) return null;
1981 if (userId != UserHandle.USER_CURRENT
1982 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1983 if (!uriHasUserId(uri)) {
1984 //We don't add the user Id if there's already one
1985 Uri.Builder builder = uri.buildUpon();
1986 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1987 return builder.build();
1988 }
1989 }
1990 return uri;
1991 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001992}