blob: 494f82105fce85cde598656901ee5f51382d8c37 [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
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Nicolas Prevot504d78e2014-06-26 10:07:33 +010020import static android.Manifest.permission.INTERACT_ACROSS_USERS;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070021
Jeff Sharkey673db442015-06-11 19:30:57 -070022import android.annotation.NonNull;
Scott Kennedy9f78f652015-03-01 15:29:25 -080023import android.annotation.Nullable;
Dianne Hackborn35654b62013-01-14 17:38:02 -080024import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070025import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.content.pm.ProviderInfo;
27import android.content.res.AssetFileDescriptor;
28import android.content.res.Configuration;
29import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070030import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.database.SQLException;
32import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070033import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080035import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070036import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080037import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070038import android.os.ICancellationSignal;
39import android.os.OperationCanceledException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070041import android.os.Process;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070042import android.os.UserHandle;
Vasu Nori0c9e14a2010-08-04 13:31:48 -070043import android.util.Log;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010044import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045
46import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080047import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070049import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080050import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070051import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052
53/**
54 * Content providers are one of the primary building blocks of Android applications, providing
55 * content to applications. They encapsulate data and provide it to applications through the single
56 * {@link ContentResolver} interface. A content provider is only required if you need to share
57 * data between multiple applications. For example, the contacts data is used by multiple
58 * applications and must be stored in a content provider. If you don't need to share data amongst
59 * multiple applications you can use a database directly via
60 * {@link android.database.sqlite.SQLiteDatabase}.
61 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 * <p>When a request is made via
63 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
64 * request to the content provider registered with the authority. The content provider can interpret
65 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
66 * URIs.</p>
67 *
68 * <p>The primary methods that need to be implemented are:
69 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070070 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071 * <li>{@link #query} which returns data to the caller</li>
72 * <li>{@link #insert} which inserts new data into the content provider</li>
73 * <li>{@link #update} which updates existing data in the content provider</li>
74 * <li>{@link #delete} which deletes data from the content provider</li>
75 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
76 * </ul></p>
77 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070078 * <p class="caution">Data access methods (such as {@link #insert} and
79 * {@link #update}) may be called from many threads at once, and must be thread-safe.
80 * Other methods (such as {@link #onCreate}) are only called from the application
81 * main thread, and must avoid performing lengthy operations. See the method
82 * descriptions for their expected thread behavior.</p>
83 *
84 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
85 * ContentProvider instance, so subclasses don't have to worry about the details of
86 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070087 *
88 * <div class="special reference">
89 * <h3>Developer Guides</h3>
90 * <p>For more information about using content providers, read the
91 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
92 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -070094public abstract class ContentProvider implements ComponentCallbacks2 {
Vasu Nori0c9e14a2010-08-04 13:31:48 -070095 private static final String TAG = "ContentProvider";
96
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +090097 /*
98 * Note: if you add methods to ContentProvider, you must add similar methods to
99 * MockContentProvider.
100 */
101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700103 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100104
105 // Since most Providers have only one authority, we keep both a String and a String[] to improve
106 // performance.
107 private String mAuthority;
108 private String[] mAuthorities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 private String mReadPermission;
110 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700111 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700112 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800113 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700114 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700116 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<String>();
117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private Transport mTransport = new Transport();
119
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700120 /**
121 * Construct a ContentProvider instance. Content providers must be
122 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
123 * in the manifest</a>, accessed with {@link ContentResolver}, and created
124 * automatically by the system, so applications usually do not create
125 * ContentProvider instances directly.
126 *
127 * <p>At construction time, the object is uninitialized, and most fields and
128 * methods are unavailable. Subclasses should initialize themselves in
129 * {@link #onCreate}, not the constructor.
130 *
131 * <p>Content providers are created on the application main thread at
132 * application launch time. The constructor must not perform lengthy
133 * operations, or application startup will be delayed.
134 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900135 public ContentProvider() {
136 }
137
138 /**
139 * Constructor just for mocking.
140 *
141 * @param context A Context object which should be some mock instance (like the
142 * instance of {@link android.test.mock.MockContext}).
143 * @param readPermission The read permision you want this instance should have in the
144 * test, which is available via {@link #getReadPermission()}.
145 * @param writePermission The write permission you want this instance should have
146 * in the test, which is available via {@link #getWritePermission()}.
147 * @param pathPermissions The PathPermissions you want this instance should have
148 * in the test, which is available via {@link #getPathPermissions()}.
149 * @hide
150 */
151 public ContentProvider(
152 Context context,
153 String readPermission,
154 String writePermission,
155 PathPermission[] pathPermissions) {
156 mContext = context;
157 mReadPermission = readPermission;
158 mWritePermission = writePermission;
159 mPathPermissions = pathPermissions;
160 }
161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 /**
163 * Given an IContentProvider, try to coerce it back to the real
164 * ContentProvider object if it is running in the local process. This can
165 * be used if you know you are running in the same process as a provider,
166 * and want to get direct access to its implementation details. Most
167 * clients should not nor have a reason to use it.
168 *
169 * @param abstractInterface The ContentProvider interface that is to be
170 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800171 * @return If the IContentProvider is non-{@code null} and local, returns its actual
172 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 * @hide
174 */
175 public static ContentProvider coerceToLocalContentProvider(
176 IContentProvider abstractInterface) {
177 if (abstractInterface instanceof Transport) {
178 return ((Transport)abstractInterface).getContentProvider();
179 }
180 return null;
181 }
182
183 /**
184 * Binder object that deals with remoting.
185 *
186 * @hide
187 */
188 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800189 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800190 int mReadOp = AppOpsManager.OP_NONE;
191 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 ContentProvider getContentProvider() {
194 return ContentProvider.this;
195 }
196
Jeff Brownd2183652011-10-09 12:39:53 -0700197 @Override
198 public String getProviderName() {
199 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 }
201
Jeff Brown75ea64f2012-01-25 19:37:13 -0800202 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800203 public Cursor query(String callingPkg, Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800204 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800205 ICancellationSignal cancellationSignal) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100206 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100207 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800208 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700209 // The caller has no access to the data, so return an empty cursor with
210 // the columns in the requested order. The caller may ask for an invalid
211 // column and we would not catch that but this is not a problem in practice.
212 // We do not call ContentProvider#query with a modified where clause since
213 // the implementation is not guaranteed to be backed by a SQL database, hence
214 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700215 if (projection != null) {
216 return new MatrixCursor(projection, 0);
217 }
218
219 // Null projection means all columns but we have no idea which they are.
220 // However, the caller may be expecting to access them my index. Hence,
221 // we have to execute the query as if allowed to get a cursor with the
222 // columns. We then use the column names to return an empty cursor.
223 Cursor cursor = ContentProvider.this.query(uri, projection, selection,
224 selectionArgs, sortOrder, CancellationSignal.fromTransport(
225 cancellationSignal));
226
227 // Create a projection for all columns.
228 final int columnCount = cursor.getCount();
229 String[] allColumns = new String[columnCount];
230 for (int i = 0; i < columnCount; i++) {
231 allColumns[i] = cursor.getColumnName(i);
232 }
233
234 // Return an empty cursor for all columns.
235 return new MatrixCursor(allColumns, 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800236 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700237 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700238 try {
239 return ContentProvider.this.query(
240 uri, projection, selection, selectionArgs, sortOrder,
241 CancellationSignal.fromTransport(cancellationSignal));
242 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700243 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 }
246
Jeff Brown75ea64f2012-01-25 19:37:13 -0800247 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100249 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100250 uri = getUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 return ContentProvider.this.getType(uri);
252 }
253
Jeff Brown75ea64f2012-01-25 19:37:13 -0800254 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800255 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100256 validateIncomingUri(uri);
257 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100258 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800259 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800260 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800261 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700262 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700263 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100264 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700265 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700266 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 }
269
Jeff Brown75ea64f2012-01-25 19:37:13 -0800270 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800271 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100272 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100273 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800274 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800275 return 0;
276 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700277 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700278 try {
279 return ContentProvider.this.bulkInsert(uri, initialValues);
280 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700281 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 }
284
Jeff Brown75ea64f2012-01-25 19:37:13 -0800285 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800286 public ContentProviderResult[] applyBatch(String callingPkg,
287 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700288 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100289 int numOperations = operations.size();
290 final int[] userIds = new int[numOperations];
291 for (int i = 0; i < numOperations; i++) {
292 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100293 Uri uri = operation.getUri();
294 validateIncomingUri(uri);
295 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100296 if (userIds[i] != UserHandle.USER_CURRENT) {
297 // Removing the user id from the uri.
298 operation = new ContentProviderOperation(operation, true);
299 operations.set(i, operation);
300 }
Fred Quintana89437372009-05-15 15:10:40 -0700301 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800302 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800303 != AppOpsManager.MODE_ALLOWED) {
304 throw new OperationApplicationException("App op not allowed", 0);
305 }
Fred Quintana89437372009-05-15 15:10:40 -0700306 }
Fred Quintana89437372009-05-15 15:10:40 -0700307 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800308 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800309 != AppOpsManager.MODE_ALLOWED) {
310 throw new OperationApplicationException("App op not allowed", 0);
311 }
Fred Quintana89437372009-05-15 15:10:40 -0700312 }
313 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700314 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700315 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100316 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800317 if (results != null) {
318 for (int i = 0; i < results.length ; i++) {
319 if (userIds[i] != UserHandle.USER_CURRENT) {
320 // Adding the userId to the uri.
321 results[i] = new ContentProviderResult(results[i], userIds[i]);
322 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100323 }
324 }
325 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700326 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700327 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700328 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700329 }
330
Jeff Brown75ea64f2012-01-25 19:37:13 -0800331 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800332 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100333 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100334 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800335 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800336 return 0;
337 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700338 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700339 try {
340 return ContentProvider.this.delete(uri, selection, selectionArgs);
341 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700342 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 }
345
Jeff Brown75ea64f2012-01-25 19:37:13 -0800346 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800347 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100349 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100350 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800351 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800352 return 0;
353 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700354 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700355 try {
356 return ContentProvider.this.update(uri, values, selection, selectionArgs);
357 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700358 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 }
361
Jeff Brown75ea64f2012-01-25 19:37:13 -0800362 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700363 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800364 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
365 IBinder callerToken) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100366 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100367 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800368 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700369 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700370 try {
371 return ContentProvider.this.openFile(
372 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
373 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700374 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 }
377
Jeff Brown75ea64f2012-01-25 19:37:13 -0800378 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700379 public AssetFileDescriptor openAssetFile(
380 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100382 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100383 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800384 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700385 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700386 try {
387 return ContentProvider.this.openAssetFile(
388 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
389 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700390 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 }
393
Jeff Brown75ea64f2012-01-25 19:37:13 -0800394 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800395 public Bundle call(
396 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700397 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700398 try {
399 return ContentProvider.this.call(method, arg, extras);
400 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700401 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700402 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800403 }
404
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700405 @Override
406 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100407 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100408 uri = getUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700409 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
410 }
411
412 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800413 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700414 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100415 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100416 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800417 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700418 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700419 try {
420 return ContentProvider.this.openTypedAssetFile(
421 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
422 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700423 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700424 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700425 }
426
Jeff Brown75ea64f2012-01-25 19:37:13 -0800427 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700428 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800429 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800430 }
431
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700432 @Override
433 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100434 validateIncomingUri(uri);
435 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100436 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800437 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700438 return null;
439 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700440 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700441 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100442 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700443 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700444 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700445 }
446 }
447
448 @Override
449 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100450 validateIncomingUri(uri);
451 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100452 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800453 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700454 return null;
455 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700456 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700457 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100458 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700459 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700460 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700461 }
462 }
463
Dianne Hackbornff170242014-11-19 10:59:01 -0800464 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
465 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800466 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800467 if (enforceWritePermission(callingPkg, uri, callerToken)
468 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800469 throw new FileNotFoundException("App op not allowed");
470 }
471 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800472 if (enforceReadPermission(callingPkg, uri, callerToken)
473 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800474 throw new FileNotFoundException("App op not allowed");
475 }
476 }
477 }
478
Dianne Hackbornff170242014-11-19 10:59:01 -0800479 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
480 throws SecurityException {
481 enforceReadPermissionInner(uri, callerToken);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800482 if (mReadOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800483 return mAppOpsManager.noteOp(mReadOp, Binder.getCallingUid(), callingPkg);
484 }
485 return AppOpsManager.MODE_ALLOWED;
486 }
487
Dianne Hackbornff170242014-11-19 10:59:01 -0800488 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
489 throws SecurityException {
490 enforceWritePermissionInner(uri, callerToken);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800491 if (mWriteOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800492 return mAppOpsManager.noteOp(mWriteOp, Binder.getCallingUid(), callingPkg);
493 }
494 return AppOpsManager.MODE_ALLOWED;
495 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700496 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800497
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100498 boolean checkUser(int pid, int uid, Context context) {
499 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700500 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100501 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
502 == PERMISSION_GRANTED;
503 }
504
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700505 /** {@hide} */
Dianne Hackbornff170242014-11-19 10:59:01 -0800506 protected void enforceReadPermissionInner(Uri uri, IBinder callerToken)
507 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700508 final Context context = getContext();
509 final int pid = Binder.getCallingPid();
510 final int uid = Binder.getCallingUid();
511 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700512
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700513 if (UserHandle.isSameApp(uid, mMyUid)) {
514 return;
515 }
516
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100517 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700518 final String componentPerm = getReadPermission();
519 if (componentPerm != null) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800520 if (context.checkPermission(componentPerm, pid, uid, callerToken)
521 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700522 return;
523 } else {
524 missingPerm = componentPerm;
525 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700526 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700527
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700528 // track if unprotected read is allowed; any denied
529 // <path-permission> below removes this ability
530 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700531
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700532 final PathPermission[] pps = getPathPermissions();
533 if (pps != null) {
534 final String path = uri.getPath();
535 for (PathPermission pp : pps) {
536 final String pathPerm = pp.getReadPermission();
537 if (pathPerm != null && pp.match(path)) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800538 if (context.checkPermission(pathPerm, pid, uid, callerToken)
539 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700540 return;
541 } else {
542 // any denied <path-permission> means we lose
543 // default <provider> access.
544 allowDefaultRead = false;
545 missingPerm = pathPerm;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700546 }
547 }
548 }
549 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700550
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700551 // if we passed <path-permission> checks above, and no default
552 // <provider> permission, then allow access.
553 if (allowDefaultRead) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700555
556 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800557 final int callingUserId = UserHandle.getUserId(uid);
558 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
559 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800560 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
561 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700562 return;
563 }
564
565 final String failReason = mExported
566 ? " requires " + missingPerm + ", or grantUriPermission()"
567 : " requires the provider be exported, or grantUriPermission()";
568 throw new SecurityException("Permission Denial: reading "
569 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
570 + ", uid=" + uid + failReason);
571 }
572
573 /** {@hide} */
Dianne Hackbornff170242014-11-19 10:59:01 -0800574 protected void enforceWritePermissionInner(Uri uri, IBinder callerToken)
575 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700576 final Context context = getContext();
577 final int pid = Binder.getCallingPid();
578 final int uid = Binder.getCallingUid();
579 String missingPerm = null;
580
581 if (UserHandle.isSameApp(uid, mMyUid)) {
582 return;
583 }
584
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100585 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700586 final String componentPerm = getWritePermission();
587 if (componentPerm != null) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800588 if (context.checkPermission(componentPerm, pid, uid, callerToken)
589 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700590 return;
591 } else {
592 missingPerm = componentPerm;
593 }
594 }
595
596 // track if unprotected write is allowed; any denied
597 // <path-permission> below removes this ability
598 boolean allowDefaultWrite = (componentPerm == null);
599
600 final PathPermission[] pps = getPathPermissions();
601 if (pps != null) {
602 final String path = uri.getPath();
603 for (PathPermission pp : pps) {
604 final String pathPerm = pp.getWritePermission();
605 if (pathPerm != null && pp.match(path)) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800606 if (context.checkPermission(pathPerm, pid, uid, callerToken)
607 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700608 return;
609 } else {
610 // any denied <path-permission> means we lose
611 // default <provider> access.
612 allowDefaultWrite = false;
613 missingPerm = pathPerm;
614 }
615 }
616 }
617 }
618
619 // if we passed <path-permission> checks above, and no default
620 // <provider> permission, then allow access.
621 if (allowDefaultWrite) return;
622 }
623
624 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800625 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
626 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700627 return;
628 }
629
630 final String failReason = mExported
631 ? " requires " + missingPerm + ", or grantUriPermission()"
632 : " requires the provider be exported, or grantUriPermission()";
633 throw new SecurityException("Permission Denial: writing "
634 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
635 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 }
637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700639 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800640 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 * constructor.
642 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700643 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800644 return mContext;
645 }
646
647 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700648 * Set the calling package, returning the current value (or {@code null})
649 * which can be used later to restore the previous state.
650 */
651 private String setCallingPackage(String callingPackage) {
652 final String original = mCallingPackage.get();
653 mCallingPackage.set(callingPackage);
654 return original;
655 }
656
657 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700658 * Return the package name of the caller that initiated the request being
659 * processed on the current thread. The returned package will have been
660 * verified to belong to the calling UID. Returns {@code null} if not
661 * currently processing a request.
662 * <p>
663 * This will always return {@code null} when processing
664 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
665 *
666 * @see Binder#getCallingUid()
667 * @see Context#grantUriPermission(String, Uri, int)
668 * @throws SecurityException if the calling package doesn't belong to the
669 * calling UID.
670 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700671 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700672 final String pkg = mCallingPackage.get();
673 if (pkg != null) {
674 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
675 }
676 return pkg;
677 }
678
679 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100680 * Change the authorities of the ContentProvider.
681 * This is normally set for you from its manifest information when the provider is first
682 * created.
683 * @hide
684 * @param authorities the semi-colon separated authorities of the ContentProvider.
685 */
686 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100687 if (authorities != null) {
688 if (authorities.indexOf(';') == -1) {
689 mAuthority = authorities;
690 mAuthorities = null;
691 } else {
692 mAuthority = null;
693 mAuthorities = authorities.split(";");
694 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100695 }
696 }
697
698 /** @hide */
699 protected final boolean matchesOurAuthorities(String authority) {
700 if (mAuthority != null) {
701 return mAuthority.equals(authority);
702 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100703 if (mAuthorities != null) {
704 int length = mAuthorities.length;
705 for (int i = 0; i < length; i++) {
706 if (mAuthorities[i].equals(authority)) return true;
707 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100708 }
709 return false;
710 }
711
712
713 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 * Change the permission required to read data from the content
715 * provider. This is normally set for you from its manifest information
716 * when the provider is first created.
717 *
718 * @param permission Name of the permission required for read-only access.
719 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700720 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 mReadPermission = permission;
722 }
723
724 /**
725 * Return the name of the permission required for read-only access to
726 * this content provider. This method can be called from multiple
727 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800728 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
729 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700731 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 return mReadPermission;
733 }
734
735 /**
736 * Change the permission required to read and write data in the content
737 * provider. This is normally set for you from its manifest information
738 * when the provider is first created.
739 *
740 * @param permission Name of the permission required for read/write access.
741 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700742 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 mWritePermission = permission;
744 }
745
746 /**
747 * Return the name of the permission required for read/write access to
748 * this content provider. This method can be called from multiple
749 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800750 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
751 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700753 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 return mWritePermission;
755 }
756
757 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700758 * Change the path-based permission required to read and/or write data in
759 * the content provider. This is normally set for you from its manifest
760 * information when the provider is first created.
761 *
762 * @param permissions Array of path permission descriptions.
763 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700764 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700765 mPathPermissions = permissions;
766 }
767
768 /**
769 * Return the path-based permissions required for read and/or write access to
770 * this content provider. This method can be called from multiple
771 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800772 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
773 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700774 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700775 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700776 return mPathPermissions;
777 }
778
Dianne Hackborn35654b62013-01-14 17:38:02 -0800779 /** @hide */
780 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800781 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800782 mTransport.mReadOp = readOp;
783 mTransport.mWriteOp = writeOp;
784 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800785 }
786
Dianne Hackborn961321f2013-02-05 17:22:41 -0800787 /** @hide */
788 public AppOpsManager getAppOpsManager() {
789 return mTransport.mAppOpsManager;
790 }
791
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700792 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700793 * Implement this to initialize your content provider on startup.
794 * This method is called for all registered content providers on the
795 * application main thread at application launch time. It must not perform
796 * lengthy operations, or application startup will be delayed.
797 *
798 * <p>You should defer nontrivial initialization (such as opening,
799 * upgrading, and scanning databases) until the content provider is used
800 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
801 * keeps application startup fast, avoids unnecessary work if the provider
802 * turns out not to be needed, and stops database errors (such as a full
803 * disk) from halting application launch.
804 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700805 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700806 * is a helpful utility class that makes it easy to manage databases,
807 * and will automatically defer opening until first use. If you do use
808 * SQLiteOpenHelper, make sure to avoid calling
809 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
810 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
811 * from this method. (Instead, override
812 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
813 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 *
815 * @return true if the provider was successfully loaded, false otherwise
816 */
817 public abstract boolean onCreate();
818
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700819 /**
820 * {@inheritDoc}
821 * This method is always called on the application main thread, and must
822 * not perform lengthy operations.
823 *
824 * <p>The default content provider implementation does nothing.
825 * Override this method to take appropriate action.
826 * (Content providers do not usually care about things like screen
827 * orientation, but may want to know about locale changes.)
828 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 public void onConfigurationChanged(Configuration newConfig) {
830 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700831
832 /**
833 * {@inheritDoc}
834 * This method is always called on the application main thread, and must
835 * not perform lengthy operations.
836 *
837 * <p>The default content provider implementation does nothing.
838 * Subclasses may override this method to take appropriate action.
839 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 public void onLowMemory() {
841 }
842
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700843 public void onTrimMemory(int level) {
844 }
845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700847 * Implement this to handle query requests from clients.
848 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800849 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
850 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 * <p>
852 * Example client call:<p>
853 * <pre>// Request a specific record.
854 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000855 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 projection, // Which columns to return.
857 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000858 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 People.NAME + " ASC"); // Sort order.</pre>
860 * Example implementation:<p>
861 * <pre>// SQLiteQueryBuilder is a helper class that creates the
862 // proper SQL syntax for us.
863 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
864
865 // Set the table we're querying.
866 qBuilder.setTables(DATABASE_TABLE_NAME);
867
868 // If the query ends in a specific record number, we're
869 // being asked for a specific record, so set the
870 // WHERE clause in our query.
871 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
872 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
873 }
874
875 // Make the query.
876 Cursor c = qBuilder.query(mDb,
877 projection,
878 selection,
879 selectionArgs,
880 groupBy,
881 having,
882 sortOrder);
883 c.setNotificationUri(getContext().getContentResolver(), uri);
884 return c;</pre>
885 *
886 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000887 * if the client is requesting a specific record, the URI will end in a record number
888 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
889 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800891 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800893 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000894 * @param selectionArgs You may include ?s in selection, which will be replaced by
895 * the values from selectionArgs, in order that they appear in the selection.
896 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800898 * If {@code null} then the provider is free to define the sort order.
899 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700901 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
902 @Nullable String selection, @Nullable String[] selectionArgs,
903 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904
Fred Quintana5bba6322009-10-05 14:21:12 -0700905 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800906 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800907 * This method can be called from multiple threads, as described in
908 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
909 * and Threads</a>.
910 * <p>
911 * Example client call:<p>
912 * <pre>// Request a specific record.
913 * Cursor managedCursor = managedQuery(
914 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
915 projection, // Which columns to return.
916 null, // WHERE clause.
917 null, // WHERE clause value substitution
918 People.NAME + " ASC"); // Sort order.</pre>
919 * Example implementation:<p>
920 * <pre>// SQLiteQueryBuilder is a helper class that creates the
921 // proper SQL syntax for us.
922 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
923
924 // Set the table we're querying.
925 qBuilder.setTables(DATABASE_TABLE_NAME);
926
927 // If the query ends in a specific record number, we're
928 // being asked for a specific record, so set the
929 // WHERE clause in our query.
930 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
931 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
932 }
933
934 // Make the query.
935 Cursor c = qBuilder.query(mDb,
936 projection,
937 selection,
938 selectionArgs,
939 groupBy,
940 having,
941 sortOrder);
942 c.setNotificationUri(getContext().getContentResolver(), uri);
943 return c;</pre>
944 * <p>
945 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800946 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
947 * signal to ensure correct operation on older versions of the Android Framework in
948 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800949 *
950 * @param uri The URI to query. This will be the full URI sent by the client;
951 * if the client is requesting a specific record, the URI will end in a record number
952 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
953 * that _id value.
954 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800955 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800956 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800957 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800958 * @param selectionArgs You may include ?s in selection, which will be replaced by
959 * the values from selectionArgs, in order that they appear in the selection.
960 * The values will be bound as Strings.
961 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800962 * If {@code null} then the provider is free to define the sort order.
963 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800964 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
965 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800966 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800967 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700968 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
969 @Nullable String selection, @Nullable String[] selectionArgs,
970 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800971 return query(uri, projection, selection, selectionArgs, sortOrder);
972 }
973
974 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700975 * Implement this to handle requests for the MIME type of the data at the
976 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 * <code>vnd.android.cursor.item</code> for a single record,
978 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700979 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800980 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
981 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700983 * <p>Note that there are no permissions needed for an application to
984 * access this information; if your content provider requires read and/or
985 * write permissions, or is not exported, all applications can still call
986 * this method regardless of their access permissions. This allows them
987 * to retrieve the MIME type for a URI when dispatching intents.
988 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800990 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700992 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993
994 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700995 * Implement this to support canonicalization of URIs that refer to your
996 * content provider. A canonical URI is one that can be transported across
997 * devices, backup/restore, and other contexts, and still be able to refer
998 * to the same data item. Typically this is implemented by adding query
999 * params to the URI allowing the content provider to verify that an incoming
1000 * canonical URI references the same data as it was originally intended for and,
1001 * if it doesn't, to find that data (if it exists) in the current environment.
1002 *
1003 * <p>For example, if the content provider holds people and a normal URI in it
1004 * is created with a row index into that people database, the cananical representation
1005 * may have an additional query param at the end which specifies the name of the
1006 * person it is intended for. Later calls into the provider with that URI will look
1007 * up the row of that URI's base index and, if it doesn't match or its entry's
1008 * name doesn't match the name in the query param, perform a query on its database
1009 * to find the correct row to operate on.</p>
1010 *
1011 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1012 * URIs (including this one) must perform this verification and recovery of any
1013 * canonical URIs they receive. In addition, you must also implement
1014 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1015 *
1016 * <p>The default implementation of this method returns null, indicating that
1017 * canonical URIs are not supported.</p>
1018 *
1019 * @param url The Uri to canonicalize.
1020 *
1021 * @return Return the canonical representation of <var>url</var>, or null if
1022 * canonicalization of that Uri is not supported.
1023 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001024 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001025 return null;
1026 }
1027
1028 /**
1029 * Remove canonicalization from canonical URIs previously returned by
1030 * {@link #canonicalize}. For example, if your implementation is to add
1031 * a query param to canonicalize a URI, this method can simply trip any
1032 * query params on the URI. The default implementation always returns the
1033 * same <var>url</var> that was passed in.
1034 *
1035 * @param url The Uri to remove any canonicalization from.
1036 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001037 * @return Return the non-canonical representation of <var>url</var>, return
1038 * the <var>url</var> as-is if there is nothing to do, or return null if
1039 * the data identified by the canonical representation can not be found in
1040 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001041 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001042 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001043 return url;
1044 }
1045
1046 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001047 * @hide
1048 * Implementation when a caller has performed an insert on the content
1049 * provider, but that call has been rejected for the operation given
1050 * to {@link #setAppOps(int, int)}. The default implementation simply
1051 * returns a dummy URI that is the base URI with a 0 path element
1052 * appended.
1053 */
1054 public Uri rejectInsert(Uri uri, ContentValues values) {
1055 // If not allowed, we need to return some reasonable URI. Maybe the
1056 // content provider should be responsible for this, but for now we
1057 // will just return the base URI with a dummy '0' tagged on to it.
1058 // You shouldn't be able to read if you can't write, anyway, so it
1059 // shouldn't matter much what is returned.
1060 return uri.buildUpon().appendPath("0").build();
1061 }
1062
1063 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001064 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1066 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001067 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001068 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1069 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001070 * @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 -08001071 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001072 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 * @return The URI for the newly inserted item.
1074 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001075 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076
1077 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001078 * Override this to handle requests to insert a set of new rows, or the
1079 * default implementation will iterate over the values and call
1080 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1082 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001083 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001084 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1085 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 *
1087 * @param uri The content:// URI of the insertion request.
1088 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001089 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 * @return The number of values that were inserted.
1091 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001092 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 int numValues = values.length;
1094 for (int i = 0; i < numValues; i++) {
1095 insert(uri, values[i]);
1096 }
1097 return numValues;
1098 }
1099
1100 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001101 * Implement this to handle requests to delete one or more rows.
1102 * The implementation should apply the selection clause when performing
1103 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001104 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001106 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001107 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1108 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 *
1110 * <p>The implementation is responsible for parsing out a row ID at the end
1111 * of the URI, if a specific row is being deleted. That is, the client would
1112 * pass in <code>content://contacts/people/22</code> and the implementation is
1113 * responsible for parsing the record number (22) when creating a SQL statement.
1114 *
1115 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1116 * @param selection An optional restriction to apply to rows when deleting.
1117 * @return The number of rows affected.
1118 * @throws SQLException
1119 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001120 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1121 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122
1123 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001124 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001125 * The implementation should update all rows matching the selection
1126 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1128 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001129 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001130 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1131 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 *
1133 * @param uri The URI to query. This can potentially have a record ID if this
1134 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001135 * @param values A set of column_name/value pairs to update in the database.
1136 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 * @param selection An optional filter to match rows to update.
1138 * @return the number of rows affected.
1139 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001140 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001141 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142
1143 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001144 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001145 * The default implementation always throws {@link FileNotFoundException}.
1146 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001147 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1148 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001149 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001150 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1151 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001152 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 *
1154 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1155 * their responsibility to close it when done. That is, the implementation
1156 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001157 * <p>
1158 * If opened with the exclusive "r" or "w" modes, the returned
1159 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1160 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1161 * supports seeking.
1162 * <p>
1163 * If you need to detect when the returned ParcelFileDescriptor has been
1164 * closed, or if the remote process has crashed or encountered some other
1165 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1166 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1167 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1168 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001170 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1171 * to return the appropriate MIME type for the data returned here with
1172 * the same URI. This will allow intent resolution to automatically determine the data MIME
1173 * type and select the appropriate matching targets as part of its operation.</p>
1174 *
1175 * <p class="note">For better interoperability with other applications, it is recommended
1176 * that for any URIs that can be opened, you also support queries on them
1177 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1178 * You may also want to support other common columns if you have additional meta-data
1179 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1180 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1181 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 * @param uri The URI whose file is to be opened.
1183 * @param mode Access mode for the file. May be "r" for read-only access,
1184 * "rw" for read and write access, or "rwt" for read and write access
1185 * that truncates any existing file.
1186 *
1187 * @return Returns a new ParcelFileDescriptor which you can use to access
1188 * the file.
1189 *
1190 * @throws FileNotFoundException Throws FileNotFoundException if there is
1191 * no file associated with the given URI or the mode is invalid.
1192 * @throws SecurityException Throws SecurityException if the caller does
1193 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001194 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 * @see #openAssetFile(Uri, String)
1196 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001197 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001198 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001199 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001200 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 throws FileNotFoundException {
1202 throw new FileNotFoundException("No files supported by provider at "
1203 + uri);
1204 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001207 * Override this to handle requests to open a file blob.
1208 * The default implementation always throws {@link FileNotFoundException}.
1209 * This method can be called from multiple threads, as described in
1210 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1211 * and Threads</a>.
1212 *
1213 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1214 * to the caller. This way large data (such as images and documents) can be
1215 * returned without copying the content.
1216 *
1217 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1218 * their responsibility to close it when done. That is, the implementation
1219 * of this method should create a new ParcelFileDescriptor for each call.
1220 * <p>
1221 * If opened with the exclusive "r" or "w" modes, the returned
1222 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1223 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1224 * supports seeking.
1225 * <p>
1226 * If you need to detect when the returned ParcelFileDescriptor has been
1227 * closed, or if the remote process has crashed or encountered some other
1228 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1229 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1230 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1231 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1232 *
1233 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1234 * to return the appropriate MIME type for the data returned here with
1235 * the same URI. This will allow intent resolution to automatically determine the data MIME
1236 * type and select the appropriate matching targets as part of its operation.</p>
1237 *
1238 * <p class="note">For better interoperability with other applications, it is recommended
1239 * that for any URIs that can be opened, you also support queries on them
1240 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1241 * You may also want to support other common columns if you have additional meta-data
1242 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1243 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1244 *
1245 * @param uri The URI whose file is to be opened.
1246 * @param mode Access mode for the file. May be "r" for read-only access,
1247 * "w" for write-only access, "rw" for read and write access, or
1248 * "rwt" for read and write access that truncates any existing
1249 * file.
1250 * @param signal A signal to cancel the operation in progress, or
1251 * {@code null} if none. For example, if you are downloading a
1252 * file from the network to service a "rw" mode request, you
1253 * should periodically call
1254 * {@link CancellationSignal#throwIfCanceled()} to check whether
1255 * the client has canceled the request and abort the download.
1256 *
1257 * @return Returns a new ParcelFileDescriptor which you can use to access
1258 * the file.
1259 *
1260 * @throws FileNotFoundException Throws FileNotFoundException if there is
1261 * no file associated with the given URI or the mode is invalid.
1262 * @throws SecurityException Throws SecurityException if the caller does
1263 * not have permission to access the file.
1264 *
1265 * @see #openAssetFile(Uri, String)
1266 * @see #openFileHelper(Uri, String)
1267 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001268 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001269 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001270 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1271 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001272 return openFile(uri, mode);
1273 }
1274
1275 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 * This is like {@link #openFile}, but can be implemented by providers
1277 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001278 * inside of their .apk.
1279 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001280 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1281 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001282 *
1283 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001284 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001285 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1287 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1288 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001289 * <p>
1290 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1291 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001292 *
1293 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 * should create the AssetFileDescriptor with
1295 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001296 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001298 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1299 * to return the appropriate MIME type for the data returned here with
1300 * the same URI. This will allow intent resolution to automatically determine the data MIME
1301 * type and select the appropriate matching targets as part of its operation.</p>
1302 *
1303 * <p class="note">For better interoperability with other applications, it is recommended
1304 * that for any URIs that can be opened, you also support queries on them
1305 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1306 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 * @param uri The URI whose file is to be opened.
1308 * @param mode Access mode for the file. May be "r" for read-only access,
1309 * "w" for write-only access (erasing whatever data is currently in
1310 * the file), "wa" for write-only access to append to any existing data,
1311 * "rw" for read and write access on any existing data, and "rwt" for read
1312 * and write access that truncates any existing file.
1313 *
1314 * @return Returns a new AssetFileDescriptor which you can use to access
1315 * the file.
1316 *
1317 * @throws FileNotFoundException Throws FileNotFoundException if there is
1318 * no file associated with the given URI or the mode is invalid.
1319 * @throws SecurityException Throws SecurityException if the caller does
1320 * not have permission to access the file.
1321 *
1322 * @see #openFile(Uri, String)
1323 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001324 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001326 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 throws FileNotFoundException {
1328 ParcelFileDescriptor fd = openFile(uri, mode);
1329 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1330 }
1331
1332 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001333 * This is like {@link #openFile}, but can be implemented by providers
1334 * that need to be able to return sub-sections of files, often assets
1335 * inside of their .apk.
1336 * This method can be called from multiple threads, as described in
1337 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1338 * and Threads</a>.
1339 *
1340 * <p>If you implement this, your clients must be able to deal with such
1341 * file slices, either directly with
1342 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1343 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1344 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1345 * methods.
1346 * <p>
1347 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1348 * streaming of data.
1349 *
1350 * <p class="note">If you are implementing this to return a full file, you
1351 * should create the AssetFileDescriptor with
1352 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1353 * applications that cannot handle sub-sections of files.</p>
1354 *
1355 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1356 * to return the appropriate MIME type for the data returned here with
1357 * the same URI. This will allow intent resolution to automatically determine the data MIME
1358 * type and select the appropriate matching targets as part of its operation.</p>
1359 *
1360 * <p class="note">For better interoperability with other applications, it is recommended
1361 * that for any URIs that can be opened, you also support queries on them
1362 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1363 *
1364 * @param uri The URI whose file is to be opened.
1365 * @param mode Access mode for the file. May be "r" for read-only access,
1366 * "w" for write-only access (erasing whatever data is currently in
1367 * the file), "wa" for write-only access to append to any existing data,
1368 * "rw" for read and write access on any existing data, and "rwt" for read
1369 * and write access that truncates any existing file.
1370 * @param signal A signal to cancel the operation in progress, or
1371 * {@code null} if none. For example, if you are downloading a
1372 * file from the network to service a "rw" mode request, you
1373 * should periodically call
1374 * {@link CancellationSignal#throwIfCanceled()} to check whether
1375 * the client has canceled the request and abort the download.
1376 *
1377 * @return Returns a new AssetFileDescriptor which you can use to access
1378 * the file.
1379 *
1380 * @throws FileNotFoundException Throws FileNotFoundException if there is
1381 * no file associated with the given URI or the mode is invalid.
1382 * @throws SecurityException Throws SecurityException if the caller does
1383 * not have permission to access the file.
1384 *
1385 * @see #openFile(Uri, String)
1386 * @see #openFileHelper(Uri, String)
1387 * @see #getType(android.net.Uri)
1388 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001389 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1390 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001391 return openAssetFile(uri, mode);
1392 }
1393
1394 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 * Convenience for subclasses that wish to implement {@link #openFile}
1396 * by looking up a column named "_data" at the given URI.
1397 *
1398 * @param uri The URI to be opened.
1399 * @param mode The file mode. May be "r" for read-only access,
1400 * "w" for write-only access (erasing whatever data is currently in
1401 * the file), "wa" for write-only access to append to any existing data,
1402 * "rw" for read and write access on any existing data, and "rwt" for read
1403 * and write access that truncates any existing file.
1404 *
1405 * @return Returns a new ParcelFileDescriptor that can be used by the
1406 * client to access the file.
1407 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001408 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1409 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1411 int count = (c != null) ? c.getCount() : 0;
1412 if (count != 1) {
1413 // If there is not exactly one result, throw an appropriate
1414 // exception.
1415 if (c != null) {
1416 c.close();
1417 }
1418 if (count == 0) {
1419 throw new FileNotFoundException("No entry for " + uri);
1420 }
1421 throw new FileNotFoundException("Multiple items at " + uri);
1422 }
1423
1424 c.moveToFirst();
1425 int i = c.getColumnIndex("_data");
1426 String path = (i >= 0 ? c.getString(i) : null);
1427 c.close();
1428 if (path == null) {
1429 throw new FileNotFoundException("Column _data not found.");
1430 }
1431
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001432 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 return ParcelFileDescriptor.open(new File(path), modeBits);
1434 }
1435
1436 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001437 * Called by a client to determine the types of data streams that this
1438 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001439 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001440 * of a particular type, return that MIME type if it matches the given
1441 * mimeTypeFilter. If it can perform type conversions, return an array
1442 * of all supported MIME types that match mimeTypeFilter.
1443 *
1444 * @param uri The data in the content provider being queried.
1445 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001446 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001447 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001448 * given mimeTypeFilter. Otherwise returns an array of all available
1449 * concrete MIME types.
1450 *
1451 * @see #getType(Uri)
1452 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001453 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001454 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001455 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001456 return null;
1457 }
1458
1459 /**
1460 * Called by a client to open a read-only stream containing data of a
1461 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1462 * except the file can only be read-only and the content provider may
1463 * perform data conversions to generate data of the desired type.
1464 *
1465 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001466 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001467 * {@link #openAssetFile(Uri, String)}.
1468 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001469 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001470 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001471 * <p>
1472 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1473 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001474 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001475 * <p class="note">For better interoperability with other applications, it is recommended
1476 * that for any URIs that can be opened, you also support queries on them
1477 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1478 * You may also want to support other common columns if you have additional meta-data
1479 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1480 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1481 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001482 * @param uri The data in the content provider being queried.
1483 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001484 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001485 * requirements; in this case the content provider will pick its best
1486 * type matching the pattern.
1487 * @param opts Additional options from the client. The definitions of
1488 * these are specific to the content provider being called.
1489 *
1490 * @return Returns a new AssetFileDescriptor from which the client can
1491 * read data of the desired type.
1492 *
1493 * @throws FileNotFoundException Throws FileNotFoundException if there is
1494 * no file associated with the given URI or the mode is invalid.
1495 * @throws SecurityException Throws SecurityException if the caller does
1496 * not have permission to access the data.
1497 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1498 * content provider does not support the requested MIME type.
1499 *
1500 * @see #getStreamTypes(Uri, String)
1501 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001502 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001503 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001504 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1505 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001506 if ("*/*".equals(mimeTypeFilter)) {
1507 // If they can take anything, the untyped open call is good enough.
1508 return openAssetFile(uri, "r");
1509 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001510 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001511 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001512 // Use old untyped open call if this provider has a type for this
1513 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001514 return openAssetFile(uri, "r");
1515 }
1516 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1517 }
1518
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001519
1520 /**
1521 * Called by a client to open a read-only stream containing data of a
1522 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1523 * except the file can only be read-only and the content provider may
1524 * perform data conversions to generate data of the desired type.
1525 *
1526 * <p>The default implementation compares the given mimeType against the
1527 * result of {@link #getType(Uri)} and, if they match, simply calls
1528 * {@link #openAssetFile(Uri, String)}.
1529 *
1530 * <p>See {@link ClipData} for examples of the use and implementation
1531 * of this method.
1532 * <p>
1533 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1534 * streaming of data.
1535 *
1536 * <p class="note">For better interoperability with other applications, it is recommended
1537 * that for any URIs that can be opened, you also support queries on them
1538 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1539 * You may also want to support other common columns if you have additional meta-data
1540 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1541 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1542 *
1543 * @param uri The data in the content provider being queried.
1544 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001545 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001546 * requirements; in this case the content provider will pick its best
1547 * type matching the pattern.
1548 * @param opts Additional options from the client. The definitions of
1549 * these are specific to the content provider being called.
1550 * @param signal A signal to cancel the operation in progress, or
1551 * {@code null} if none. For example, if you are downloading a
1552 * file from the network to service a "rw" mode request, you
1553 * should periodically call
1554 * {@link CancellationSignal#throwIfCanceled()} to check whether
1555 * the client has canceled the request and abort the download.
1556 *
1557 * @return Returns a new AssetFileDescriptor from which the client can
1558 * read data of the desired type.
1559 *
1560 * @throws FileNotFoundException Throws FileNotFoundException if there is
1561 * no file associated with the given URI or the mode is invalid.
1562 * @throws SecurityException Throws SecurityException if the caller does
1563 * not have permission to access the data.
1564 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1565 * content provider does not support the requested MIME type.
1566 *
1567 * @see #getStreamTypes(Uri, String)
1568 * @see #openAssetFile(Uri, String)
1569 * @see ClipDescription#compareMimeTypes(String, String)
1570 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001571 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1572 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1573 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001574 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1575 }
1576
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001577 /**
1578 * Interface to write a stream of data to a pipe. Use with
1579 * {@link ContentProvider#openPipeHelper}.
1580 */
1581 public interface PipeDataWriter<T> {
1582 /**
1583 * Called from a background thread to stream data out to a pipe.
1584 * Note that the pipe is blocking, so this thread can block on
1585 * writes for an arbitrary amount of time if the client is slow
1586 * at reading.
1587 *
1588 * @param output The pipe where data should be written. This will be
1589 * closed for you upon returning from this function.
1590 * @param uri The URI whose data is to be written.
1591 * @param mimeType The desired type of data to be written.
1592 * @param opts Options supplied by caller.
1593 * @param args Your own custom arguments.
1594 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001595 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1596 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001597 }
1598
1599 /**
1600 * A helper function for implementing {@link #openTypedAssetFile}, for
1601 * creating a data pipe and background thread allowing you to stream
1602 * generated data back to the client. This function returns a new
1603 * ParcelFileDescriptor that should be returned to the caller (the caller
1604 * is responsible for closing it).
1605 *
1606 * @param uri The URI whose data is to be written.
1607 * @param mimeType The desired type of data to be written.
1608 * @param opts Options supplied by caller.
1609 * @param args Your own custom arguments.
1610 * @param func Interface implementing the function that will actually
1611 * stream the data.
1612 * @return Returns a new ParcelFileDescriptor holding the read side of
1613 * the pipe. This should be returned to the caller for reading; the caller
1614 * is responsible for closing it when done.
1615 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001616 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1617 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1618 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001619 try {
1620 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1621
1622 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1623 @Override
1624 protected Object doInBackground(Object... params) {
1625 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1626 try {
1627 fds[1].close();
1628 } catch (IOException e) {
1629 Log.w(TAG, "Failure closing pipe", e);
1630 }
1631 return null;
1632 }
1633 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001634 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001635
1636 return fds[0];
1637 } catch (IOException e) {
1638 throw new FileNotFoundException("failure making pipe");
1639 }
1640 }
1641
1642 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 * Returns true if this instance is a temporary content provider.
1644 * @return true if this instance is a temporary content provider
1645 */
1646 protected boolean isTemporary() {
1647 return false;
1648 }
1649
1650 /**
1651 * Returns the Binder object for this provider.
1652 *
1653 * @return the Binder object for this provider
1654 * @hide
1655 */
1656 public IContentProvider getIContentProvider() {
1657 return mTransport;
1658 }
1659
1660 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001661 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1662 * when directly instantiating the provider for testing.
1663 * @hide
1664 */
1665 public void attachInfoForTesting(Context context, ProviderInfo info) {
1666 attachInfo(context, info, true);
1667 }
1668
1669 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 * After being instantiated, this is called to tell the content provider
1671 * about itself.
1672 *
1673 * @param context The context this provider is running in
1674 * @param info Registered information about this content provider
1675 */
1676 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001677 attachInfo(context, info, false);
1678 }
1679
1680 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001681 mNoPerms = testing;
1682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 /*
1684 * Only allow it to be set once, so after the content service gives
1685 * this to us clients can't change it.
1686 */
1687 if (mContext == null) {
1688 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001689 if (context != null) {
1690 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1691 Context.APP_OPS_SERVICE);
1692 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001693 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 if (info != null) {
1695 setReadPermission(info.readPermission);
1696 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001697 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001698 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001699 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001700 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
1702 ContentProvider.this.onCreate();
1703 }
1704 }
Fred Quintanace31b232009-05-04 16:01:15 -07001705
1706 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001707 * Override this to handle requests to perform a batch of operations, or the
1708 * default implementation will iterate over the operations and call
1709 * {@link ContentProviderOperation#apply} on each of them.
1710 * If all calls to {@link ContentProviderOperation#apply} succeed
1711 * then a {@link ContentProviderResult} array with as many
1712 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001713 * fail, it is up to the implementation how many of the others take effect.
1714 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001715 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1716 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001717 *
Fred Quintanace31b232009-05-04 16:01:15 -07001718 * @param operations the operations to apply
1719 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001720 * @throws OperationApplicationException thrown if any operation fails.
1721 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001722 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001723 public @NonNull ContentProviderResult[] applyBatch(
1724 @NonNull ArrayList<ContentProviderOperation> operations)
1725 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001726 final int numOperations = operations.size();
1727 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1728 for (int i = 0; i < numOperations; i++) {
1729 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001730 }
1731 return results;
1732 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001733
1734 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001735 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001736 * interfaces that are cheaper and/or unnatural for a table-like
1737 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001738 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001739 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1740 * on this entry into the content provider besides the basic ability for the application
1741 * to get access to the provider at all. For example, it has no idea whether the call
1742 * being executed may read or write data in the provider, so can't enforce those
1743 * individual permissions. Any implementation of this method <strong>must</strong>
1744 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1745 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001746 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1747 * @param arg provider-defined String argument. May be {@code null}.
1748 * @param extras provider-defined Bundle argument. May be {@code null}.
1749 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001750 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001751 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001752 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
1753 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001754 return null;
1755 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001756
1757 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001758 * Implement this to shut down the ContentProvider instance. You can then
1759 * invoke this method in unit tests.
1760 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001761 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001762 * Android normally handles ContentProvider startup and shutdown
1763 * automatically. You do not need to start up or shut down a
1764 * ContentProvider. When you invoke a test method on a ContentProvider,
1765 * however, a ContentProvider instance is started and keeps running after
1766 * the test finishes, even if a succeeding test instantiates another
1767 * ContentProvider. A conflict develops because the two instances are
1768 * usually running against the same underlying data source (for example, an
1769 * sqlite database).
1770 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001771 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001772 * Implementing shutDown() avoids this conflict by providing a way to
1773 * terminate the ContentProvider. This method can also prevent memory leaks
1774 * from multiple instantiations of the ContentProvider, and it can ensure
1775 * unit test isolation by allowing you to completely clean up the test
1776 * fixture before moving on to the next test.
1777 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001778 */
1779 public void shutdown() {
1780 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1781 "connections are gracefully shutdown");
1782 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001783
1784 /**
1785 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001786 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001787 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001788 * @param fd The raw file descriptor that the dump is being sent to.
1789 * @param writer The PrintWriter to which you should dump your state. This will be
1790 * closed for you after you return.
1791 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001792 */
1793 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1794 writer.println("nothing to dump");
1795 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001796
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001797 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001798 private void validateIncomingUri(Uri uri) throws SecurityException {
1799 String auth = uri.getAuthority();
1800 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001801 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
1802 throw new SecurityException("trying to query a ContentProvider in user "
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001803 + mContext.getUserId() + " with a uri belonging to user " + userId);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001804 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001805 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
1806 String message = "The authority of the uri " + uri + " does not match the one of the "
1807 + "contentProvider: ";
1808 if (mAuthority != null) {
1809 message += mAuthority;
1810 } else {
1811 message += mAuthorities;
1812 }
1813 throw new SecurityException(message);
1814 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001815 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001816
1817 /** @hide */
1818 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1819 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001820 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001821 if (end == -1) return defaultUserId;
1822 String userIdString = auth.substring(0, end);
1823 try {
1824 return Integer.parseInt(userIdString);
1825 } catch (NumberFormatException e) {
1826 Log.w(TAG, "Error parsing userId.", e);
1827 return UserHandle.USER_NULL;
1828 }
1829 }
1830
1831 /** @hide */
1832 public static int getUserIdFromAuthority(String auth) {
1833 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1834 }
1835
1836 /** @hide */
1837 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1838 if (uri == null) return defaultUserId;
1839 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1840 }
1841
1842 /** @hide */
1843 public static int getUserIdFromUri(Uri uri) {
1844 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1845 }
1846
1847 /**
1848 * Removes userId part from authority string. Expects format:
1849 * userId@some.authority
1850 * If there is no userId in the authority, it symply returns the argument
1851 * @hide
1852 */
1853 public static String getAuthorityWithoutUserId(String auth) {
1854 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001855 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001856 return auth.substring(end+1);
1857 }
1858
1859 /** @hide */
1860 public static Uri getUriWithoutUserId(Uri uri) {
1861 if (uri == null) return null;
1862 Uri.Builder builder = uri.buildUpon();
1863 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1864 return builder.build();
1865 }
1866
1867 /** @hide */
1868 public static boolean uriHasUserId(Uri uri) {
1869 if (uri == null) return false;
1870 return !TextUtils.isEmpty(uri.getUserInfo());
1871 }
1872
1873 /** @hide */
1874 public static Uri maybeAddUserId(Uri uri, int userId) {
1875 if (uri == null) return null;
1876 if (userId != UserHandle.USER_CURRENT
1877 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1878 if (!uriHasUserId(uri)) {
1879 //We don't add the user Id if there's already one
1880 Uri.Builder builder = uri.buildUpon();
1881 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1882 return builder.build();
1883 }
1884 }
1885 return uri;
1886 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001887}