blob: 3cc76841bd706a60a2b49e8ee34945b1d8e3a28b [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));
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700226 if (cursor == null) {
227 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700228 }
229
230 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700231 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800232 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700233 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700234 try {
235 return ContentProvider.this.query(
236 uri, projection, selection, selectionArgs, sortOrder,
237 CancellationSignal.fromTransport(cancellationSignal));
238 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700239 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 }
242
Jeff Brown75ea64f2012-01-25 19:37:13 -0800243 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100245 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100246 uri = getUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 return ContentProvider.this.getType(uri);
248 }
249
Jeff Brown75ea64f2012-01-25 19:37:13 -0800250 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800251 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100252 validateIncomingUri(uri);
253 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100254 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800255 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800256 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800257 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700258 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700259 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100260 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700261 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700262 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 }
265
Jeff Brown75ea64f2012-01-25 19:37:13 -0800266 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800267 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100268 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100269 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800270 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800271 return 0;
272 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700273 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700274 try {
275 return ContentProvider.this.bulkInsert(uri, initialValues);
276 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700277 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800279 }
280
Jeff Brown75ea64f2012-01-25 19:37:13 -0800281 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800282 public ContentProviderResult[] applyBatch(String callingPkg,
283 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700284 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100285 int numOperations = operations.size();
286 final int[] userIds = new int[numOperations];
287 for (int i = 0; i < numOperations; i++) {
288 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100289 Uri uri = operation.getUri();
290 validateIncomingUri(uri);
291 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100292 if (userIds[i] != UserHandle.USER_CURRENT) {
293 // Removing the user id from the uri.
294 operation = new ContentProviderOperation(operation, true);
295 operations.set(i, operation);
296 }
Fred Quintana89437372009-05-15 15:10:40 -0700297 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800298 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800299 != AppOpsManager.MODE_ALLOWED) {
300 throw new OperationApplicationException("App op not allowed", 0);
301 }
Fred Quintana89437372009-05-15 15:10:40 -0700302 }
Fred Quintana89437372009-05-15 15:10:40 -0700303 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800304 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800305 != AppOpsManager.MODE_ALLOWED) {
306 throw new OperationApplicationException("App op not allowed", 0);
307 }
Fred Quintana89437372009-05-15 15:10:40 -0700308 }
309 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700310 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700311 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100312 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800313 if (results != null) {
314 for (int i = 0; i < results.length ; i++) {
315 if (userIds[i] != UserHandle.USER_CURRENT) {
316 // Adding the userId to the uri.
317 results[i] = new ContentProviderResult(results[i], userIds[i]);
318 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100319 }
320 }
321 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700322 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700323 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700324 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700325 }
326
Jeff Brown75ea64f2012-01-25 19:37:13 -0800327 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800328 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100329 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100330 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800331 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800332 return 0;
333 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700334 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700335 try {
336 return ContentProvider.this.delete(uri, selection, selectionArgs);
337 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700338 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 }
341
Jeff Brown75ea64f2012-01-25 19:37:13 -0800342 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800343 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100345 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100346 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800347 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800348 return 0;
349 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700350 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700351 try {
352 return ContentProvider.this.update(uri, values, selection, selectionArgs);
353 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700354 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 }
357
Jeff Brown75ea64f2012-01-25 19:37:13 -0800358 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700359 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800360 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
361 IBinder callerToken) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100362 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100363 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800364 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700365 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700366 try {
367 return ContentProvider.this.openFile(
368 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
369 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700370 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 }
373
Jeff Brown75ea64f2012-01-25 19:37:13 -0800374 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700375 public AssetFileDescriptor openAssetFile(
376 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100378 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100379 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800380 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700381 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700382 try {
383 return ContentProvider.this.openAssetFile(
384 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
385 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700386 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 }
389
Jeff Brown75ea64f2012-01-25 19:37:13 -0800390 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800391 public Bundle call(
392 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700393 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700394 try {
395 return ContentProvider.this.call(method, arg, extras);
396 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700397 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700398 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800399 }
400
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700401 @Override
402 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100403 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100404 uri = getUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700405 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
406 }
407
408 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800409 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700410 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100411 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100412 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800413 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700414 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700415 try {
416 return ContentProvider.this.openTypedAssetFile(
417 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
418 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700419 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700420 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700421 }
422
Jeff Brown75ea64f2012-01-25 19:37:13 -0800423 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700424 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800425 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800426 }
427
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700428 @Override
429 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100430 validateIncomingUri(uri);
431 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100432 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800433 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700434 return null;
435 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700436 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700437 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100438 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700439 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700440 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700441 }
442 }
443
444 @Override
445 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100446 validateIncomingUri(uri);
447 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100448 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800449 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700450 return null;
451 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700452 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700453 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100454 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700455 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700456 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700457 }
458 }
459
Dianne Hackbornff170242014-11-19 10:59:01 -0800460 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
461 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800462 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800463 if (enforceWritePermission(callingPkg, uri, callerToken)
464 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800465 throw new FileNotFoundException("App op not allowed");
466 }
467 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800468 if (enforceReadPermission(callingPkg, uri, callerToken)
469 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800470 throw new FileNotFoundException("App op not allowed");
471 }
472 }
473 }
474
Dianne Hackbornff170242014-11-19 10:59:01 -0800475 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
476 throws SecurityException {
477 enforceReadPermissionInner(uri, callerToken);
Svet Ganov99b60432015-06-27 13:15:22 -0700478
479 final int permOp = AppOpsManager.permissionToOpCode(mReadPermission);
480 if (permOp != AppOpsManager.OP_NONE) {
481 final int mode = mAppOpsManager.noteProxyOp(permOp, callingPkg);
482 if (mode != AppOpsManager.MODE_ALLOWED) {
483 return mode;
484 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800485 }
Svet Ganov99b60432015-06-27 13:15:22 -0700486
487 if (mReadOp != AppOpsManager.OP_NONE) {
488 return mAppOpsManager.noteProxyOp(mReadOp, callingPkg);
489 }
490
Dianne Hackborn35654b62013-01-14 17:38:02 -0800491 return AppOpsManager.MODE_ALLOWED;
492 }
493
Dianne Hackbornff170242014-11-19 10:59:01 -0800494 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
495 throws SecurityException {
496 enforceWritePermissionInner(uri, callerToken);
Svet Ganov99b60432015-06-27 13:15:22 -0700497
498 final int permOp = AppOpsManager.permissionToOpCode(mWritePermission);
499 if (permOp != AppOpsManager.OP_NONE) {
500 final int mode = mAppOpsManager.noteProxyOp(permOp, callingPkg);
501 if (mode != AppOpsManager.MODE_ALLOWED) {
502 return mode;
503 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800504 }
Svet Ganov99b60432015-06-27 13:15:22 -0700505
506 if (mWriteOp != AppOpsManager.OP_NONE) {
507 return mAppOpsManager.noteProxyOp(mWriteOp, callingPkg);
508 }
509
Dianne Hackborn35654b62013-01-14 17:38:02 -0800510 return AppOpsManager.MODE_ALLOWED;
511 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700512 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800513
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100514 boolean checkUser(int pid, int uid, Context context) {
515 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700516 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100517 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
518 == PERMISSION_GRANTED;
519 }
520
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700521 /** {@hide} */
Dianne Hackbornff170242014-11-19 10:59:01 -0800522 protected void enforceReadPermissionInner(Uri uri, IBinder callerToken)
523 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700524 final Context context = getContext();
525 final int pid = Binder.getCallingPid();
526 final int uid = Binder.getCallingUid();
527 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700528
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700529 if (UserHandle.isSameApp(uid, mMyUid)) {
530 return;
531 }
532
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100533 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700534 final String componentPerm = getReadPermission();
535 if (componentPerm != null) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800536 if (context.checkPermission(componentPerm, pid, uid, callerToken)
537 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700538 return;
539 } else {
540 missingPerm = componentPerm;
541 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700542 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700543
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700544 // track if unprotected read is allowed; any denied
545 // <path-permission> below removes this ability
546 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700547
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700548 final PathPermission[] pps = getPathPermissions();
549 if (pps != null) {
550 final String path = uri.getPath();
551 for (PathPermission pp : pps) {
552 final String pathPerm = pp.getReadPermission();
553 if (pathPerm != null && pp.match(path)) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800554 if (context.checkPermission(pathPerm, pid, uid, callerToken)
555 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700556 return;
557 } else {
558 // any denied <path-permission> means we lose
559 // default <provider> access.
560 allowDefaultRead = false;
561 missingPerm = pathPerm;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700562 }
563 }
564 }
565 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700566
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700567 // if we passed <path-permission> checks above, and no default
568 // <provider> permission, then allow access.
569 if (allowDefaultRead) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700571
572 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800573 final int callingUserId = UserHandle.getUserId(uid);
574 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
575 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800576 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
577 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700578 return;
579 }
580
581 final String failReason = mExported
582 ? " requires " + missingPerm + ", or grantUriPermission()"
583 : " requires the provider be exported, or grantUriPermission()";
584 throw new SecurityException("Permission Denial: reading "
585 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
586 + ", uid=" + uid + failReason);
587 }
588
589 /** {@hide} */
Dianne Hackbornff170242014-11-19 10:59:01 -0800590 protected void enforceWritePermissionInner(Uri uri, IBinder callerToken)
591 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700592 final Context context = getContext();
593 final int pid = Binder.getCallingPid();
594 final int uid = Binder.getCallingUid();
595 String missingPerm = null;
596
597 if (UserHandle.isSameApp(uid, mMyUid)) {
598 return;
599 }
600
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100601 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700602 final String componentPerm = getWritePermission();
603 if (componentPerm != null) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800604 if (context.checkPermission(componentPerm, pid, uid, callerToken)
605 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700606 return;
607 } else {
608 missingPerm = componentPerm;
609 }
610 }
611
612 // track if unprotected write is allowed; any denied
613 // <path-permission> below removes this ability
614 boolean allowDefaultWrite = (componentPerm == null);
615
616 final PathPermission[] pps = getPathPermissions();
617 if (pps != null) {
618 final String path = uri.getPath();
619 for (PathPermission pp : pps) {
620 final String pathPerm = pp.getWritePermission();
621 if (pathPerm != null && pp.match(path)) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800622 if (context.checkPermission(pathPerm, pid, uid, callerToken)
623 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700624 return;
625 } else {
626 // any denied <path-permission> means we lose
627 // default <provider> access.
628 allowDefaultWrite = false;
629 missingPerm = pathPerm;
630 }
631 }
632 }
633 }
634
635 // if we passed <path-permission> checks above, and no default
636 // <provider> permission, then allow access.
637 if (allowDefaultWrite) return;
638 }
639
640 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800641 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
642 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700643 return;
644 }
645
646 final String failReason = mExported
647 ? " requires " + missingPerm + ", or grantUriPermission()"
648 : " requires the provider be exported, or grantUriPermission()";
649 throw new SecurityException("Permission Denial: writing "
650 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
651 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 }
653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700655 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800656 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 * constructor.
658 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700659 public final @Nullable Context getContext() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 return mContext;
661 }
662
663 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700664 * Set the calling package, returning the current value (or {@code null})
665 * which can be used later to restore the previous state.
666 */
667 private String setCallingPackage(String callingPackage) {
668 final String original = mCallingPackage.get();
669 mCallingPackage.set(callingPackage);
670 return original;
671 }
672
673 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700674 * Return the package name of the caller that initiated the request being
675 * processed on the current thread. The returned package will have been
676 * verified to belong to the calling UID. Returns {@code null} if not
677 * currently processing a request.
678 * <p>
679 * This will always return {@code null} when processing
680 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
681 *
682 * @see Binder#getCallingUid()
683 * @see Context#grantUriPermission(String, Uri, int)
684 * @throws SecurityException if the calling package doesn't belong to the
685 * calling UID.
686 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700687 public final @Nullable String getCallingPackage() {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700688 final String pkg = mCallingPackage.get();
689 if (pkg != null) {
690 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
691 }
692 return pkg;
693 }
694
695 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100696 * Change the authorities of the ContentProvider.
697 * This is normally set for you from its manifest information when the provider is first
698 * created.
699 * @hide
700 * @param authorities the semi-colon separated authorities of the ContentProvider.
701 */
702 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100703 if (authorities != null) {
704 if (authorities.indexOf(';') == -1) {
705 mAuthority = authorities;
706 mAuthorities = null;
707 } else {
708 mAuthority = null;
709 mAuthorities = authorities.split(";");
710 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100711 }
712 }
713
714 /** @hide */
715 protected final boolean matchesOurAuthorities(String authority) {
716 if (mAuthority != null) {
717 return mAuthority.equals(authority);
718 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100719 if (mAuthorities != null) {
720 int length = mAuthorities.length;
721 for (int i = 0; i < length; i++) {
722 if (mAuthorities[i].equals(authority)) return true;
723 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100724 }
725 return false;
726 }
727
728
729 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 * Change the permission required to read data from the content
731 * provider. This is normally set for you from its manifest information
732 * when the provider is first created.
733 *
734 * @param permission Name of the permission required for read-only access.
735 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700736 protected final void setReadPermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 mReadPermission = permission;
738 }
739
740 /**
741 * Return the name of the permission required for read-only access to
742 * this content provider. This method can be called from multiple
743 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800744 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
745 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700747 public final @Nullable String getReadPermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 return mReadPermission;
749 }
750
751 /**
752 * Change the permission required to read and write data in the content
753 * provider. This is normally set for you from its manifest information
754 * when the provider is first created.
755 *
756 * @param permission Name of the permission required for read/write access.
757 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700758 protected final void setWritePermission(@Nullable String permission) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 mWritePermission = permission;
760 }
761
762 /**
763 * Return the name of the permission required for read/write access to
764 * this content provider. This method can be called from multiple
765 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800766 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
767 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700769 public final @Nullable String getWritePermission() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 return mWritePermission;
771 }
772
773 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700774 * Change the path-based permission required to read and/or write data in
775 * the content provider. This is normally set for you from its manifest
776 * information when the provider is first created.
777 *
778 * @param permissions Array of path permission descriptions.
779 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700780 protected final void setPathPermissions(@Nullable PathPermission[] permissions) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700781 mPathPermissions = permissions;
782 }
783
784 /**
785 * Return the path-based permissions required for read and/or write access to
786 * this content provider. This method can be called from multiple
787 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800788 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
789 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700790 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700791 public final @Nullable PathPermission[] getPathPermissions() {
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700792 return mPathPermissions;
793 }
794
Dianne Hackborn35654b62013-01-14 17:38:02 -0800795 /** @hide */
796 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800797 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800798 mTransport.mReadOp = readOp;
799 mTransport.mWriteOp = writeOp;
800 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800801 }
802
Dianne Hackborn961321f2013-02-05 17:22:41 -0800803 /** @hide */
804 public AppOpsManager getAppOpsManager() {
805 return mTransport.mAppOpsManager;
806 }
807
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700808 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700809 * Implement this to initialize your content provider on startup.
810 * This method is called for all registered content providers on the
811 * application main thread at application launch time. It must not perform
812 * lengthy operations, or application startup will be delayed.
813 *
814 * <p>You should defer nontrivial initialization (such as opening,
815 * upgrading, and scanning databases) until the content provider is used
816 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
817 * keeps application startup fast, avoids unnecessary work if the provider
818 * turns out not to be needed, and stops database errors (such as a full
819 * disk) from halting application launch.
820 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700821 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700822 * is a helpful utility class that makes it easy to manage databases,
823 * and will automatically defer opening until first use. If you do use
824 * SQLiteOpenHelper, make sure to avoid calling
825 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
826 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
827 * from this method. (Instead, override
828 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
829 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 *
831 * @return true if the provider was successfully loaded, false otherwise
832 */
833 public abstract boolean onCreate();
834
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700835 /**
836 * {@inheritDoc}
837 * This method is always called on the application main thread, and must
838 * not perform lengthy operations.
839 *
840 * <p>The default content provider implementation does nothing.
841 * Override this method to take appropriate action.
842 * (Content providers do not usually care about things like screen
843 * orientation, but may want to know about locale changes.)
844 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 public void onConfigurationChanged(Configuration newConfig) {
846 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700847
848 /**
849 * {@inheritDoc}
850 * This method is always called on the application main thread, and must
851 * not perform lengthy operations.
852 *
853 * <p>The default content provider implementation does nothing.
854 * Subclasses may override this method to take appropriate action.
855 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 public void onLowMemory() {
857 }
858
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700859 public void onTrimMemory(int level) {
860 }
861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700863 * Implement this to handle query requests from clients.
864 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800865 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
866 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 * <p>
868 * Example client call:<p>
869 * <pre>// Request a specific record.
870 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000871 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 projection, // Which columns to return.
873 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000874 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 People.NAME + " ASC"); // Sort order.</pre>
876 * Example implementation:<p>
877 * <pre>// SQLiteQueryBuilder is a helper class that creates the
878 // proper SQL syntax for us.
879 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
880
881 // Set the table we're querying.
882 qBuilder.setTables(DATABASE_TABLE_NAME);
883
884 // If the query ends in a specific record number, we're
885 // being asked for a specific record, so set the
886 // WHERE clause in our query.
887 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
888 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
889 }
890
891 // Make the query.
892 Cursor c = qBuilder.query(mDb,
893 projection,
894 selection,
895 selectionArgs,
896 groupBy,
897 having,
898 sortOrder);
899 c.setNotificationUri(getContext().getContentResolver(), uri);
900 return c;</pre>
901 *
902 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000903 * if the client is requesting a specific record, the URI will end in a record number
904 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
905 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800907 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800909 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000910 * @param selectionArgs You may include ?s in selection, which will be replaced by
911 * the values from selectionArgs, in order that they appear in the selection.
912 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800914 * If {@code null} then the provider is free to define the sort order.
915 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700917 public abstract @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
918 @Nullable String selection, @Nullable String[] selectionArgs,
919 @Nullable String sortOrder);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920
Fred Quintana5bba6322009-10-05 14:21:12 -0700921 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800922 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800923 * This method can be called from multiple threads, as described in
924 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
925 * and Threads</a>.
926 * <p>
927 * Example client call:<p>
928 * <pre>// Request a specific record.
929 * Cursor managedCursor = managedQuery(
930 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
931 projection, // Which columns to return.
932 null, // WHERE clause.
933 null, // WHERE clause value substitution
934 People.NAME + " ASC"); // Sort order.</pre>
935 * Example implementation:<p>
936 * <pre>// SQLiteQueryBuilder is a helper class that creates the
937 // proper SQL syntax for us.
938 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
939
940 // Set the table we're querying.
941 qBuilder.setTables(DATABASE_TABLE_NAME);
942
943 // If the query ends in a specific record number, we're
944 // being asked for a specific record, so set the
945 // WHERE clause in our query.
946 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
947 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
948 }
949
950 // Make the query.
951 Cursor c = qBuilder.query(mDb,
952 projection,
953 selection,
954 selectionArgs,
955 groupBy,
956 having,
957 sortOrder);
958 c.setNotificationUri(getContext().getContentResolver(), uri);
959 return c;</pre>
960 * <p>
961 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800962 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
963 * signal to ensure correct operation on older versions of the Android Framework in
964 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800965 *
966 * @param uri The URI to query. This will be the full URI sent by the client;
967 * if the client is requesting a specific record, the URI will end in a record number
968 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
969 * that _id value.
970 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800971 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800972 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800973 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800974 * @param selectionArgs You may include ?s in selection, which will be replaced by
975 * the values from selectionArgs, in order that they appear in the selection.
976 * The values will be bound as Strings.
977 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800978 * If {@code null} then the provider is free to define the sort order.
979 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800980 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
981 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800982 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800983 */
Jeff Sharkey673db442015-06-11 19:30:57 -0700984 public @Nullable Cursor query(@NonNull Uri uri, @Nullable String[] projection,
985 @Nullable String selection, @Nullable String[] selectionArgs,
986 @Nullable String sortOrder, @Nullable CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800987 return query(uri, projection, selection, selectionArgs, sortOrder);
988 }
989
990 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700991 * Implement this to handle requests for the MIME type of the data at the
992 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 * <code>vnd.android.cursor.item</code> for a single record,
994 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700995 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800996 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
997 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700999 * <p>Note that there are no permissions needed for an application to
1000 * access this information; if your content provider requires read and/or
1001 * write permissions, or is not exported, all applications can still call
1002 * this method regardless of their access permissions. This allows them
1003 * to retrieve the MIME type for a URI when dispatching intents.
1004 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001006 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001008 public abstract @Nullable String getType(@NonNull Uri uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009
1010 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001011 * Implement this to support canonicalization of URIs that refer to your
1012 * content provider. A canonical URI is one that can be transported across
1013 * devices, backup/restore, and other contexts, and still be able to refer
1014 * to the same data item. Typically this is implemented by adding query
1015 * params to the URI allowing the content provider to verify that an incoming
1016 * canonical URI references the same data as it was originally intended for and,
1017 * if it doesn't, to find that data (if it exists) in the current environment.
1018 *
1019 * <p>For example, if the content provider holds people and a normal URI in it
1020 * is created with a row index into that people database, the cananical representation
1021 * may have an additional query param at the end which specifies the name of the
1022 * person it is intended for. Later calls into the provider with that URI will look
1023 * up the row of that URI's base index and, if it doesn't match or its entry's
1024 * name doesn't match the name in the query param, perform a query on its database
1025 * to find the correct row to operate on.</p>
1026 *
1027 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1028 * URIs (including this one) must perform this verification and recovery of any
1029 * canonical URIs they receive. In addition, you must also implement
1030 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1031 *
1032 * <p>The default implementation of this method returns null, indicating that
1033 * canonical URIs are not supported.</p>
1034 *
1035 * @param url The Uri to canonicalize.
1036 *
1037 * @return Return the canonical representation of <var>url</var>, or null if
1038 * canonicalization of that Uri is not supported.
1039 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001040 public @Nullable Uri canonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001041 return null;
1042 }
1043
1044 /**
1045 * Remove canonicalization from canonical URIs previously returned by
1046 * {@link #canonicalize}. For example, if your implementation is to add
1047 * a query param to canonicalize a URI, this method can simply trip any
1048 * query params on the URI. The default implementation always returns the
1049 * same <var>url</var> that was passed in.
1050 *
1051 * @param url The Uri to remove any canonicalization from.
1052 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001053 * @return Return the non-canonical representation of <var>url</var>, return
1054 * the <var>url</var> as-is if there is nothing to do, or return null if
1055 * the data identified by the canonical representation can not be found in
1056 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001057 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001058 public @Nullable Uri uncanonicalize(@NonNull Uri url) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001059 return url;
1060 }
1061
1062 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001063 * @hide
1064 * Implementation when a caller has performed an insert on the content
1065 * provider, but that call has been rejected for the operation given
1066 * to {@link #setAppOps(int, int)}. The default implementation simply
1067 * returns a dummy URI that is the base URI with a 0 path element
1068 * appended.
1069 */
1070 public Uri rejectInsert(Uri uri, ContentValues values) {
1071 // If not allowed, we need to return some reasonable URI. Maybe the
1072 // content provider should be responsible for this, but for now we
1073 // will just return the base URI with a dummy '0' tagged on to it.
1074 // You shouldn't be able to read if you can't write, anyway, so it
1075 // shouldn't matter much what is returned.
1076 return uri.buildUpon().appendPath("0").build();
1077 }
1078
1079 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001080 * Implement this to handle requests to insert a new row.
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>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001086 * @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 -08001087 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001088 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 * @return The URI for the newly inserted item.
1090 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001091 public abstract @Nullable Uri insert(@NonNull Uri uri, @Nullable ContentValues values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092
1093 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001094 * Override this to handle requests to insert a set of new rows, or the
1095 * default implementation will iterate over the values and call
1096 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1098 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001099 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001100 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1101 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 *
1103 * @param uri The content:// URI of the insertion request.
1104 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001105 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 * @return The number of values that were inserted.
1107 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001108 public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 int numValues = values.length;
1110 for (int i = 0; i < numValues; i++) {
1111 insert(uri, values[i]);
1112 }
1113 return numValues;
1114 }
1115
1116 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001117 * Implement this to handle requests to delete one or more rows.
1118 * The implementation should apply the selection clause when performing
1119 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001120 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001122 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001123 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1124 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 *
1126 * <p>The implementation is responsible for parsing out a row ID at the end
1127 * of the URI, if a specific row is being deleted. That is, the client would
1128 * pass in <code>content://contacts/people/22</code> and the implementation is
1129 * responsible for parsing the record number (22) when creating a SQL statement.
1130 *
1131 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1132 * @param selection An optional restriction to apply to rows when deleting.
1133 * @return The number of rows affected.
1134 * @throws SQLException
1135 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001136 public abstract int delete(@NonNull Uri uri, @Nullable String selection,
1137 @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138
1139 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001140 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001141 * The implementation should update all rows matching the selection
1142 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1144 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001145 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001146 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1147 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 *
1149 * @param uri The URI to query. This can potentially have a record ID if this
1150 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001151 * @param values A set of column_name/value pairs to update in the database.
1152 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 * @param selection An optional filter to match rows to update.
1154 * @return the number of rows affected.
1155 */
Jeff Sharkey34796bd2015-06-11 21:55:32 -07001156 public abstract int update(@NonNull Uri uri, @Nullable ContentValues values,
Jeff Sharkey673db442015-06-11 19:30:57 -07001157 @Nullable String selection, @Nullable String[] selectionArgs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158
1159 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001160 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001161 * The default implementation always throws {@link FileNotFoundException}.
1162 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001163 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1164 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001165 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001166 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1167 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001168 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 *
1170 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1171 * their responsibility to close it when done. That is, the implementation
1172 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001173 * <p>
1174 * If opened with the exclusive "r" or "w" modes, the returned
1175 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1176 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1177 * supports seeking.
1178 * <p>
1179 * If you need to detect when the returned ParcelFileDescriptor has been
1180 * closed, or if the remote process has crashed or encountered some other
1181 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1182 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1183 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1184 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001186 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1187 * to return the appropriate MIME type for the data returned here with
1188 * the same URI. This will allow intent resolution to automatically determine the data MIME
1189 * type and select the appropriate matching targets as part of its operation.</p>
1190 *
1191 * <p class="note">For better interoperability with other applications, it is recommended
1192 * that for any URIs that can be opened, you also support queries on them
1193 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1194 * You may also want to support other common columns if you have additional meta-data
1195 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1196 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1197 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 * @param uri The URI whose file is to be opened.
1199 * @param mode Access mode for the file. May be "r" for read-only access,
1200 * "rw" for read and write access, or "rwt" for read and write access
1201 * that truncates any existing file.
1202 *
1203 * @return Returns a new ParcelFileDescriptor which you can use to access
1204 * the file.
1205 *
1206 * @throws FileNotFoundException Throws FileNotFoundException if there is
1207 * no file associated with the given URI or the mode is invalid.
1208 * @throws SecurityException Throws SecurityException if the caller does
1209 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001210 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 * @see #openAssetFile(Uri, String)
1212 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001213 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001214 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001215 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001216 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 throws FileNotFoundException {
1218 throw new FileNotFoundException("No files supported by provider at "
1219 + uri);
1220 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001223 * Override this to handle requests to open a file blob.
1224 * The default implementation always throws {@link FileNotFoundException}.
1225 * This method can be called from multiple threads, as described in
1226 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1227 * and Threads</a>.
1228 *
1229 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1230 * to the caller. This way large data (such as images and documents) can be
1231 * returned without copying the content.
1232 *
1233 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1234 * their responsibility to close it when done. That is, the implementation
1235 * of this method should create a new ParcelFileDescriptor for each call.
1236 * <p>
1237 * If opened with the exclusive "r" or "w" modes, the returned
1238 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1239 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1240 * supports seeking.
1241 * <p>
1242 * If you need to detect when the returned ParcelFileDescriptor has been
1243 * closed, or if the remote process has crashed or encountered some other
1244 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1245 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1246 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1247 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1248 *
1249 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1250 * to return the appropriate MIME type for the data returned here with
1251 * the same URI. This will allow intent resolution to automatically determine the data MIME
1252 * type and select the appropriate matching targets as part of its operation.</p>
1253 *
1254 * <p class="note">For better interoperability with other applications, it is recommended
1255 * that for any URIs that can be opened, you also support queries on them
1256 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1257 * You may also want to support other common columns if you have additional meta-data
1258 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1259 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1260 *
1261 * @param uri The URI whose file is to be opened.
1262 * @param mode Access mode for the file. May be "r" for read-only access,
1263 * "w" for write-only access, "rw" for read and write access, or
1264 * "rwt" for read and write access that truncates any existing
1265 * file.
1266 * @param signal A signal to cancel the operation in progress, or
1267 * {@code null} if none. For example, if you are downloading a
1268 * file from the network to service a "rw" mode request, you
1269 * should periodically call
1270 * {@link CancellationSignal#throwIfCanceled()} to check whether
1271 * the client has canceled the request and abort the download.
1272 *
1273 * @return Returns a new ParcelFileDescriptor which you can use to access
1274 * the file.
1275 *
1276 * @throws FileNotFoundException Throws FileNotFoundException if there is
1277 * no file associated with the given URI or the mode is invalid.
1278 * @throws SecurityException Throws SecurityException if the caller does
1279 * not have permission to access the file.
1280 *
1281 * @see #openAssetFile(Uri, String)
1282 * @see #openFileHelper(Uri, String)
1283 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001284 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001285 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001286 public @Nullable ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode,
1287 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001288 return openFile(uri, mode);
1289 }
1290
1291 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 * This is like {@link #openFile}, but can be implemented by providers
1293 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001294 * inside of their .apk.
1295 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001296 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1297 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001298 *
1299 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001300 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001301 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1303 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1304 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001305 * <p>
1306 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1307 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001308 *
1309 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 * should create the AssetFileDescriptor with
1311 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001312 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001314 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1315 * to return the appropriate MIME type for the data returned here with
1316 * the same URI. This will allow intent resolution to automatically determine the data MIME
1317 * type and select the appropriate matching targets as part of its operation.</p>
1318 *
1319 * <p class="note">For better interoperability with other applications, it is recommended
1320 * that for any URIs that can be opened, you also support queries on them
1321 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1322 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 * @param uri The URI whose file is to be opened.
1324 * @param mode Access mode for the file. May be "r" for read-only access,
1325 * "w" for write-only access (erasing whatever data is currently in
1326 * the file), "wa" for write-only access to append to any existing data,
1327 * "rw" for read and write access on any existing data, and "rwt" for read
1328 * and write access that truncates any existing file.
1329 *
1330 * @return Returns a new AssetFileDescriptor which you can use to access
1331 * the file.
1332 *
1333 * @throws FileNotFoundException Throws FileNotFoundException if there is
1334 * no file associated with the given URI or the mode is invalid.
1335 * @throws SecurityException Throws SecurityException if the caller does
1336 * not have permission to access the file.
1337 *
1338 * @see #openFile(Uri, String)
1339 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001340 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001342 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 throws FileNotFoundException {
1344 ParcelFileDescriptor fd = openFile(uri, mode);
1345 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1346 }
1347
1348 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001349 * This is like {@link #openFile}, but can be implemented by providers
1350 * that need to be able to return sub-sections of files, often assets
1351 * inside of their .apk.
1352 * This method can be called from multiple threads, as described in
1353 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1354 * and Threads</a>.
1355 *
1356 * <p>If you implement this, your clients must be able to deal with such
1357 * file slices, either directly with
1358 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1359 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1360 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1361 * methods.
1362 * <p>
1363 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1364 * streaming of data.
1365 *
1366 * <p class="note">If you are implementing this to return a full file, you
1367 * should create the AssetFileDescriptor with
1368 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1369 * applications that cannot handle sub-sections of files.</p>
1370 *
1371 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1372 * to return the appropriate MIME type for the data returned here with
1373 * the same URI. This will allow intent resolution to automatically determine the data MIME
1374 * type and select the appropriate matching targets as part of its operation.</p>
1375 *
1376 * <p class="note">For better interoperability with other applications, it is recommended
1377 * that for any URIs that can be opened, you also support queries on them
1378 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1379 *
1380 * @param uri The URI whose file is to be opened.
1381 * @param mode Access mode for the file. May be "r" for read-only access,
1382 * "w" for write-only access (erasing whatever data is currently in
1383 * the file), "wa" for write-only access to append to any existing data,
1384 * "rw" for read and write access on any existing data, and "rwt" for read
1385 * and write access that truncates any existing file.
1386 * @param signal A signal to cancel the operation in progress, or
1387 * {@code null} if none. For example, if you are downloading a
1388 * file from the network to service a "rw" mode request, you
1389 * should periodically call
1390 * {@link CancellationSignal#throwIfCanceled()} to check whether
1391 * the client has canceled the request and abort the download.
1392 *
1393 * @return Returns a new AssetFileDescriptor which you can use to access
1394 * the file.
1395 *
1396 * @throws FileNotFoundException Throws FileNotFoundException if there is
1397 * no file associated with the given URI or the mode is invalid.
1398 * @throws SecurityException Throws SecurityException if the caller does
1399 * not have permission to access the file.
1400 *
1401 * @see #openFile(Uri, String)
1402 * @see #openFileHelper(Uri, String)
1403 * @see #getType(android.net.Uri)
1404 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001405 public @Nullable AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode,
1406 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001407 return openAssetFile(uri, mode);
1408 }
1409
1410 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 * Convenience for subclasses that wish to implement {@link #openFile}
1412 * by looking up a column named "_data" at the given URI.
1413 *
1414 * @param uri The URI to be opened.
1415 * @param mode The file mode. May be "r" for read-only access,
1416 * "w" for write-only access (erasing whatever data is currently in
1417 * the file), "wa" for write-only access to append to any existing data,
1418 * "rw" for read and write access on any existing data, and "rwt" for read
1419 * and write access that truncates any existing file.
1420 *
1421 * @return Returns a new ParcelFileDescriptor that can be used by the
1422 * client to access the file.
1423 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001424 protected final @NonNull ParcelFileDescriptor openFileHelper(@NonNull Uri uri,
1425 @NonNull String mode) throws FileNotFoundException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1427 int count = (c != null) ? c.getCount() : 0;
1428 if (count != 1) {
1429 // If there is not exactly one result, throw an appropriate
1430 // exception.
1431 if (c != null) {
1432 c.close();
1433 }
1434 if (count == 0) {
1435 throw new FileNotFoundException("No entry for " + uri);
1436 }
1437 throw new FileNotFoundException("Multiple items at " + uri);
1438 }
1439
1440 c.moveToFirst();
1441 int i = c.getColumnIndex("_data");
1442 String path = (i >= 0 ? c.getString(i) : null);
1443 c.close();
1444 if (path == null) {
1445 throw new FileNotFoundException("Column _data not found.");
1446 }
1447
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001448 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 return ParcelFileDescriptor.open(new File(path), modeBits);
1450 }
1451
1452 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001453 * Called by a client to determine the types of data streams that this
1454 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001455 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001456 * of a particular type, return that MIME type if it matches the given
1457 * mimeTypeFilter. If it can perform type conversions, return an array
1458 * of all supported MIME types that match mimeTypeFilter.
1459 *
1460 * @param uri The data in the content provider being queried.
1461 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001462 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001463 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001464 * given mimeTypeFilter. Otherwise returns an array of all available
1465 * concrete MIME types.
1466 *
1467 * @see #getType(Uri)
1468 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001469 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001470 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001471 public @Nullable String[] getStreamTypes(@NonNull Uri uri, @NonNull String mimeTypeFilter) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001472 return null;
1473 }
1474
1475 /**
1476 * Called by a client to open a read-only stream containing data of a
1477 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1478 * except the file can only be read-only and the content provider may
1479 * perform data conversions to generate data of the desired type.
1480 *
1481 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001482 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001483 * {@link #openAssetFile(Uri, String)}.
1484 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001485 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001486 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001487 * <p>
1488 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1489 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001490 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001491 * <p class="note">For better interoperability with other applications, it is recommended
1492 * that for any URIs that can be opened, you also support queries on them
1493 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1494 * You may also want to support other common columns if you have additional meta-data
1495 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1496 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1497 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001498 * @param uri The data in the content provider being queried.
1499 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001500 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001501 * requirements; in this case the content provider will pick its best
1502 * type matching the pattern.
1503 * @param opts Additional options from the client. The definitions of
1504 * these are specific to the content provider being called.
1505 *
1506 * @return Returns a new AssetFileDescriptor from which the client can
1507 * read data of the desired type.
1508 *
1509 * @throws FileNotFoundException Throws FileNotFoundException if there is
1510 * no file associated with the given URI or the mode is invalid.
1511 * @throws SecurityException Throws SecurityException if the caller does
1512 * not have permission to access the data.
1513 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1514 * content provider does not support the requested MIME type.
1515 *
1516 * @see #getStreamTypes(Uri, String)
1517 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001518 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001519 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001520 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1521 @NonNull String mimeTypeFilter, @Nullable Bundle opts) throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001522 if ("*/*".equals(mimeTypeFilter)) {
1523 // If they can take anything, the untyped open call is good enough.
1524 return openAssetFile(uri, "r");
1525 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001526 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001527 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001528 // Use old untyped open call if this provider has a type for this
1529 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001530 return openAssetFile(uri, "r");
1531 }
1532 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1533 }
1534
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001535
1536 /**
1537 * Called by a client to open a read-only stream containing data of a
1538 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1539 * except the file can only be read-only and the content provider may
1540 * perform data conversions to generate data of the desired type.
1541 *
1542 * <p>The default implementation compares the given mimeType against the
1543 * result of {@link #getType(Uri)} and, if they match, simply calls
1544 * {@link #openAssetFile(Uri, String)}.
1545 *
1546 * <p>See {@link ClipData} for examples of the use and implementation
1547 * of this method.
1548 * <p>
1549 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1550 * streaming of data.
1551 *
1552 * <p class="note">For better interoperability with other applications, it is recommended
1553 * that for any URIs that can be opened, you also support queries on them
1554 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1555 * You may also want to support other common columns if you have additional meta-data
1556 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1557 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1558 *
1559 * @param uri The data in the content provider being queried.
1560 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001561 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001562 * requirements; in this case the content provider will pick its best
1563 * type matching the pattern.
1564 * @param opts Additional options from the client. The definitions of
1565 * these are specific to the content provider being called.
1566 * @param signal A signal to cancel the operation in progress, or
1567 * {@code null} if none. For example, if you are downloading a
1568 * file from the network to service a "rw" mode request, you
1569 * should periodically call
1570 * {@link CancellationSignal#throwIfCanceled()} to check whether
1571 * the client has canceled the request and abort the download.
1572 *
1573 * @return Returns a new AssetFileDescriptor from which the client can
1574 * read data of the desired type.
1575 *
1576 * @throws FileNotFoundException Throws FileNotFoundException if there is
1577 * no file associated with the given URI or the mode is invalid.
1578 * @throws SecurityException Throws SecurityException if the caller does
1579 * not have permission to access the data.
1580 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1581 * content provider does not support the requested MIME type.
1582 *
1583 * @see #getStreamTypes(Uri, String)
1584 * @see #openAssetFile(Uri, String)
1585 * @see ClipDescription#compareMimeTypes(String, String)
1586 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001587 public @Nullable AssetFileDescriptor openTypedAssetFile(@NonNull Uri uri,
1588 @NonNull String mimeTypeFilter, @Nullable Bundle opts,
1589 @Nullable CancellationSignal signal) throws FileNotFoundException {
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001590 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1591 }
1592
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001593 /**
1594 * Interface to write a stream of data to a pipe. Use with
1595 * {@link ContentProvider#openPipeHelper}.
1596 */
1597 public interface PipeDataWriter<T> {
1598 /**
1599 * Called from a background thread to stream data out to a pipe.
1600 * Note that the pipe is blocking, so this thread can block on
1601 * writes for an arbitrary amount of time if the client is slow
1602 * at reading.
1603 *
1604 * @param output The pipe where data should be written. This will be
1605 * closed for you upon returning from this function.
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 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001611 public void writeDataToPipe(@NonNull ParcelFileDescriptor output, @NonNull Uri uri,
1612 @NonNull String mimeType, @Nullable Bundle opts, @Nullable T args);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001613 }
1614
1615 /**
1616 * A helper function for implementing {@link #openTypedAssetFile}, for
1617 * creating a data pipe and background thread allowing you to stream
1618 * generated data back to the client. This function returns a new
1619 * ParcelFileDescriptor that should be returned to the caller (the caller
1620 * is responsible for closing it).
1621 *
1622 * @param uri The URI whose data is to be written.
1623 * @param mimeType The desired type of data to be written.
1624 * @param opts Options supplied by caller.
1625 * @param args Your own custom arguments.
1626 * @param func Interface implementing the function that will actually
1627 * stream the data.
1628 * @return Returns a new ParcelFileDescriptor holding the read side of
1629 * the pipe. This should be returned to the caller for reading; the caller
1630 * is responsible for closing it when done.
1631 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001632 public @NonNull <T> ParcelFileDescriptor openPipeHelper(final @NonNull Uri uri,
1633 final @NonNull String mimeType, final @Nullable Bundle opts, final @Nullable T args,
1634 final @NonNull PipeDataWriter<T> func) throws FileNotFoundException {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001635 try {
1636 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1637
1638 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1639 @Override
1640 protected Object doInBackground(Object... params) {
1641 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1642 try {
1643 fds[1].close();
1644 } catch (IOException e) {
1645 Log.w(TAG, "Failure closing pipe", e);
1646 }
1647 return null;
1648 }
1649 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001650 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001651
1652 return fds[0];
1653 } catch (IOException e) {
1654 throw new FileNotFoundException("failure making pipe");
1655 }
1656 }
1657
1658 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 * Returns true if this instance is a temporary content provider.
1660 * @return true if this instance is a temporary content provider
1661 */
1662 protected boolean isTemporary() {
1663 return false;
1664 }
1665
1666 /**
1667 * Returns the Binder object for this provider.
1668 *
1669 * @return the Binder object for this provider
1670 * @hide
1671 */
1672 public IContentProvider getIContentProvider() {
1673 return mTransport;
1674 }
1675
1676 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001677 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1678 * when directly instantiating the provider for testing.
1679 * @hide
1680 */
1681 public void attachInfoForTesting(Context context, ProviderInfo info) {
1682 attachInfo(context, info, true);
1683 }
1684
1685 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 * After being instantiated, this is called to tell the content provider
1687 * about itself.
1688 *
1689 * @param context The context this provider is running in
1690 * @param info Registered information about this content provider
1691 */
1692 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001693 attachInfo(context, info, false);
1694 }
1695
1696 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001697 mNoPerms = testing;
1698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 /*
1700 * Only allow it to be set once, so after the content service gives
1701 * this to us clients can't change it.
1702 */
1703 if (mContext == null) {
1704 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001705 if (context != null) {
1706 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1707 Context.APP_OPS_SERVICE);
1708 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001709 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 if (info != null) {
1711 setReadPermission(info.readPermission);
1712 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001713 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001714 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001715 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001716 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 }
1718 ContentProvider.this.onCreate();
1719 }
1720 }
Fred Quintanace31b232009-05-04 16:01:15 -07001721
1722 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001723 * Override this to handle requests to perform a batch of operations, or the
1724 * default implementation will iterate over the operations and call
1725 * {@link ContentProviderOperation#apply} on each of them.
1726 * If all calls to {@link ContentProviderOperation#apply} succeed
1727 * then a {@link ContentProviderResult} array with as many
1728 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001729 * fail, it is up to the implementation how many of the others take effect.
1730 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001731 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1732 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001733 *
Fred Quintanace31b232009-05-04 16:01:15 -07001734 * @param operations the operations to apply
1735 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001736 * @throws OperationApplicationException thrown if any operation fails.
1737 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001738 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001739 public @NonNull ContentProviderResult[] applyBatch(
1740 @NonNull ArrayList<ContentProviderOperation> operations)
1741 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001742 final int numOperations = operations.size();
1743 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1744 for (int i = 0; i < numOperations; i++) {
1745 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001746 }
1747 return results;
1748 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001749
1750 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001751 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001752 * interfaces that are cheaper and/or unnatural for a table-like
1753 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001754 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001755 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1756 * on this entry into the content provider besides the basic ability for the application
1757 * to get access to the provider at all. For example, it has no idea whether the call
1758 * being executed may read or write data in the provider, so can't enforce those
1759 * individual permissions. Any implementation of this method <strong>must</strong>
1760 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1761 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001762 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1763 * @param arg provider-defined String argument. May be {@code null}.
1764 * @param extras provider-defined Bundle argument. May be {@code null}.
1765 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001766 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001767 */
Jeff Sharkey673db442015-06-11 19:30:57 -07001768 public @Nullable Bundle call(@NonNull String method, @Nullable String arg,
1769 @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001770 return null;
1771 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001772
1773 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001774 * Implement this to shut down the ContentProvider instance. You can then
1775 * invoke this method in unit tests.
1776 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001777 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001778 * Android normally handles ContentProvider startup and shutdown
1779 * automatically. You do not need to start up or shut down a
1780 * ContentProvider. When you invoke a test method on a ContentProvider,
1781 * however, a ContentProvider instance is started and keeps running after
1782 * the test finishes, even if a succeeding test instantiates another
1783 * ContentProvider. A conflict develops because the two instances are
1784 * usually running against the same underlying data source (for example, an
1785 * sqlite database).
1786 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001787 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001788 * Implementing shutDown() avoids this conflict by providing a way to
1789 * terminate the ContentProvider. This method can also prevent memory leaks
1790 * from multiple instantiations of the ContentProvider, and it can ensure
1791 * unit test isolation by allowing you to completely clean up the test
1792 * fixture before moving on to the next test.
1793 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001794 */
1795 public void shutdown() {
1796 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1797 "connections are gracefully shutdown");
1798 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001799
1800 /**
1801 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001802 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001803 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001804 * @param fd The raw file descriptor that the dump is being sent to.
1805 * @param writer The PrintWriter to which you should dump your state. This will be
1806 * closed for you after you return.
1807 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001808 */
1809 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1810 writer.println("nothing to dump");
1811 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001812
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001813 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001814 private void validateIncomingUri(Uri uri) throws SecurityException {
1815 String auth = uri.getAuthority();
1816 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001817 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
1818 throw new SecurityException("trying to query a ContentProvider in user "
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001819 + mContext.getUserId() + " with a uri belonging to user " + userId);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001820 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001821 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
1822 String message = "The authority of the uri " + uri + " does not match the one of the "
1823 + "contentProvider: ";
1824 if (mAuthority != null) {
1825 message += mAuthority;
1826 } else {
1827 message += mAuthorities;
1828 }
1829 throw new SecurityException(message);
1830 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001831 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001832
1833 /** @hide */
1834 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1835 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001836 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001837 if (end == -1) return defaultUserId;
1838 String userIdString = auth.substring(0, end);
1839 try {
1840 return Integer.parseInt(userIdString);
1841 } catch (NumberFormatException e) {
1842 Log.w(TAG, "Error parsing userId.", e);
1843 return UserHandle.USER_NULL;
1844 }
1845 }
1846
1847 /** @hide */
1848 public static int getUserIdFromAuthority(String auth) {
1849 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1850 }
1851
1852 /** @hide */
1853 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1854 if (uri == null) return defaultUserId;
1855 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1856 }
1857
1858 /** @hide */
1859 public static int getUserIdFromUri(Uri uri) {
1860 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1861 }
1862
1863 /**
1864 * Removes userId part from authority string. Expects format:
1865 * userId@some.authority
1866 * If there is no userId in the authority, it symply returns the argument
1867 * @hide
1868 */
1869 public static String getAuthorityWithoutUserId(String auth) {
1870 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001871 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001872 return auth.substring(end+1);
1873 }
1874
1875 /** @hide */
1876 public static Uri getUriWithoutUserId(Uri uri) {
1877 if (uri == null) return null;
1878 Uri.Builder builder = uri.buildUpon();
1879 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1880 return builder.build();
1881 }
1882
1883 /** @hide */
1884 public static boolean uriHasUserId(Uri uri) {
1885 if (uri == null) return false;
1886 return !TextUtils.isEmpty(uri.getUserInfo());
1887 }
1888
1889 /** @hide */
1890 public static Uri maybeAddUserId(Uri uri, int userId) {
1891 if (uri == null) return null;
1892 if (userId != UserHandle.USER_CURRENT
1893 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1894 if (!uriHasUserId(uri)) {
1895 //We don't add the user Id if there's already one
1896 Uri.Builder builder = uri.buildUpon();
1897 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1898 return builder.build();
1899 }
1900 }
1901 return uri;
1902 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001903}