blob: 72e701ddb16b0c801e3b60570f41546c4bb92717 [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
Scott Kennedy9f78f652015-03-01 15:29:25 -080022import android.annotation.Nullable;
Dianne Hackborn35654b62013-01-14 17:38:02 -080023import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070024import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.pm.ProviderInfo;
26import android.content.res.AssetFileDescriptor;
27import android.content.res.Configuration;
28import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070029import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.database.SQLException;
31import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070032import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080034import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070035import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080036import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070037import android.os.ICancellationSignal;
38import android.os.OperationCanceledException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070040import android.os.Process;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070041import android.os.UserHandle;
Vasu Nori0c9e14a2010-08-04 13:31:48 -070042import android.util.Log;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010043import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044
45import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080046import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070048import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080049import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070050import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051
52/**
53 * Content providers are one of the primary building blocks of Android applications, providing
54 * content to applications. They encapsulate data and provide it to applications through the single
55 * {@link ContentResolver} interface. A content provider is only required if you need to share
56 * data between multiple applications. For example, the contacts data is used by multiple
57 * applications and must be stored in a content provider. If you don't need to share data amongst
58 * multiple applications you can use a database directly via
59 * {@link android.database.sqlite.SQLiteDatabase}.
60 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061 * <p>When a request is made via
62 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
63 * request to the content provider registered with the authority. The content provider can interpret
64 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
65 * URIs.</p>
66 *
67 * <p>The primary methods that need to be implemented are:
68 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070069 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 * <li>{@link #query} which returns data to the caller</li>
71 * <li>{@link #insert} which inserts new data into the content provider</li>
72 * <li>{@link #update} which updates existing data in the content provider</li>
73 * <li>{@link #delete} which deletes data from the content provider</li>
74 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
75 * </ul></p>
76 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070077 * <p class="caution">Data access methods (such as {@link #insert} and
78 * {@link #update}) may be called from many threads at once, and must be thread-safe.
79 * Other methods (such as {@link #onCreate}) are only called from the application
80 * main thread, and must avoid performing lengthy operations. See the method
81 * descriptions for their expected thread behavior.</p>
82 *
83 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
84 * ContentProvider instance, so subclasses don't have to worry about the details of
85 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070086 *
87 * <div class="special reference">
88 * <h3>Developer Guides</h3>
89 * <p>For more information about using content providers, read the
90 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
91 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -070093public abstract class ContentProvider implements ComponentCallbacks2 {
Vasu Nori0c9e14a2010-08-04 13:31:48 -070094 private static final String TAG = "ContentProvider";
95
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +090096 /*
97 * Note: if you add methods to ContentProvider, you must add similar methods to
98 * MockContentProvider.
99 */
100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700102 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100103
104 // Since most Providers have only one authority, we keep both a String and a String[] to improve
105 // performance.
106 private String mAuthority;
107 private String[] mAuthorities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 private String mReadPermission;
109 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700110 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700111 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800112 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700113 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700115 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<String>();
116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 private Transport mTransport = new Transport();
118
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700119 /**
120 * Construct a ContentProvider instance. Content providers must be
121 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
122 * in the manifest</a>, accessed with {@link ContentResolver}, and created
123 * automatically by the system, so applications usually do not create
124 * ContentProvider instances directly.
125 *
126 * <p>At construction time, the object is uninitialized, and most fields and
127 * methods are unavailable. Subclasses should initialize themselves in
128 * {@link #onCreate}, not the constructor.
129 *
130 * <p>Content providers are created on the application main thread at
131 * application launch time. The constructor must not perform lengthy
132 * operations, or application startup will be delayed.
133 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900134 public ContentProvider() {
135 }
136
137 /**
138 * Constructor just for mocking.
139 *
140 * @param context A Context object which should be some mock instance (like the
141 * instance of {@link android.test.mock.MockContext}).
142 * @param readPermission The read permision you want this instance should have in the
143 * test, which is available via {@link #getReadPermission()}.
144 * @param writePermission The write permission you want this instance should have
145 * in the test, which is available via {@link #getWritePermission()}.
146 * @param pathPermissions The PathPermissions you want this instance should have
147 * in the test, which is available via {@link #getPathPermissions()}.
148 * @hide
149 */
150 public ContentProvider(
151 Context context,
152 String readPermission,
153 String writePermission,
154 PathPermission[] pathPermissions) {
155 mContext = context;
156 mReadPermission = readPermission;
157 mWritePermission = writePermission;
158 mPathPermissions = pathPermissions;
159 }
160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 /**
162 * Given an IContentProvider, try to coerce it back to the real
163 * ContentProvider object if it is running in the local process. This can
164 * be used if you know you are running in the same process as a provider,
165 * and want to get direct access to its implementation details. Most
166 * clients should not nor have a reason to use it.
167 *
168 * @param abstractInterface The ContentProvider interface that is to be
169 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800170 * @return If the IContentProvider is non-{@code null} and local, returns its actual
171 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 * @hide
173 */
174 public static ContentProvider coerceToLocalContentProvider(
175 IContentProvider abstractInterface) {
176 if (abstractInterface instanceof Transport) {
177 return ((Transport)abstractInterface).getContentProvider();
178 }
179 return null;
180 }
181
182 /**
183 * Binder object that deals with remoting.
184 *
185 * @hide
186 */
187 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800188 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800189 int mReadOp = AppOpsManager.OP_NONE;
190 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 ContentProvider getContentProvider() {
193 return ContentProvider.this;
194 }
195
Jeff Brownd2183652011-10-09 12:39:53 -0700196 @Override
197 public String getProviderName() {
198 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 }
200
Jeff Brown75ea64f2012-01-25 19:37:13 -0800201 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800202 public Cursor query(String callingPkg, Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800203 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800204 ICancellationSignal cancellationSignal) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100205 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100206 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800207 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700208 // The caller has no access to the data, so return an empty cursor with
209 // the columns in the requested order. The caller may ask for an invalid
210 // column and we would not catch that but this is not a problem in practice.
211 // We do not call ContentProvider#query with a modified where clause since
212 // the implementation is not guaranteed to be backed by a SQL database, hence
213 // it may not handle properly the tautology where clause we would have created.
Svet Ganova2147ec2015-04-27 17:00:44 -0700214 if (projection != null) {
215 return new MatrixCursor(projection, 0);
216 }
217
218 // Null projection means all columns but we have no idea which they are.
219 // However, the caller may be expecting to access them my index. Hence,
220 // we have to execute the query as if allowed to get a cursor with the
221 // columns. We then use the column names to return an empty cursor.
222 Cursor cursor = ContentProvider.this.query(uri, projection, selection,
223 selectionArgs, sortOrder, CancellationSignal.fromTransport(
224 cancellationSignal));
225
226 // Create a projection for all columns.
227 final int columnCount = cursor.getCount();
228 String[] allColumns = new String[columnCount];
229 for (int i = 0; i < columnCount; i++) {
230 allColumns[i] = cursor.getColumnName(i);
231 }
232
233 // Return an empty cursor for all columns.
234 return new MatrixCursor(allColumns, 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800235 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700236 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700237 try {
238 return ContentProvider.this.query(
239 uri, projection, selection, selectionArgs, sortOrder,
240 CancellationSignal.fromTransport(cancellationSignal));
241 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700242 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700243 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 }
245
Jeff Brown75ea64f2012-01-25 19:37:13 -0800246 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100248 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100249 uri = getUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 return ContentProvider.this.getType(uri);
251 }
252
Jeff Brown75ea64f2012-01-25 19:37:13 -0800253 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800254 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100255 validateIncomingUri(uri);
256 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100257 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800258 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800259 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800260 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700261 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700262 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100263 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700264 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700265 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 }
268
Jeff Brown75ea64f2012-01-25 19:37:13 -0800269 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800270 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100271 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100272 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800273 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800274 return 0;
275 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700276 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700277 try {
278 return ContentProvider.this.bulkInsert(uri, initialValues);
279 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700280 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 }
283
Jeff Brown75ea64f2012-01-25 19:37:13 -0800284 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800285 public ContentProviderResult[] applyBatch(String callingPkg,
286 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700287 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100288 int numOperations = operations.size();
289 final int[] userIds = new int[numOperations];
290 for (int i = 0; i < numOperations; i++) {
291 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100292 Uri uri = operation.getUri();
293 validateIncomingUri(uri);
294 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100295 if (userIds[i] != UserHandle.USER_CURRENT) {
296 // Removing the user id from the uri.
297 operation = new ContentProviderOperation(operation, true);
298 operations.set(i, operation);
299 }
Fred Quintana89437372009-05-15 15:10:40 -0700300 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800301 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800302 != AppOpsManager.MODE_ALLOWED) {
303 throw new OperationApplicationException("App op not allowed", 0);
304 }
Fred Quintana89437372009-05-15 15:10:40 -0700305 }
Fred Quintana89437372009-05-15 15:10:40 -0700306 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800307 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800308 != AppOpsManager.MODE_ALLOWED) {
309 throw new OperationApplicationException("App op not allowed", 0);
310 }
Fred Quintana89437372009-05-15 15:10:40 -0700311 }
312 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700313 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700314 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100315 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800316 if (results != null) {
317 for (int i = 0; i < results.length ; i++) {
318 if (userIds[i] != UserHandle.USER_CURRENT) {
319 // Adding the userId to the uri.
320 results[i] = new ContentProviderResult(results[i], userIds[i]);
321 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100322 }
323 }
324 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700325 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700326 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700327 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700328 }
329
Jeff Brown75ea64f2012-01-25 19:37:13 -0800330 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800331 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100332 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100333 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800334 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800335 return 0;
336 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700337 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700338 try {
339 return ContentProvider.this.delete(uri, selection, selectionArgs);
340 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700341 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 }
344
Jeff Brown75ea64f2012-01-25 19:37:13 -0800345 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800346 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100348 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100349 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800350 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800351 return 0;
352 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700353 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700354 try {
355 return ContentProvider.this.update(uri, values, selection, selectionArgs);
356 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700357 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 }
360
Jeff Brown75ea64f2012-01-25 19:37:13 -0800361 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700362 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800363 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
364 IBinder callerToken) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100365 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100366 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800367 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700368 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700369 try {
370 return ContentProvider.this.openFile(
371 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
372 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700373 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 }
376
Jeff Brown75ea64f2012-01-25 19:37:13 -0800377 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700378 public AssetFileDescriptor openAssetFile(
379 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800380 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100381 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100382 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800383 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700384 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700385 try {
386 return ContentProvider.this.openAssetFile(
387 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
388 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700389 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800391 }
392
Jeff Brown75ea64f2012-01-25 19:37:13 -0800393 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800394 public Bundle call(
395 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700396 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700397 try {
398 return ContentProvider.this.call(method, arg, extras);
399 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700400 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700401 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800402 }
403
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700404 @Override
405 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100406 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100407 uri = getUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700408 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
409 }
410
411 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800412 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700413 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100414 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100415 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800416 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700417 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700418 try {
419 return ContentProvider.this.openTypedAssetFile(
420 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
421 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700422 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700423 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700424 }
425
Jeff Brown75ea64f2012-01-25 19:37:13 -0800426 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700427 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800428 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800429 }
430
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700431 @Override
432 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100433 validateIncomingUri(uri);
434 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100435 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800436 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700437 return null;
438 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700439 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700440 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100441 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700442 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700443 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700444 }
445 }
446
447 @Override
448 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100449 validateIncomingUri(uri);
450 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100451 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800452 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700453 return null;
454 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700455 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700456 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100457 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700458 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700459 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700460 }
461 }
462
Dianne Hackbornff170242014-11-19 10:59:01 -0800463 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
464 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800465 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800466 if (enforceWritePermission(callingPkg, uri, callerToken)
467 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800468 throw new FileNotFoundException("App op not allowed");
469 }
470 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800471 if (enforceReadPermission(callingPkg, uri, callerToken)
472 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800473 throw new FileNotFoundException("App op not allowed");
474 }
475 }
476 }
477
Dianne Hackbornff170242014-11-19 10:59:01 -0800478 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
479 throws SecurityException {
480 enforceReadPermissionInner(uri, callerToken);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800481 if (mReadOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800482 return mAppOpsManager.noteOp(mReadOp, Binder.getCallingUid(), callingPkg);
483 }
484 return AppOpsManager.MODE_ALLOWED;
485 }
486
Dianne Hackbornff170242014-11-19 10:59:01 -0800487 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
488 throws SecurityException {
489 enforceWritePermissionInner(uri, callerToken);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800490 if (mWriteOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800491 return mAppOpsManager.noteOp(mWriteOp, Binder.getCallingUid(), callingPkg);
492 }
493 return AppOpsManager.MODE_ALLOWED;
494 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700495 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800496
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100497 boolean checkUser(int pid, int uid, Context context) {
498 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700499 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100500 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
501 == PERMISSION_GRANTED;
502 }
503
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700504 /** {@hide} */
Dianne Hackbornff170242014-11-19 10:59:01 -0800505 protected void enforceReadPermissionInner(Uri uri, IBinder callerToken)
506 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700507 final Context context = getContext();
508 final int pid = Binder.getCallingPid();
509 final int uid = Binder.getCallingUid();
510 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700511
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700512 if (UserHandle.isSameApp(uid, mMyUid)) {
513 return;
514 }
515
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100516 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700517 final String componentPerm = getReadPermission();
518 if (componentPerm != null) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800519 if (context.checkPermission(componentPerm, pid, uid, callerToken)
520 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700521 return;
522 } else {
523 missingPerm = componentPerm;
524 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700525 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700526
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700527 // track if unprotected read is allowed; any denied
528 // <path-permission> below removes this ability
529 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700530
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700531 final PathPermission[] pps = getPathPermissions();
532 if (pps != null) {
533 final String path = uri.getPath();
534 for (PathPermission pp : pps) {
535 final String pathPerm = pp.getReadPermission();
536 if (pathPerm != null && pp.match(path)) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800537 if (context.checkPermission(pathPerm, pid, uid, callerToken)
538 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700539 return;
540 } else {
541 // any denied <path-permission> means we lose
542 // default <provider> access.
543 allowDefaultRead = false;
544 missingPerm = pathPerm;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700545 }
546 }
547 }
548 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700549
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700550 // if we passed <path-permission> checks above, and no default
551 // <provider> permission, then allow access.
552 if (allowDefaultRead) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700554
555 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800556 final int callingUserId = UserHandle.getUserId(uid);
557 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
558 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800559 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
560 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700561 return;
562 }
563
564 final String failReason = mExported
565 ? " requires " + missingPerm + ", or grantUriPermission()"
566 : " requires the provider be exported, or grantUriPermission()";
567 throw new SecurityException("Permission Denial: reading "
568 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
569 + ", uid=" + uid + failReason);
570 }
571
572 /** {@hide} */
Dianne Hackbornff170242014-11-19 10:59:01 -0800573 protected void enforceWritePermissionInner(Uri uri, IBinder callerToken)
574 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700575 final Context context = getContext();
576 final int pid = Binder.getCallingPid();
577 final int uid = Binder.getCallingUid();
578 String missingPerm = null;
579
580 if (UserHandle.isSameApp(uid, mMyUid)) {
581 return;
582 }
583
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100584 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700585 final String componentPerm = getWritePermission();
586 if (componentPerm != null) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800587 if (context.checkPermission(componentPerm, pid, uid, callerToken)
588 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700589 return;
590 } else {
591 missingPerm = componentPerm;
592 }
593 }
594
595 // track if unprotected write is allowed; any denied
596 // <path-permission> below removes this ability
597 boolean allowDefaultWrite = (componentPerm == null);
598
599 final PathPermission[] pps = getPathPermissions();
600 if (pps != null) {
601 final String path = uri.getPath();
602 for (PathPermission pp : pps) {
603 final String pathPerm = pp.getWritePermission();
604 if (pathPerm != null && pp.match(path)) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800605 if (context.checkPermission(pathPerm, pid, uid, callerToken)
606 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700607 return;
608 } else {
609 // any denied <path-permission> means we lose
610 // default <provider> access.
611 allowDefaultWrite = false;
612 missingPerm = pathPerm;
613 }
614 }
615 }
616 }
617
618 // if we passed <path-permission> checks above, and no default
619 // <provider> permission, then allow access.
620 if (allowDefaultWrite) return;
621 }
622
623 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800624 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
625 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700626 return;
627 }
628
629 final String failReason = mExported
630 ? " requires " + missingPerm + ", or grantUriPermission()"
631 : " requires the provider be exported, or grantUriPermission()";
632 throw new SecurityException("Permission Denial: writing "
633 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
634 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 }
636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700638 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800639 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 * constructor.
641 */
642 public final Context getContext() {
643 return mContext;
644 }
645
646 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700647 * Set the calling package, returning the current value (or {@code null})
648 * which can be used later to restore the previous state.
649 */
650 private String setCallingPackage(String callingPackage) {
651 final String original = mCallingPackage.get();
652 mCallingPackage.set(callingPackage);
653 return original;
654 }
655
656 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700657 * Return the package name of the caller that initiated the request being
658 * processed on the current thread. The returned package will have been
659 * verified to belong to the calling UID. Returns {@code null} if not
660 * currently processing a request.
661 * <p>
662 * This will always return {@code null} when processing
663 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
664 *
665 * @see Binder#getCallingUid()
666 * @see Context#grantUriPermission(String, Uri, int)
667 * @throws SecurityException if the calling package doesn't belong to the
668 * calling UID.
669 */
670 public final String getCallingPackage() {
671 final String pkg = mCallingPackage.get();
672 if (pkg != null) {
673 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
674 }
675 return pkg;
676 }
677
678 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100679 * Change the authorities of the ContentProvider.
680 * This is normally set for you from its manifest information when the provider is first
681 * created.
682 * @hide
683 * @param authorities the semi-colon separated authorities of the ContentProvider.
684 */
685 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100686 if (authorities != null) {
687 if (authorities.indexOf(';') == -1) {
688 mAuthority = authorities;
689 mAuthorities = null;
690 } else {
691 mAuthority = null;
692 mAuthorities = authorities.split(";");
693 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100694 }
695 }
696
697 /** @hide */
698 protected final boolean matchesOurAuthorities(String authority) {
699 if (mAuthority != null) {
700 return mAuthority.equals(authority);
701 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100702 if (mAuthorities != null) {
703 int length = mAuthorities.length;
704 for (int i = 0; i < length; i++) {
705 if (mAuthorities[i].equals(authority)) return true;
706 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100707 }
708 return false;
709 }
710
711
712 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 * Change the permission required to read data from the content
714 * provider. This is normally set for you from its manifest information
715 * when the provider is first created.
716 *
717 * @param permission Name of the permission required for read-only access.
718 */
719 protected final void setReadPermission(String permission) {
720 mReadPermission = permission;
721 }
722
723 /**
724 * Return the name of the permission required for read-only access to
725 * this content provider. This method can be called from multiple
726 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800727 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
728 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 */
730 public final String getReadPermission() {
731 return mReadPermission;
732 }
733
734 /**
735 * Change the permission required to read and write data in the content
736 * provider. This is normally set for you from its manifest information
737 * when the provider is first created.
738 *
739 * @param permission Name of the permission required for read/write access.
740 */
741 protected final void setWritePermission(String permission) {
742 mWritePermission = permission;
743 }
744
745 /**
746 * Return the name of the permission required for read/write access to
747 * this content provider. This method can be called from multiple
748 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800749 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
750 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 */
752 public final String getWritePermission() {
753 return mWritePermission;
754 }
755
756 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700757 * Change the path-based permission required to read and/or write data in
758 * the content provider. This is normally set for you from its manifest
759 * information when the provider is first created.
760 *
761 * @param permissions Array of path permission descriptions.
762 */
763 protected final void setPathPermissions(PathPermission[] permissions) {
764 mPathPermissions = permissions;
765 }
766
767 /**
768 * Return the path-based permissions required for read and/or write access to
769 * this content provider. This method can be called from multiple
770 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800771 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
772 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700773 */
774 public final PathPermission[] getPathPermissions() {
775 return mPathPermissions;
776 }
777
Dianne Hackborn35654b62013-01-14 17:38:02 -0800778 /** @hide */
779 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800780 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800781 mTransport.mReadOp = readOp;
782 mTransport.mWriteOp = writeOp;
783 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800784 }
785
Dianne Hackborn961321f2013-02-05 17:22:41 -0800786 /** @hide */
787 public AppOpsManager getAppOpsManager() {
788 return mTransport.mAppOpsManager;
789 }
790
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700791 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700792 * Implement this to initialize your content provider on startup.
793 * This method is called for all registered content providers on the
794 * application main thread at application launch time. It must not perform
795 * lengthy operations, or application startup will be delayed.
796 *
797 * <p>You should defer nontrivial initialization (such as opening,
798 * upgrading, and scanning databases) until the content provider is used
799 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
800 * keeps application startup fast, avoids unnecessary work if the provider
801 * turns out not to be needed, and stops database errors (such as a full
802 * disk) from halting application launch.
803 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700804 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700805 * is a helpful utility class that makes it easy to manage databases,
806 * and will automatically defer opening until first use. If you do use
807 * SQLiteOpenHelper, make sure to avoid calling
808 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
809 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
810 * from this method. (Instead, override
811 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
812 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 *
814 * @return true if the provider was successfully loaded, false otherwise
815 */
816 public abstract boolean onCreate();
817
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700818 /**
819 * {@inheritDoc}
820 * This method is always called on the application main thread, and must
821 * not perform lengthy operations.
822 *
823 * <p>The default content provider implementation does nothing.
824 * Override this method to take appropriate action.
825 * (Content providers do not usually care about things like screen
826 * orientation, but may want to know about locale changes.)
827 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 public void onConfigurationChanged(Configuration newConfig) {
829 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700830
831 /**
832 * {@inheritDoc}
833 * This method is always called on the application main thread, and must
834 * not perform lengthy operations.
835 *
836 * <p>The default content provider implementation does nothing.
837 * Subclasses may override this method to take appropriate action.
838 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 public void onLowMemory() {
840 }
841
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700842 public void onTrimMemory(int level) {
843 }
844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700846 * Implement this to handle query requests from clients.
847 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800848 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
849 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 * <p>
851 * Example client call:<p>
852 * <pre>// Request a specific record.
853 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000854 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 projection, // Which columns to return.
856 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000857 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 People.NAME + " ASC"); // Sort order.</pre>
859 * Example implementation:<p>
860 * <pre>// SQLiteQueryBuilder is a helper class that creates the
861 // proper SQL syntax for us.
862 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
863
864 // Set the table we're querying.
865 qBuilder.setTables(DATABASE_TABLE_NAME);
866
867 // If the query ends in a specific record number, we're
868 // being asked for a specific record, so set the
869 // WHERE clause in our query.
870 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
871 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
872 }
873
874 // Make the query.
875 Cursor c = qBuilder.query(mDb,
876 projection,
877 selection,
878 selectionArgs,
879 groupBy,
880 having,
881 sortOrder);
882 c.setNotificationUri(getContext().getContentResolver(), uri);
883 return c;</pre>
884 *
885 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000886 * if the client is requesting a specific record, the URI will end in a record number
887 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
888 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800890 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800892 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000893 * @param selectionArgs You may include ?s in selection, which will be replaced by
894 * the values from selectionArgs, in order that they appear in the selection.
895 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800897 * If {@code null} then the provider is free to define the sort order.
898 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 */
900 public abstract Cursor query(Uri uri, String[] projection,
901 String selection, String[] selectionArgs, String sortOrder);
902
Fred Quintana5bba6322009-10-05 14:21:12 -0700903 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800904 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800905 * This method can be called from multiple threads, as described in
906 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
907 * and Threads</a>.
908 * <p>
909 * Example client call:<p>
910 * <pre>// Request a specific record.
911 * Cursor managedCursor = managedQuery(
912 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
913 projection, // Which columns to return.
914 null, // WHERE clause.
915 null, // WHERE clause value substitution
916 People.NAME + " ASC"); // Sort order.</pre>
917 * Example implementation:<p>
918 * <pre>// SQLiteQueryBuilder is a helper class that creates the
919 // proper SQL syntax for us.
920 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
921
922 // Set the table we're querying.
923 qBuilder.setTables(DATABASE_TABLE_NAME);
924
925 // If the query ends in a specific record number, we're
926 // being asked for a specific record, so set the
927 // WHERE clause in our query.
928 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
929 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
930 }
931
932 // Make the query.
933 Cursor c = qBuilder.query(mDb,
934 projection,
935 selection,
936 selectionArgs,
937 groupBy,
938 having,
939 sortOrder);
940 c.setNotificationUri(getContext().getContentResolver(), uri);
941 return c;</pre>
942 * <p>
943 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800944 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
945 * signal to ensure correct operation on older versions of the Android Framework in
946 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800947 *
948 * @param uri The URI to query. This will be the full URI sent by the client;
949 * if the client is requesting a specific record, the URI will end in a record number
950 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
951 * that _id value.
952 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800953 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800954 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800955 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800956 * @param selectionArgs You may include ?s in selection, which will be replaced by
957 * the values from selectionArgs, in order that they appear in the selection.
958 * The values will be bound as Strings.
959 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800960 * If {@code null} then the provider is free to define the sort order.
961 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800962 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
963 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800964 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800965 */
966 public Cursor query(Uri uri, String[] projection,
967 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800968 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800969 return query(uri, projection, selection, selectionArgs, sortOrder);
970 }
971
972 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700973 * Implement this to handle requests for the MIME type of the data at the
974 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 * <code>vnd.android.cursor.item</code> for a single record,
976 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700977 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800978 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
979 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700981 * <p>Note that there are no permissions needed for an application to
982 * access this information; if your content provider requires read and/or
983 * write permissions, or is not exported, all applications can still call
984 * this method regardless of their access permissions. This allows them
985 * to retrieve the MIME type for a URI when dispatching intents.
986 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800988 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 */
990 public abstract String getType(Uri uri);
991
992 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700993 * Implement this to support canonicalization of URIs that refer to your
994 * content provider. A canonical URI is one that can be transported across
995 * devices, backup/restore, and other contexts, and still be able to refer
996 * to the same data item. Typically this is implemented by adding query
997 * params to the URI allowing the content provider to verify that an incoming
998 * canonical URI references the same data as it was originally intended for and,
999 * if it doesn't, to find that data (if it exists) in the current environment.
1000 *
1001 * <p>For example, if the content provider holds people and a normal URI in it
1002 * is created with a row index into that people database, the cananical representation
1003 * may have an additional query param at the end which specifies the name of the
1004 * person it is intended for. Later calls into the provider with that URI will look
1005 * up the row of that URI's base index and, if it doesn't match or its entry's
1006 * name doesn't match the name in the query param, perform a query on its database
1007 * to find the correct row to operate on.</p>
1008 *
1009 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1010 * URIs (including this one) must perform this verification and recovery of any
1011 * canonical URIs they receive. In addition, you must also implement
1012 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1013 *
1014 * <p>The default implementation of this method returns null, indicating that
1015 * canonical URIs are not supported.</p>
1016 *
1017 * @param url The Uri to canonicalize.
1018 *
1019 * @return Return the canonical representation of <var>url</var>, or null if
1020 * canonicalization of that Uri is not supported.
1021 */
1022 public Uri canonicalize(Uri url) {
1023 return null;
1024 }
1025
1026 /**
1027 * Remove canonicalization from canonical URIs previously returned by
1028 * {@link #canonicalize}. For example, if your implementation is to add
1029 * a query param to canonicalize a URI, this method can simply trip any
1030 * query params on the URI. The default implementation always returns the
1031 * same <var>url</var> that was passed in.
1032 *
1033 * @param url The Uri to remove any canonicalization from.
1034 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001035 * @return Return the non-canonical representation of <var>url</var>, return
1036 * the <var>url</var> as-is if there is nothing to do, or return null if
1037 * the data identified by the canonical representation can not be found in
1038 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001039 */
1040 public Uri uncanonicalize(Uri url) {
1041 return url;
1042 }
1043
1044 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001045 * @hide
1046 * Implementation when a caller has performed an insert on the content
1047 * provider, but that call has been rejected for the operation given
1048 * to {@link #setAppOps(int, int)}. The default implementation simply
1049 * returns a dummy URI that is the base URI with a 0 path element
1050 * appended.
1051 */
1052 public Uri rejectInsert(Uri uri, ContentValues values) {
1053 // If not allowed, we need to return some reasonable URI. Maybe the
1054 // content provider should be responsible for this, but for now we
1055 // will just return the base URI with a dummy '0' tagged on to it.
1056 // You shouldn't be able to read if you can't write, anyway, so it
1057 // shouldn't matter much what is returned.
1058 return uri.buildUpon().appendPath("0").build();
1059 }
1060
1061 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001062 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1064 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001065 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001066 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1067 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001068 * @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 -08001069 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001070 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 * @return The URI for the newly inserted item.
1072 */
1073 public abstract Uri insert(Uri uri, ContentValues values);
1074
1075 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001076 * Override this to handle requests to insert a set of new rows, or the
1077 * default implementation will iterate over the values and call
1078 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1080 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001081 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001082 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1083 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 *
1085 * @param uri The content:// URI of the insertion request.
1086 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001087 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 * @return The number of values that were inserted.
1089 */
1090 public int bulkInsert(Uri uri, ContentValues[] values) {
1091 int numValues = values.length;
1092 for (int i = 0; i < numValues; i++) {
1093 insert(uri, values[i]);
1094 }
1095 return numValues;
1096 }
1097
1098 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001099 * Implement this to handle requests to delete one or more rows.
1100 * The implementation should apply the selection clause when performing
1101 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001102 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001104 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001105 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1106 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 *
1108 * <p>The implementation is responsible for parsing out a row ID at the end
1109 * of the URI, if a specific row is being deleted. That is, the client would
1110 * pass in <code>content://contacts/people/22</code> and the implementation is
1111 * responsible for parsing the record number (22) when creating a SQL statement.
1112 *
1113 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1114 * @param selection An optional restriction to apply to rows when deleting.
1115 * @return The number of rows affected.
1116 * @throws SQLException
1117 */
1118 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
1119
1120 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001121 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001122 * The implementation should update all rows matching the selection
1123 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1125 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001126 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001127 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1128 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 *
1130 * @param uri The URI to query. This can potentially have a record ID if this
1131 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001132 * @param values A set of column_name/value pairs to update in the database.
1133 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 * @param selection An optional filter to match rows to update.
1135 * @return the number of rows affected.
1136 */
1137 public abstract int update(Uri uri, ContentValues values, String selection,
1138 String[] selectionArgs);
1139
1140 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001141 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001142 * The default implementation always throws {@link FileNotFoundException}.
1143 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001144 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1145 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001146 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001147 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1148 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001149 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 *
1151 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1152 * their responsibility to close it when done. That is, the implementation
1153 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001154 * <p>
1155 * If opened with the exclusive "r" or "w" modes, the returned
1156 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1157 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1158 * supports seeking.
1159 * <p>
1160 * If you need to detect when the returned ParcelFileDescriptor has been
1161 * closed, or if the remote process has crashed or encountered some other
1162 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1163 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1164 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1165 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001167 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1168 * to return the appropriate MIME type for the data returned here with
1169 * the same URI. This will allow intent resolution to automatically determine the data MIME
1170 * type and select the appropriate matching targets as part of its operation.</p>
1171 *
1172 * <p class="note">For better interoperability with other applications, it is recommended
1173 * that for any URIs that can be opened, you also support queries on them
1174 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1175 * You may also want to support other common columns if you have additional meta-data
1176 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1177 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1178 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 * @param uri The URI whose file is to be opened.
1180 * @param mode Access mode for the file. May be "r" for read-only access,
1181 * "rw" for read and write access, or "rwt" for read and write access
1182 * that truncates any existing file.
1183 *
1184 * @return Returns a new ParcelFileDescriptor which you can use to access
1185 * the file.
1186 *
1187 * @throws FileNotFoundException Throws FileNotFoundException if there is
1188 * no file associated with the given URI or the mode is invalid.
1189 * @throws SecurityException Throws SecurityException if the caller does
1190 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001191 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 * @see #openAssetFile(Uri, String)
1193 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001194 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001195 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001196 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 public ParcelFileDescriptor openFile(Uri uri, String mode)
1198 throws FileNotFoundException {
1199 throw new FileNotFoundException("No files supported by provider at "
1200 + uri);
1201 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001204 * Override this to handle requests to open a file blob.
1205 * The default implementation always throws {@link FileNotFoundException}.
1206 * This method can be called from multiple threads, as described in
1207 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1208 * and Threads</a>.
1209 *
1210 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1211 * to the caller. This way large data (such as images and documents) can be
1212 * returned without copying the content.
1213 *
1214 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1215 * their responsibility to close it when done. That is, the implementation
1216 * of this method should create a new ParcelFileDescriptor for each call.
1217 * <p>
1218 * If opened with the exclusive "r" or "w" modes, the returned
1219 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1220 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1221 * supports seeking.
1222 * <p>
1223 * If you need to detect when the returned ParcelFileDescriptor has been
1224 * closed, or if the remote process has crashed or encountered some other
1225 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1226 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1227 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1228 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1229 *
1230 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1231 * to return the appropriate MIME type for the data returned here with
1232 * the same URI. This will allow intent resolution to automatically determine the data MIME
1233 * type and select the appropriate matching targets as part of its operation.</p>
1234 *
1235 * <p class="note">For better interoperability with other applications, it is recommended
1236 * that for any URIs that can be opened, you also support queries on them
1237 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1238 * You may also want to support other common columns if you have additional meta-data
1239 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1240 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1241 *
1242 * @param uri The URI whose file is to be opened.
1243 * @param mode Access mode for the file. May be "r" for read-only access,
1244 * "w" for write-only access, "rw" for read and write access, or
1245 * "rwt" for read and write access that truncates any existing
1246 * file.
1247 * @param signal A signal to cancel the operation in progress, or
1248 * {@code null} if none. For example, if you are downloading a
1249 * file from the network to service a "rw" mode request, you
1250 * should periodically call
1251 * {@link CancellationSignal#throwIfCanceled()} to check whether
1252 * the client has canceled the request and abort the download.
1253 *
1254 * @return Returns a new ParcelFileDescriptor which you can use to access
1255 * the file.
1256 *
1257 * @throws FileNotFoundException Throws FileNotFoundException if there is
1258 * no file associated with the given URI or the mode is invalid.
1259 * @throws SecurityException Throws SecurityException if the caller does
1260 * not have permission to access the file.
1261 *
1262 * @see #openAssetFile(Uri, String)
1263 * @see #openFileHelper(Uri, String)
1264 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001265 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001266 */
1267 public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
1268 throws FileNotFoundException {
1269 return openFile(uri, mode);
1270 }
1271
1272 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 * This is like {@link #openFile}, but can be implemented by providers
1274 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001275 * inside of their .apk.
1276 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001277 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1278 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001279 *
1280 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001281 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001282 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1284 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1285 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001286 * <p>
1287 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1288 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001289 *
1290 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 * should create the AssetFileDescriptor with
1292 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001293 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001295 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1296 * to return the appropriate MIME type for the data returned here with
1297 * the same URI. This will allow intent resolution to automatically determine the data MIME
1298 * type and select the appropriate matching targets as part of its operation.</p>
1299 *
1300 * <p class="note">For better interoperability with other applications, it is recommended
1301 * that for any URIs that can be opened, you also support queries on them
1302 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1303 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 * @param uri The URI whose file is to be opened.
1305 * @param mode Access mode for the file. May be "r" for read-only access,
1306 * "w" for write-only access (erasing whatever data is currently in
1307 * the file), "wa" for write-only access to append to any existing data,
1308 * "rw" for read and write access on any existing data, and "rwt" for read
1309 * and write access that truncates any existing file.
1310 *
1311 * @return Returns a new AssetFileDescriptor which you can use to access
1312 * the file.
1313 *
1314 * @throws FileNotFoundException Throws FileNotFoundException if there is
1315 * no file associated with the given URI or the mode is invalid.
1316 * @throws SecurityException Throws SecurityException if the caller does
1317 * not have permission to access the file.
1318 *
1319 * @see #openFile(Uri, String)
1320 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001321 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 */
1323 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
1324 throws FileNotFoundException {
1325 ParcelFileDescriptor fd = openFile(uri, mode);
1326 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1327 }
1328
1329 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001330 * This is like {@link #openFile}, but can be implemented by providers
1331 * that need to be able to return sub-sections of files, often assets
1332 * inside of their .apk.
1333 * This method can be called from multiple threads, as described in
1334 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1335 * and Threads</a>.
1336 *
1337 * <p>If you implement this, your clients must be able to deal with such
1338 * file slices, either directly with
1339 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1340 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1341 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1342 * methods.
1343 * <p>
1344 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1345 * streaming of data.
1346 *
1347 * <p class="note">If you are implementing this to return a full file, you
1348 * should create the AssetFileDescriptor with
1349 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1350 * applications that cannot handle sub-sections of files.</p>
1351 *
1352 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1353 * to return the appropriate MIME type for the data returned here with
1354 * the same URI. This will allow intent resolution to automatically determine the data MIME
1355 * type and select the appropriate matching targets as part of its operation.</p>
1356 *
1357 * <p class="note">For better interoperability with other applications, it is recommended
1358 * that for any URIs that can be opened, you also support queries on them
1359 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1360 *
1361 * @param uri The URI whose file is to be opened.
1362 * @param mode Access mode for the file. May be "r" for read-only access,
1363 * "w" for write-only access (erasing whatever data is currently in
1364 * the file), "wa" for write-only access to append to any existing data,
1365 * "rw" for read and write access on any existing data, and "rwt" for read
1366 * and write access that truncates any existing file.
1367 * @param signal A signal to cancel the operation in progress, or
1368 * {@code null} if none. For example, if you are downloading a
1369 * file from the network to service a "rw" mode request, you
1370 * should periodically call
1371 * {@link CancellationSignal#throwIfCanceled()} to check whether
1372 * the client has canceled the request and abort the download.
1373 *
1374 * @return Returns a new AssetFileDescriptor which you can use to access
1375 * the file.
1376 *
1377 * @throws FileNotFoundException Throws FileNotFoundException if there is
1378 * no file associated with the given URI or the mode is invalid.
1379 * @throws SecurityException Throws SecurityException if the caller does
1380 * not have permission to access the file.
1381 *
1382 * @see #openFile(Uri, String)
1383 * @see #openFileHelper(Uri, String)
1384 * @see #getType(android.net.Uri)
1385 */
1386 public AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)
1387 throws FileNotFoundException {
1388 return openAssetFile(uri, mode);
1389 }
1390
1391 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 * Convenience for subclasses that wish to implement {@link #openFile}
1393 * by looking up a column named "_data" at the given URI.
1394 *
1395 * @param uri The URI to be opened.
1396 * @param mode The file mode. May be "r" for read-only access,
1397 * "w" for write-only access (erasing whatever data is currently in
1398 * the file), "wa" for write-only access to append to any existing data,
1399 * "rw" for read and write access on any existing data, and "rwt" for read
1400 * and write access that truncates any existing file.
1401 *
1402 * @return Returns a new ParcelFileDescriptor that can be used by the
1403 * client to access the file.
1404 */
1405 protected final ParcelFileDescriptor openFileHelper(Uri uri,
1406 String mode) throws FileNotFoundException {
1407 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1408 int count = (c != null) ? c.getCount() : 0;
1409 if (count != 1) {
1410 // If there is not exactly one result, throw an appropriate
1411 // exception.
1412 if (c != null) {
1413 c.close();
1414 }
1415 if (count == 0) {
1416 throw new FileNotFoundException("No entry for " + uri);
1417 }
1418 throw new FileNotFoundException("Multiple items at " + uri);
1419 }
1420
1421 c.moveToFirst();
1422 int i = c.getColumnIndex("_data");
1423 String path = (i >= 0 ? c.getString(i) : null);
1424 c.close();
1425 if (path == null) {
1426 throw new FileNotFoundException("Column _data not found.");
1427 }
1428
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001429 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 return ParcelFileDescriptor.open(new File(path), modeBits);
1431 }
1432
1433 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001434 * Called by a client to determine the types of data streams that this
1435 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001436 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001437 * of a particular type, return that MIME type if it matches the given
1438 * mimeTypeFilter. If it can perform type conversions, return an array
1439 * of all supported MIME types that match mimeTypeFilter.
1440 *
1441 * @param uri The data in the content provider being queried.
1442 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001443 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001444 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001445 * given mimeTypeFilter. Otherwise returns an array of all available
1446 * concrete MIME types.
1447 *
1448 * @see #getType(Uri)
1449 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001450 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001451 */
1452 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
1453 return null;
1454 }
1455
1456 /**
1457 * Called by a client to open a read-only stream containing data of a
1458 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1459 * except the file can only be read-only and the content provider may
1460 * perform data conversions to generate data of the desired type.
1461 *
1462 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001463 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001464 * {@link #openAssetFile(Uri, String)}.
1465 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001466 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001467 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001468 * <p>
1469 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1470 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001471 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001472 * <p class="note">For better interoperability with other applications, it is recommended
1473 * that for any URIs that can be opened, you also support queries on them
1474 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1475 * You may also want to support other common columns if you have additional meta-data
1476 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1477 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1478 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001479 * @param uri The data in the content provider being queried.
1480 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001481 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001482 * requirements; in this case the content provider will pick its best
1483 * type matching the pattern.
1484 * @param opts Additional options from the client. The definitions of
1485 * these are specific to the content provider being called.
1486 *
1487 * @return Returns a new AssetFileDescriptor from which the client can
1488 * read data of the desired type.
1489 *
1490 * @throws FileNotFoundException Throws FileNotFoundException if there is
1491 * no file associated with the given URI or the mode is invalid.
1492 * @throws SecurityException Throws SecurityException if the caller does
1493 * not have permission to access the data.
1494 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1495 * content provider does not support the requested MIME type.
1496 *
1497 * @see #getStreamTypes(Uri, String)
1498 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001499 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001500 */
1501 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
1502 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001503 if ("*/*".equals(mimeTypeFilter)) {
1504 // If they can take anything, the untyped open call is good enough.
1505 return openAssetFile(uri, "r");
1506 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001507 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001508 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001509 // Use old untyped open call if this provider has a type for this
1510 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001511 return openAssetFile(uri, "r");
1512 }
1513 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1514 }
1515
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001516
1517 /**
1518 * Called by a client to open a read-only stream containing data of a
1519 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1520 * except the file can only be read-only and the content provider may
1521 * perform data conversions to generate data of the desired type.
1522 *
1523 * <p>The default implementation compares the given mimeType against the
1524 * result of {@link #getType(Uri)} and, if they match, simply calls
1525 * {@link #openAssetFile(Uri, String)}.
1526 *
1527 * <p>See {@link ClipData} for examples of the use and implementation
1528 * of this method.
1529 * <p>
1530 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1531 * streaming of data.
1532 *
1533 * <p class="note">For better interoperability with other applications, it is recommended
1534 * that for any URIs that can be opened, you also support queries on them
1535 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1536 * You may also want to support other common columns if you have additional meta-data
1537 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1538 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1539 *
1540 * @param uri The data in the content provider being queried.
1541 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001542 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001543 * requirements; in this case the content provider will pick its best
1544 * type matching the pattern.
1545 * @param opts Additional options from the client. The definitions of
1546 * these are specific to the content provider being called.
1547 * @param signal A signal to cancel the operation in progress, or
1548 * {@code null} if none. For example, if you are downloading a
1549 * file from the network to service a "rw" mode request, you
1550 * should periodically call
1551 * {@link CancellationSignal#throwIfCanceled()} to check whether
1552 * the client has canceled the request and abort the download.
1553 *
1554 * @return Returns a new AssetFileDescriptor from which the client can
1555 * read data of the desired type.
1556 *
1557 * @throws FileNotFoundException Throws FileNotFoundException if there is
1558 * no file associated with the given URI or the mode is invalid.
1559 * @throws SecurityException Throws SecurityException if the caller does
1560 * not have permission to access the data.
1561 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1562 * content provider does not support the requested MIME type.
1563 *
1564 * @see #getStreamTypes(Uri, String)
1565 * @see #openAssetFile(Uri, String)
1566 * @see ClipDescription#compareMimeTypes(String, String)
1567 */
1568 public AssetFileDescriptor openTypedAssetFile(
1569 Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)
1570 throws FileNotFoundException {
1571 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1572 }
1573
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001574 /**
1575 * Interface to write a stream of data to a pipe. Use with
1576 * {@link ContentProvider#openPipeHelper}.
1577 */
1578 public interface PipeDataWriter<T> {
1579 /**
1580 * Called from a background thread to stream data out to a pipe.
1581 * Note that the pipe is blocking, so this thread can block on
1582 * writes for an arbitrary amount of time if the client is slow
1583 * at reading.
1584 *
1585 * @param output The pipe where data should be written. This will be
1586 * closed for you upon returning from this function.
1587 * @param uri The URI whose data is to be written.
1588 * @param mimeType The desired type of data to be written.
1589 * @param opts Options supplied by caller.
1590 * @param args Your own custom arguments.
1591 */
1592 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
1593 Bundle opts, T args);
1594 }
1595
1596 /**
1597 * A helper function for implementing {@link #openTypedAssetFile}, for
1598 * creating a data pipe and background thread allowing you to stream
1599 * generated data back to the client. This function returns a new
1600 * ParcelFileDescriptor that should be returned to the caller (the caller
1601 * is responsible for closing it).
1602 *
1603 * @param uri The URI whose data is to be written.
1604 * @param mimeType The desired type of data to be written.
1605 * @param opts Options supplied by caller.
1606 * @param args Your own custom arguments.
1607 * @param func Interface implementing the function that will actually
1608 * stream the data.
1609 * @return Returns a new ParcelFileDescriptor holding the read side of
1610 * the pipe. This should be returned to the caller for reading; the caller
1611 * is responsible for closing it when done.
1612 */
1613 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
1614 final Bundle opts, final T args, final PipeDataWriter<T> func)
1615 throws FileNotFoundException {
1616 try {
1617 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1618
1619 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1620 @Override
1621 protected Object doInBackground(Object... params) {
1622 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1623 try {
1624 fds[1].close();
1625 } catch (IOException e) {
1626 Log.w(TAG, "Failure closing pipe", e);
1627 }
1628 return null;
1629 }
1630 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001631 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001632
1633 return fds[0];
1634 } catch (IOException e) {
1635 throw new FileNotFoundException("failure making pipe");
1636 }
1637 }
1638
1639 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 * Returns true if this instance is a temporary content provider.
1641 * @return true if this instance is a temporary content provider
1642 */
1643 protected boolean isTemporary() {
1644 return false;
1645 }
1646
1647 /**
1648 * Returns the Binder object for this provider.
1649 *
1650 * @return the Binder object for this provider
1651 * @hide
1652 */
1653 public IContentProvider getIContentProvider() {
1654 return mTransport;
1655 }
1656
1657 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001658 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1659 * when directly instantiating the provider for testing.
1660 * @hide
1661 */
1662 public void attachInfoForTesting(Context context, ProviderInfo info) {
1663 attachInfo(context, info, true);
1664 }
1665
1666 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 * After being instantiated, this is called to tell the content provider
1668 * about itself.
1669 *
1670 * @param context The context this provider is running in
1671 * @param info Registered information about this content provider
1672 */
1673 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001674 attachInfo(context, info, false);
1675 }
1676
1677 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001678 mNoPerms = testing;
1679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 /*
1681 * Only allow it to be set once, so after the content service gives
1682 * this to us clients can't change it.
1683 */
1684 if (mContext == null) {
1685 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001686 if (context != null) {
1687 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1688 Context.APP_OPS_SERVICE);
1689 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001690 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 if (info != null) {
1692 setReadPermission(info.readPermission);
1693 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001694 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001695 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001696 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001697 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 }
1699 ContentProvider.this.onCreate();
1700 }
1701 }
Fred Quintanace31b232009-05-04 16:01:15 -07001702
1703 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001704 * Override this to handle requests to perform a batch of operations, or the
1705 * default implementation will iterate over the operations and call
1706 * {@link ContentProviderOperation#apply} on each of them.
1707 * If all calls to {@link ContentProviderOperation#apply} succeed
1708 * then a {@link ContentProviderResult} array with as many
1709 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001710 * fail, it is up to the implementation how many of the others take effect.
1711 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001712 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1713 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001714 *
Fred Quintanace31b232009-05-04 16:01:15 -07001715 * @param operations the operations to apply
1716 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001717 * @throws OperationApplicationException thrown if any operation fails.
1718 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001719 */
Fred Quintana03d94902009-05-22 14:23:31 -07001720 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001721 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001722 final int numOperations = operations.size();
1723 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1724 for (int i = 0; i < numOperations; i++) {
1725 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001726 }
1727 return results;
1728 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001729
1730 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001731 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001732 * interfaces that are cheaper and/or unnatural for a table-like
1733 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001734 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001735 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1736 * on this entry into the content provider besides the basic ability for the application
1737 * to get access to the provider at all. For example, it has no idea whether the call
1738 * being executed may read or write data in the provider, so can't enforce those
1739 * individual permissions. Any implementation of this method <strong>must</strong>
1740 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1741 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001742 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1743 * @param arg provider-defined String argument. May be {@code null}.
1744 * @param extras provider-defined Bundle argument. May be {@code null}.
1745 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001746 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001747 */
Scott Kennedy9f78f652015-03-01 15:29:25 -08001748 public Bundle call(String method, @Nullable String arg, @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001749 return null;
1750 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001751
1752 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001753 * Implement this to shut down the ContentProvider instance. You can then
1754 * invoke this method in unit tests.
1755 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001756 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001757 * Android normally handles ContentProvider startup and shutdown
1758 * automatically. You do not need to start up or shut down a
1759 * ContentProvider. When you invoke a test method on a ContentProvider,
1760 * however, a ContentProvider instance is started and keeps running after
1761 * the test finishes, even if a succeeding test instantiates another
1762 * ContentProvider. A conflict develops because the two instances are
1763 * usually running against the same underlying data source (for example, an
1764 * sqlite database).
1765 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001766 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001767 * Implementing shutDown() avoids this conflict by providing a way to
1768 * terminate the ContentProvider. This method can also prevent memory leaks
1769 * from multiple instantiations of the ContentProvider, and it can ensure
1770 * unit test isolation by allowing you to completely clean up the test
1771 * fixture before moving on to the next test.
1772 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001773 */
1774 public void shutdown() {
1775 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1776 "connections are gracefully shutdown");
1777 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001778
1779 /**
1780 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001781 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001782 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001783 * @param fd The raw file descriptor that the dump is being sent to.
1784 * @param writer The PrintWriter to which you should dump your state. This will be
1785 * closed for you after you return.
1786 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001787 */
1788 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1789 writer.println("nothing to dump");
1790 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001791
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001792 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001793 private void validateIncomingUri(Uri uri) throws SecurityException {
1794 String auth = uri.getAuthority();
1795 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001796 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
1797 throw new SecurityException("trying to query a ContentProvider in user "
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001798 + mContext.getUserId() + " with a uri belonging to user " + userId);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001799 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001800 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
1801 String message = "The authority of the uri " + uri + " does not match the one of the "
1802 + "contentProvider: ";
1803 if (mAuthority != null) {
1804 message += mAuthority;
1805 } else {
1806 message += mAuthorities;
1807 }
1808 throw new SecurityException(message);
1809 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001810 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001811
1812 /** @hide */
1813 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1814 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001815 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001816 if (end == -1) return defaultUserId;
1817 String userIdString = auth.substring(0, end);
1818 try {
1819 return Integer.parseInt(userIdString);
1820 } catch (NumberFormatException e) {
1821 Log.w(TAG, "Error parsing userId.", e);
1822 return UserHandle.USER_NULL;
1823 }
1824 }
1825
1826 /** @hide */
1827 public static int getUserIdFromAuthority(String auth) {
1828 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1829 }
1830
1831 /** @hide */
1832 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1833 if (uri == null) return defaultUserId;
1834 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1835 }
1836
1837 /** @hide */
1838 public static int getUserIdFromUri(Uri uri) {
1839 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1840 }
1841
1842 /**
1843 * Removes userId part from authority string. Expects format:
1844 * userId@some.authority
1845 * If there is no userId in the authority, it symply returns the argument
1846 * @hide
1847 */
1848 public static String getAuthorityWithoutUserId(String auth) {
1849 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001850 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001851 return auth.substring(end+1);
1852 }
1853
1854 /** @hide */
1855 public static Uri getUriWithoutUserId(Uri uri) {
1856 if (uri == null) return null;
1857 Uri.Builder builder = uri.buildUpon();
1858 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1859 return builder.build();
1860 }
1861
1862 /** @hide */
1863 public static boolean uriHasUserId(Uri uri) {
1864 if (uri == null) return false;
1865 return !TextUtils.isEmpty(uri.getUserInfo());
1866 }
1867
1868 /** @hide */
1869 public static Uri maybeAddUserId(Uri uri, int userId) {
1870 if (uri == null) return null;
1871 if (userId != UserHandle.USER_CURRENT
1872 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1873 if (!uriHasUserId(uri)) {
1874 //We don't add the user Id if there's already one
1875 Uri.Builder builder = uri.buildUpon();
1876 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1877 return builder.build();
1878 }
1879 }
1880 return uri;
1881 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001882}