blob: e916b9f2b2f1ce5d7c600d68339b8d9ff4219bb2 [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));
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700225 if (cursor == null) {
226 return null;
Svet Ganova2147ec2015-04-27 17:00:44 -0700227 }
228
229 // Return an empty cursor for all columns.
Makoto Onuki34bdcdb2015-06-12 17:14:57 -0700230 return new MatrixCursor(cursor.getColumnNames(), 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800231 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700232 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700233 try {
234 return ContentProvider.this.query(
235 uri, projection, selection, selectionArgs, sortOrder,
236 CancellationSignal.fromTransport(cancellationSignal));
237 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700238 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 }
241
Jeff Brown75ea64f2012-01-25 19:37:13 -0800242 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100244 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100245 uri = getUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 return ContentProvider.this.getType(uri);
247 }
248
Jeff Brown75ea64f2012-01-25 19:37:13 -0800249 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800250 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100251 validateIncomingUri(uri);
252 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100253 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800254 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800255 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800256 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700257 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700258 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100259 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700260 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700261 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 }
264
Jeff Brown75ea64f2012-01-25 19:37:13 -0800265 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800266 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100267 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100268 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800269 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800270 return 0;
271 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700272 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700273 try {
274 return ContentProvider.this.bulkInsert(uri, initialValues);
275 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700276 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 }
279
Jeff Brown75ea64f2012-01-25 19:37:13 -0800280 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800281 public ContentProviderResult[] applyBatch(String callingPkg,
282 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700283 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100284 int numOperations = operations.size();
285 final int[] userIds = new int[numOperations];
286 for (int i = 0; i < numOperations; i++) {
287 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100288 Uri uri = operation.getUri();
289 validateIncomingUri(uri);
290 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100291 if (userIds[i] != UserHandle.USER_CURRENT) {
292 // Removing the user id from the uri.
293 operation = new ContentProviderOperation(operation, true);
294 operations.set(i, operation);
295 }
Fred Quintana89437372009-05-15 15:10:40 -0700296 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800297 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800298 != AppOpsManager.MODE_ALLOWED) {
299 throw new OperationApplicationException("App op not allowed", 0);
300 }
Fred Quintana89437372009-05-15 15:10:40 -0700301 }
Fred Quintana89437372009-05-15 15:10:40 -0700302 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800303 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800304 != AppOpsManager.MODE_ALLOWED) {
305 throw new OperationApplicationException("App op not allowed", 0);
306 }
Fred Quintana89437372009-05-15 15:10:40 -0700307 }
308 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700309 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700310 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100311 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800312 if (results != null) {
313 for (int i = 0; i < results.length ; i++) {
314 if (userIds[i] != UserHandle.USER_CURRENT) {
315 // Adding the userId to the uri.
316 results[i] = new ContentProviderResult(results[i], userIds[i]);
317 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100318 }
319 }
320 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700321 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700322 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700323 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700324 }
325
Jeff Brown75ea64f2012-01-25 19:37:13 -0800326 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800327 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100328 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100329 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800330 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800331 return 0;
332 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700333 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700334 try {
335 return ContentProvider.this.delete(uri, selection, selectionArgs);
336 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700337 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 }
340
Jeff Brown75ea64f2012-01-25 19:37:13 -0800341 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800342 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100344 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100345 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800346 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800347 return 0;
348 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700349 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700350 try {
351 return ContentProvider.this.update(uri, values, selection, selectionArgs);
352 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700353 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 }
356
Jeff Brown75ea64f2012-01-25 19:37:13 -0800357 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700358 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800359 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
360 IBinder callerToken) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100361 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100362 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800363 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700364 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700365 try {
366 return ContentProvider.this.openFile(
367 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
368 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700369 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 }
372
Jeff Brown75ea64f2012-01-25 19:37:13 -0800373 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700374 public AssetFileDescriptor openAssetFile(
375 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800376 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100377 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100378 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800379 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700380 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700381 try {
382 return ContentProvider.this.openAssetFile(
383 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
384 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700385 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 }
388
Jeff Brown75ea64f2012-01-25 19:37:13 -0800389 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800390 public Bundle call(
391 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700392 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700393 try {
394 return ContentProvider.this.call(method, arg, extras);
395 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700396 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700397 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800398 }
399
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700400 @Override
401 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100402 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100403 uri = getUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700404 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
405 }
406
407 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800408 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700409 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100410 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100411 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800412 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700413 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700414 try {
415 return ContentProvider.this.openTypedAssetFile(
416 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
417 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700418 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700419 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700420 }
421
Jeff Brown75ea64f2012-01-25 19:37:13 -0800422 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700423 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800424 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800425 }
426
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700427 @Override
428 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100429 validateIncomingUri(uri);
430 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100431 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800432 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700433 return null;
434 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700435 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700436 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100437 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700438 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700439 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700440 }
441 }
442
443 @Override
444 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100445 validateIncomingUri(uri);
446 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100447 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800448 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700449 return null;
450 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700451 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700452 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100453 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700454 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700455 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700456 }
457 }
458
Dianne Hackbornff170242014-11-19 10:59:01 -0800459 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
460 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800461 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800462 if (enforceWritePermission(callingPkg, uri, callerToken)
463 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800464 throw new FileNotFoundException("App op not allowed");
465 }
466 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800467 if (enforceReadPermission(callingPkg, uri, callerToken)
468 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800469 throw new FileNotFoundException("App op not allowed");
470 }
471 }
472 }
473
Dianne Hackbornff170242014-11-19 10:59:01 -0800474 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
475 throws SecurityException {
476 enforceReadPermissionInner(uri, callerToken);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800477 if (mReadOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800478 return mAppOpsManager.noteOp(mReadOp, Binder.getCallingUid(), callingPkg);
479 }
480 return AppOpsManager.MODE_ALLOWED;
481 }
482
Dianne Hackbornff170242014-11-19 10:59:01 -0800483 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
484 throws SecurityException {
485 enforceWritePermissionInner(uri, callerToken);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800486 if (mWriteOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800487 return mAppOpsManager.noteOp(mWriteOp, Binder.getCallingUid(), callingPkg);
488 }
489 return AppOpsManager.MODE_ALLOWED;
490 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700491 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800492
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100493 boolean checkUser(int pid, int uid, Context context) {
494 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700495 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100496 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
497 == PERMISSION_GRANTED;
498 }
499
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700500 /** {@hide} */
Dianne Hackbornff170242014-11-19 10:59:01 -0800501 protected void enforceReadPermissionInner(Uri uri, IBinder callerToken)
502 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700503 final Context context = getContext();
504 final int pid = Binder.getCallingPid();
505 final int uid = Binder.getCallingUid();
506 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700507
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700508 if (UserHandle.isSameApp(uid, mMyUid)) {
509 return;
510 }
511
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100512 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700513 final String componentPerm = getReadPermission();
514 if (componentPerm != null) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800515 if (context.checkPermission(componentPerm, pid, uid, callerToken)
516 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700517 return;
518 } else {
519 missingPerm = componentPerm;
520 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700521 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700522
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700523 // track if unprotected read is allowed; any denied
524 // <path-permission> below removes this ability
525 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700526
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700527 final PathPermission[] pps = getPathPermissions();
528 if (pps != null) {
529 final String path = uri.getPath();
530 for (PathPermission pp : pps) {
531 final String pathPerm = pp.getReadPermission();
532 if (pathPerm != null && pp.match(path)) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800533 if (context.checkPermission(pathPerm, pid, uid, callerToken)
534 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700535 return;
536 } else {
537 // any denied <path-permission> means we lose
538 // default <provider> access.
539 allowDefaultRead = false;
540 missingPerm = pathPerm;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700541 }
542 }
543 }
544 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700545
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700546 // if we passed <path-permission> checks above, and no default
547 // <provider> permission, then allow access.
548 if (allowDefaultRead) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700550
551 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800552 final int callingUserId = UserHandle.getUserId(uid);
553 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
554 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800555 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
556 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700557 return;
558 }
559
560 final String failReason = mExported
561 ? " requires " + missingPerm + ", or grantUriPermission()"
562 : " requires the provider be exported, or grantUriPermission()";
563 throw new SecurityException("Permission Denial: reading "
564 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
565 + ", uid=" + uid + failReason);
566 }
567
568 /** {@hide} */
Dianne Hackbornff170242014-11-19 10:59:01 -0800569 protected void enforceWritePermissionInner(Uri uri, IBinder callerToken)
570 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700571 final Context context = getContext();
572 final int pid = Binder.getCallingPid();
573 final int uid = Binder.getCallingUid();
574 String missingPerm = null;
575
576 if (UserHandle.isSameApp(uid, mMyUid)) {
577 return;
578 }
579
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100580 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700581 final String componentPerm = getWritePermission();
582 if (componentPerm != null) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800583 if (context.checkPermission(componentPerm, pid, uid, callerToken)
584 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700585 return;
586 } else {
587 missingPerm = componentPerm;
588 }
589 }
590
591 // track if unprotected write is allowed; any denied
592 // <path-permission> below removes this ability
593 boolean allowDefaultWrite = (componentPerm == null);
594
595 final PathPermission[] pps = getPathPermissions();
596 if (pps != null) {
597 final String path = uri.getPath();
598 for (PathPermission pp : pps) {
599 final String pathPerm = pp.getWritePermission();
600 if (pathPerm != null && pp.match(path)) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800601 if (context.checkPermission(pathPerm, pid, uid, callerToken)
602 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700603 return;
604 } else {
605 // any denied <path-permission> means we lose
606 // default <provider> access.
607 allowDefaultWrite = false;
608 missingPerm = pathPerm;
609 }
610 }
611 }
612 }
613
614 // if we passed <path-permission> checks above, and no default
615 // <provider> permission, then allow access.
616 if (allowDefaultWrite) return;
617 }
618
619 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800620 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
621 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700622 return;
623 }
624
625 final String failReason = mExported
626 ? " requires " + missingPerm + ", or grantUriPermission()"
627 : " requires the provider be exported, or grantUriPermission()";
628 throw new SecurityException("Permission Denial: writing "
629 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
630 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 }
632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700634 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800635 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 * constructor.
637 */
638 public final Context getContext() {
639 return mContext;
640 }
641
642 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700643 * Set the calling package, returning the current value (or {@code null})
644 * which can be used later to restore the previous state.
645 */
646 private String setCallingPackage(String callingPackage) {
647 final String original = mCallingPackage.get();
648 mCallingPackage.set(callingPackage);
649 return original;
650 }
651
652 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700653 * Return the package name of the caller that initiated the request being
654 * processed on the current thread. The returned package will have been
655 * verified to belong to the calling UID. Returns {@code null} if not
656 * currently processing a request.
657 * <p>
658 * This will always return {@code null} when processing
659 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
660 *
661 * @see Binder#getCallingUid()
662 * @see Context#grantUriPermission(String, Uri, int)
663 * @throws SecurityException if the calling package doesn't belong to the
664 * calling UID.
665 */
666 public final String getCallingPackage() {
667 final String pkg = mCallingPackage.get();
668 if (pkg != null) {
669 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
670 }
671 return pkg;
672 }
673
674 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100675 * Change the authorities of the ContentProvider.
676 * This is normally set for you from its manifest information when the provider is first
677 * created.
678 * @hide
679 * @param authorities the semi-colon separated authorities of the ContentProvider.
680 */
681 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100682 if (authorities != null) {
683 if (authorities.indexOf(';') == -1) {
684 mAuthority = authorities;
685 mAuthorities = null;
686 } else {
687 mAuthority = null;
688 mAuthorities = authorities.split(";");
689 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100690 }
691 }
692
693 /** @hide */
694 protected final boolean matchesOurAuthorities(String authority) {
695 if (mAuthority != null) {
696 return mAuthority.equals(authority);
697 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100698 if (mAuthorities != null) {
699 int length = mAuthorities.length;
700 for (int i = 0; i < length; i++) {
701 if (mAuthorities[i].equals(authority)) return true;
702 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100703 }
704 return false;
705 }
706
707
708 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 * Change the permission required to read data from the content
710 * provider. This is normally set for you from its manifest information
711 * when the provider is first created.
712 *
713 * @param permission Name of the permission required for read-only access.
714 */
715 protected final void setReadPermission(String permission) {
716 mReadPermission = permission;
717 }
718
719 /**
720 * Return the name of the permission required for read-only access to
721 * this content provider. This method can be called from multiple
722 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800723 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
724 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 */
726 public final String getReadPermission() {
727 return mReadPermission;
728 }
729
730 /**
731 * Change the permission required to read and write data in the content
732 * provider. This is normally set for you from its manifest information
733 * when the provider is first created.
734 *
735 * @param permission Name of the permission required for read/write access.
736 */
737 protected final void setWritePermission(String permission) {
738 mWritePermission = permission;
739 }
740
741 /**
742 * Return the name of the permission required for read/write access to
743 * this content provider. This method can be called from multiple
744 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800745 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
746 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 */
748 public final String getWritePermission() {
749 return mWritePermission;
750 }
751
752 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700753 * Change the path-based permission required to read and/or write data in
754 * the content provider. This is normally set for you from its manifest
755 * information when the provider is first created.
756 *
757 * @param permissions Array of path permission descriptions.
758 */
759 protected final void setPathPermissions(PathPermission[] permissions) {
760 mPathPermissions = permissions;
761 }
762
763 /**
764 * Return the path-based permissions required for read and/or write access to
765 * this content provider. This method can be called from multiple
766 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800767 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
768 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700769 */
770 public final PathPermission[] getPathPermissions() {
771 return mPathPermissions;
772 }
773
Dianne Hackborn35654b62013-01-14 17:38:02 -0800774 /** @hide */
775 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800776 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800777 mTransport.mReadOp = readOp;
778 mTransport.mWriteOp = writeOp;
779 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800780 }
781
Dianne Hackborn961321f2013-02-05 17:22:41 -0800782 /** @hide */
783 public AppOpsManager getAppOpsManager() {
784 return mTransport.mAppOpsManager;
785 }
786
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700787 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700788 * Implement this to initialize your content provider on startup.
789 * This method is called for all registered content providers on the
790 * application main thread at application launch time. It must not perform
791 * lengthy operations, or application startup will be delayed.
792 *
793 * <p>You should defer nontrivial initialization (such as opening,
794 * upgrading, and scanning databases) until the content provider is used
795 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
796 * keeps application startup fast, avoids unnecessary work if the provider
797 * turns out not to be needed, and stops database errors (such as a full
798 * disk) from halting application launch.
799 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700800 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700801 * is a helpful utility class that makes it easy to manage databases,
802 * and will automatically defer opening until first use. If you do use
803 * SQLiteOpenHelper, make sure to avoid calling
804 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
805 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
806 * from this method. (Instead, override
807 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
808 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 *
810 * @return true if the provider was successfully loaded, false otherwise
811 */
812 public abstract boolean onCreate();
813
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700814 /**
815 * {@inheritDoc}
816 * This method is always called on the application main thread, and must
817 * not perform lengthy operations.
818 *
819 * <p>The default content provider implementation does nothing.
820 * Override this method to take appropriate action.
821 * (Content providers do not usually care about things like screen
822 * orientation, but may want to know about locale changes.)
823 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 public void onConfigurationChanged(Configuration newConfig) {
825 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700826
827 /**
828 * {@inheritDoc}
829 * This method is always called on the application main thread, and must
830 * not perform lengthy operations.
831 *
832 * <p>The default content provider implementation does nothing.
833 * Subclasses may override this method to take appropriate action.
834 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 public void onLowMemory() {
836 }
837
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700838 public void onTrimMemory(int level) {
839 }
840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700842 * Implement this to handle query requests from clients.
843 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800844 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
845 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 * <p>
847 * Example client call:<p>
848 * <pre>// Request a specific record.
849 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000850 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 projection, // Which columns to return.
852 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000853 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 People.NAME + " ASC"); // Sort order.</pre>
855 * Example implementation:<p>
856 * <pre>// SQLiteQueryBuilder is a helper class that creates the
857 // proper SQL syntax for us.
858 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
859
860 // Set the table we're querying.
861 qBuilder.setTables(DATABASE_TABLE_NAME);
862
863 // If the query ends in a specific record number, we're
864 // being asked for a specific record, so set the
865 // WHERE clause in our query.
866 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
867 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
868 }
869
870 // Make the query.
871 Cursor c = qBuilder.query(mDb,
872 projection,
873 selection,
874 selectionArgs,
875 groupBy,
876 having,
877 sortOrder);
878 c.setNotificationUri(getContext().getContentResolver(), uri);
879 return c;</pre>
880 *
881 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000882 * if the client is requesting a specific record, the URI will end in a record number
883 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
884 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800886 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800888 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000889 * @param selectionArgs You may include ?s in selection, which will be replaced by
890 * the values from selectionArgs, in order that they appear in the selection.
891 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800893 * If {@code null} then the provider is free to define the sort order.
894 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 */
896 public abstract Cursor query(Uri uri, String[] projection,
897 String selection, String[] selectionArgs, String sortOrder);
898
Fred Quintana5bba6322009-10-05 14:21:12 -0700899 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800900 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800901 * This method can be called from multiple threads, as described in
902 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
903 * and Threads</a>.
904 * <p>
905 * Example client call:<p>
906 * <pre>// Request a specific record.
907 * Cursor managedCursor = managedQuery(
908 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
909 projection, // Which columns to return.
910 null, // WHERE clause.
911 null, // WHERE clause value substitution
912 People.NAME + " ASC"); // Sort order.</pre>
913 * Example implementation:<p>
914 * <pre>// SQLiteQueryBuilder is a helper class that creates the
915 // proper SQL syntax for us.
916 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
917
918 // Set the table we're querying.
919 qBuilder.setTables(DATABASE_TABLE_NAME);
920
921 // If the query ends in a specific record number, we're
922 // being asked for a specific record, so set the
923 // WHERE clause in our query.
924 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
925 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
926 }
927
928 // Make the query.
929 Cursor c = qBuilder.query(mDb,
930 projection,
931 selection,
932 selectionArgs,
933 groupBy,
934 having,
935 sortOrder);
936 c.setNotificationUri(getContext().getContentResolver(), uri);
937 return c;</pre>
938 * <p>
939 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800940 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
941 * signal to ensure correct operation on older versions of the Android Framework in
942 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800943 *
944 * @param uri The URI to query. This will be the full URI sent by the client;
945 * if the client is requesting a specific record, the URI will end in a record number
946 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
947 * that _id value.
948 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800949 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800950 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800951 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800952 * @param selectionArgs You may include ?s in selection, which will be replaced by
953 * the values from selectionArgs, in order that they appear in the selection.
954 * The values will be bound as Strings.
955 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800956 * If {@code null} then the provider is free to define the sort order.
957 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800958 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
959 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800960 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800961 */
962 public Cursor query(Uri uri, String[] projection,
963 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800964 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800965 return query(uri, projection, selection, selectionArgs, sortOrder);
966 }
967
968 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700969 * Implement this to handle requests for the MIME type of the data at the
970 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 * <code>vnd.android.cursor.item</code> for a single record,
972 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700973 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800974 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
975 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700977 * <p>Note that there are no permissions needed for an application to
978 * access this information; if your content provider requires read and/or
979 * write permissions, or is not exported, all applications can still call
980 * this method regardless of their access permissions. This allows them
981 * to retrieve the MIME type for a URI when dispatching intents.
982 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800984 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 */
986 public abstract String getType(Uri uri);
987
988 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700989 * Implement this to support canonicalization of URIs that refer to your
990 * content provider. A canonical URI is one that can be transported across
991 * devices, backup/restore, and other contexts, and still be able to refer
992 * to the same data item. Typically this is implemented by adding query
993 * params to the URI allowing the content provider to verify that an incoming
994 * canonical URI references the same data as it was originally intended for and,
995 * if it doesn't, to find that data (if it exists) in the current environment.
996 *
997 * <p>For example, if the content provider holds people and a normal URI in it
998 * is created with a row index into that people database, the cananical representation
999 * may have an additional query param at the end which specifies the name of the
1000 * person it is intended for. Later calls into the provider with that URI will look
1001 * up the row of that URI's base index and, if it doesn't match or its entry's
1002 * name doesn't match the name in the query param, perform a query on its database
1003 * to find the correct row to operate on.</p>
1004 *
1005 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1006 * URIs (including this one) must perform this verification and recovery of any
1007 * canonical URIs they receive. In addition, you must also implement
1008 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1009 *
1010 * <p>The default implementation of this method returns null, indicating that
1011 * canonical URIs are not supported.</p>
1012 *
1013 * @param url The Uri to canonicalize.
1014 *
1015 * @return Return the canonical representation of <var>url</var>, or null if
1016 * canonicalization of that Uri is not supported.
1017 */
1018 public Uri canonicalize(Uri url) {
1019 return null;
1020 }
1021
1022 /**
1023 * Remove canonicalization from canonical URIs previously returned by
1024 * {@link #canonicalize}. For example, if your implementation is to add
1025 * a query param to canonicalize a URI, this method can simply trip any
1026 * query params on the URI. The default implementation always returns the
1027 * same <var>url</var> that was passed in.
1028 *
1029 * @param url The Uri to remove any canonicalization from.
1030 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001031 * @return Return the non-canonical representation of <var>url</var>, return
1032 * the <var>url</var> as-is if there is nothing to do, or return null if
1033 * the data identified by the canonical representation can not be found in
1034 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001035 */
1036 public Uri uncanonicalize(Uri url) {
1037 return url;
1038 }
1039
1040 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001041 * @hide
1042 * Implementation when a caller has performed an insert on the content
1043 * provider, but that call has been rejected for the operation given
1044 * to {@link #setAppOps(int, int)}. The default implementation simply
1045 * returns a dummy URI that is the base URI with a 0 path element
1046 * appended.
1047 */
1048 public Uri rejectInsert(Uri uri, ContentValues values) {
1049 // If not allowed, we need to return some reasonable URI. Maybe the
1050 // content provider should be responsible for this, but for now we
1051 // will just return the base URI with a dummy '0' tagged on to it.
1052 // You shouldn't be able to read if you can't write, anyway, so it
1053 // shouldn't matter much what is returned.
1054 return uri.buildUpon().appendPath("0").build();
1055 }
1056
1057 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001058 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1060 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001061 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001062 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1063 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001064 * @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 -08001065 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001066 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 * @return The URI for the newly inserted item.
1068 */
1069 public abstract Uri insert(Uri uri, ContentValues values);
1070
1071 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001072 * Override this to handle requests to insert a set of new rows, or the
1073 * default implementation will iterate over the values and call
1074 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1076 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001077 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001078 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1079 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 *
1081 * @param uri The content:// URI of the insertion request.
1082 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001083 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 * @return The number of values that were inserted.
1085 */
1086 public int bulkInsert(Uri uri, ContentValues[] values) {
1087 int numValues = values.length;
1088 for (int i = 0; i < numValues; i++) {
1089 insert(uri, values[i]);
1090 }
1091 return numValues;
1092 }
1093
1094 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001095 * Implement this to handle requests to delete one or more rows.
1096 * The implementation should apply the selection clause when performing
1097 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001098 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001100 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001101 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1102 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 *
1104 * <p>The implementation is responsible for parsing out a row ID at the end
1105 * of the URI, if a specific row is being deleted. That is, the client would
1106 * pass in <code>content://contacts/people/22</code> and the implementation is
1107 * responsible for parsing the record number (22) when creating a SQL statement.
1108 *
1109 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1110 * @param selection An optional restriction to apply to rows when deleting.
1111 * @return The number of rows affected.
1112 * @throws SQLException
1113 */
1114 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
1115
1116 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001117 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001118 * The implementation should update all rows matching the selection
1119 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1121 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001122 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001123 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1124 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 *
1126 * @param uri The URI to query. This can potentially have a record ID if this
1127 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001128 * @param values A set of column_name/value pairs to update in the database.
1129 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 * @param selection An optional filter to match rows to update.
1131 * @return the number of rows affected.
1132 */
1133 public abstract int update(Uri uri, ContentValues values, String selection,
1134 String[] selectionArgs);
1135
1136 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001137 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001138 * The default implementation always throws {@link FileNotFoundException}.
1139 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001140 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1141 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001142 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001143 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1144 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001145 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 *
1147 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1148 * their responsibility to close it when done. That is, the implementation
1149 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001150 * <p>
1151 * If opened with the exclusive "r" or "w" modes, the returned
1152 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1153 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1154 * supports seeking.
1155 * <p>
1156 * If you need to detect when the returned ParcelFileDescriptor has been
1157 * closed, or if the remote process has crashed or encountered some other
1158 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1159 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1160 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1161 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001163 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1164 * to return the appropriate MIME type for the data returned here with
1165 * the same URI. This will allow intent resolution to automatically determine the data MIME
1166 * type and select the appropriate matching targets as part of its operation.</p>
1167 *
1168 * <p class="note">For better interoperability with other applications, it is recommended
1169 * that for any URIs that can be opened, you also support queries on them
1170 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1171 * You may also want to support other common columns if you have additional meta-data
1172 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1173 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1174 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 * @param uri The URI whose file is to be opened.
1176 * @param mode Access mode for the file. May be "r" for read-only access,
1177 * "rw" for read and write access, or "rwt" for read and write access
1178 * that truncates any existing file.
1179 *
1180 * @return Returns a new ParcelFileDescriptor which you can use to access
1181 * the file.
1182 *
1183 * @throws FileNotFoundException Throws FileNotFoundException if there is
1184 * no file associated with the given URI or the mode is invalid.
1185 * @throws SecurityException Throws SecurityException if the caller does
1186 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001187 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 * @see #openAssetFile(Uri, String)
1189 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001190 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001191 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001192 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 public ParcelFileDescriptor openFile(Uri uri, String mode)
1194 throws FileNotFoundException {
1195 throw new FileNotFoundException("No files supported by provider at "
1196 + uri);
1197 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001200 * Override this to handle requests to open a file blob.
1201 * The default implementation always throws {@link FileNotFoundException}.
1202 * This method can be called from multiple threads, as described in
1203 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1204 * and Threads</a>.
1205 *
1206 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1207 * to the caller. This way large data (such as images and documents) can be
1208 * returned without copying the content.
1209 *
1210 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1211 * their responsibility to close it when done. That is, the implementation
1212 * of this method should create a new ParcelFileDescriptor for each call.
1213 * <p>
1214 * If opened with the exclusive "r" or "w" modes, the returned
1215 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1216 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1217 * supports seeking.
1218 * <p>
1219 * If you need to detect when the returned ParcelFileDescriptor has been
1220 * closed, or if the remote process has crashed or encountered some other
1221 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1222 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1223 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1224 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1225 *
1226 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1227 * to return the appropriate MIME type for the data returned here with
1228 * the same URI. This will allow intent resolution to automatically determine the data MIME
1229 * type and select the appropriate matching targets as part of its operation.</p>
1230 *
1231 * <p class="note">For better interoperability with other applications, it is recommended
1232 * that for any URIs that can be opened, you also support queries on them
1233 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1234 * You may also want to support other common columns if you have additional meta-data
1235 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1236 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1237 *
1238 * @param uri The URI whose file is to be opened.
1239 * @param mode Access mode for the file. May be "r" for read-only access,
1240 * "w" for write-only access, "rw" for read and write access, or
1241 * "rwt" for read and write access that truncates any existing
1242 * file.
1243 * @param signal A signal to cancel the operation in progress, or
1244 * {@code null} if none. For example, if you are downloading a
1245 * file from the network to service a "rw" mode request, you
1246 * should periodically call
1247 * {@link CancellationSignal#throwIfCanceled()} to check whether
1248 * the client has canceled the request and abort the download.
1249 *
1250 * @return Returns a new ParcelFileDescriptor which you can use to access
1251 * the file.
1252 *
1253 * @throws FileNotFoundException Throws FileNotFoundException if there is
1254 * no file associated with the given URI or the mode is invalid.
1255 * @throws SecurityException Throws SecurityException if the caller does
1256 * not have permission to access the file.
1257 *
1258 * @see #openAssetFile(Uri, String)
1259 * @see #openFileHelper(Uri, String)
1260 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001261 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001262 */
1263 public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
1264 throws FileNotFoundException {
1265 return openFile(uri, mode);
1266 }
1267
1268 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 * This is like {@link #openFile}, but can be implemented by providers
1270 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001271 * inside of their .apk.
1272 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001273 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1274 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001275 *
1276 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001277 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001278 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1280 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1281 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001282 * <p>
1283 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1284 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001285 *
1286 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 * should create the AssetFileDescriptor with
1288 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001289 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001291 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1292 * to return the appropriate MIME type for the data returned here with
1293 * the same URI. This will allow intent resolution to automatically determine the data MIME
1294 * type and select the appropriate matching targets as part of its operation.</p>
1295 *
1296 * <p class="note">For better interoperability with other applications, it is recommended
1297 * that for any URIs that can be opened, you also support queries on them
1298 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1299 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 * @param uri The URI whose file is to be opened.
1301 * @param mode Access mode for the file. May be "r" for read-only access,
1302 * "w" for write-only access (erasing whatever data is currently in
1303 * the file), "wa" for write-only access to append to any existing data,
1304 * "rw" for read and write access on any existing data, and "rwt" for read
1305 * and write access that truncates any existing file.
1306 *
1307 * @return Returns a new AssetFileDescriptor which you can use to access
1308 * the file.
1309 *
1310 * @throws FileNotFoundException Throws FileNotFoundException if there is
1311 * no file associated with the given URI or the mode is invalid.
1312 * @throws SecurityException Throws SecurityException if the caller does
1313 * not have permission to access the file.
1314 *
1315 * @see #openFile(Uri, String)
1316 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001317 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 */
1319 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
1320 throws FileNotFoundException {
1321 ParcelFileDescriptor fd = openFile(uri, mode);
1322 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1323 }
1324
1325 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001326 * This is like {@link #openFile}, but can be implemented by providers
1327 * that need to be able to return sub-sections of files, often assets
1328 * inside of their .apk.
1329 * This method can be called from multiple threads, as described in
1330 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1331 * and Threads</a>.
1332 *
1333 * <p>If you implement this, your clients must be able to deal with such
1334 * file slices, either directly with
1335 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1336 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1337 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1338 * methods.
1339 * <p>
1340 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1341 * streaming of data.
1342 *
1343 * <p class="note">If you are implementing this to return a full file, you
1344 * should create the AssetFileDescriptor with
1345 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1346 * applications that cannot handle sub-sections of files.</p>
1347 *
1348 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1349 * to return the appropriate MIME type for the data returned here with
1350 * the same URI. This will allow intent resolution to automatically determine the data MIME
1351 * type and select the appropriate matching targets as part of its operation.</p>
1352 *
1353 * <p class="note">For better interoperability with other applications, it is recommended
1354 * that for any URIs that can be opened, you also support queries on them
1355 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1356 *
1357 * @param uri The URI whose file is to be opened.
1358 * @param mode Access mode for the file. May be "r" for read-only access,
1359 * "w" for write-only access (erasing whatever data is currently in
1360 * the file), "wa" for write-only access to append to any existing data,
1361 * "rw" for read and write access on any existing data, and "rwt" for read
1362 * and write access that truncates any existing file.
1363 * @param signal A signal to cancel the operation in progress, or
1364 * {@code null} if none. For example, if you are downloading a
1365 * file from the network to service a "rw" mode request, you
1366 * should periodically call
1367 * {@link CancellationSignal#throwIfCanceled()} to check whether
1368 * the client has canceled the request and abort the download.
1369 *
1370 * @return Returns a new AssetFileDescriptor which you can use to access
1371 * the file.
1372 *
1373 * @throws FileNotFoundException Throws FileNotFoundException if there is
1374 * no file associated with the given URI or the mode is invalid.
1375 * @throws SecurityException Throws SecurityException if the caller does
1376 * not have permission to access the file.
1377 *
1378 * @see #openFile(Uri, String)
1379 * @see #openFileHelper(Uri, String)
1380 * @see #getType(android.net.Uri)
1381 */
1382 public AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)
1383 throws FileNotFoundException {
1384 return openAssetFile(uri, mode);
1385 }
1386
1387 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 * Convenience for subclasses that wish to implement {@link #openFile}
1389 * by looking up a column named "_data" at the given URI.
1390 *
1391 * @param uri The URI to be opened.
1392 * @param mode The file mode. May be "r" for read-only access,
1393 * "w" for write-only access (erasing whatever data is currently in
1394 * the file), "wa" for write-only access to append to any existing data,
1395 * "rw" for read and write access on any existing data, and "rwt" for read
1396 * and write access that truncates any existing file.
1397 *
1398 * @return Returns a new ParcelFileDescriptor that can be used by the
1399 * client to access the file.
1400 */
1401 protected final ParcelFileDescriptor openFileHelper(Uri uri,
1402 String mode) throws FileNotFoundException {
1403 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1404 int count = (c != null) ? c.getCount() : 0;
1405 if (count != 1) {
1406 // If there is not exactly one result, throw an appropriate
1407 // exception.
1408 if (c != null) {
1409 c.close();
1410 }
1411 if (count == 0) {
1412 throw new FileNotFoundException("No entry for " + uri);
1413 }
1414 throw new FileNotFoundException("Multiple items at " + uri);
1415 }
1416
1417 c.moveToFirst();
1418 int i = c.getColumnIndex("_data");
1419 String path = (i >= 0 ? c.getString(i) : null);
1420 c.close();
1421 if (path == null) {
1422 throw new FileNotFoundException("Column _data not found.");
1423 }
1424
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001425 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 return ParcelFileDescriptor.open(new File(path), modeBits);
1427 }
1428
1429 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001430 * Called by a client to determine the types of data streams that this
1431 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001432 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001433 * of a particular type, return that MIME type if it matches the given
1434 * mimeTypeFilter. If it can perform type conversions, return an array
1435 * of all supported MIME types that match mimeTypeFilter.
1436 *
1437 * @param uri The data in the content provider being queried.
1438 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001439 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001440 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001441 * given mimeTypeFilter. Otherwise returns an array of all available
1442 * concrete MIME types.
1443 *
1444 * @see #getType(Uri)
1445 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001446 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001447 */
1448 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
1449 return null;
1450 }
1451
1452 /**
1453 * Called by a client to open a read-only stream containing data of a
1454 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1455 * except the file can only be read-only and the content provider may
1456 * perform data conversions to generate data of the desired type.
1457 *
1458 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001459 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001460 * {@link #openAssetFile(Uri, String)}.
1461 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001462 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001463 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001464 * <p>
1465 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1466 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001467 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001468 * <p class="note">For better interoperability with other applications, it is recommended
1469 * that for any URIs that can be opened, you also support queries on them
1470 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1471 * You may also want to support other common columns if you have additional meta-data
1472 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1473 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1474 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001475 * @param uri The data in the content provider being queried.
1476 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001477 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001478 * requirements; in this case the content provider will pick its best
1479 * type matching the pattern.
1480 * @param opts Additional options from the client. The definitions of
1481 * these are specific to the content provider being called.
1482 *
1483 * @return Returns a new AssetFileDescriptor from which the client can
1484 * read data of the desired type.
1485 *
1486 * @throws FileNotFoundException Throws FileNotFoundException if there is
1487 * no file associated with the given URI or the mode is invalid.
1488 * @throws SecurityException Throws SecurityException if the caller does
1489 * not have permission to access the data.
1490 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1491 * content provider does not support the requested MIME type.
1492 *
1493 * @see #getStreamTypes(Uri, String)
1494 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001495 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001496 */
1497 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
1498 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001499 if ("*/*".equals(mimeTypeFilter)) {
1500 // If they can take anything, the untyped open call is good enough.
1501 return openAssetFile(uri, "r");
1502 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001503 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001504 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001505 // Use old untyped open call if this provider has a type for this
1506 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001507 return openAssetFile(uri, "r");
1508 }
1509 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1510 }
1511
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001512
1513 /**
1514 * Called by a client to open a read-only stream containing data of a
1515 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1516 * except the file can only be read-only and the content provider may
1517 * perform data conversions to generate data of the desired type.
1518 *
1519 * <p>The default implementation compares the given mimeType against the
1520 * result of {@link #getType(Uri)} and, if they match, simply calls
1521 * {@link #openAssetFile(Uri, String)}.
1522 *
1523 * <p>See {@link ClipData} for examples of the use and implementation
1524 * of this method.
1525 * <p>
1526 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1527 * streaming of data.
1528 *
1529 * <p class="note">For better interoperability with other applications, it is recommended
1530 * that for any URIs that can be opened, you also support queries on them
1531 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1532 * You may also want to support other common columns if you have additional meta-data
1533 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1534 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1535 *
1536 * @param uri The data in the content provider being queried.
1537 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001538 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001539 * requirements; in this case the content provider will pick its best
1540 * type matching the pattern.
1541 * @param opts Additional options from the client. The definitions of
1542 * these are specific to the content provider being called.
1543 * @param signal A signal to cancel the operation in progress, or
1544 * {@code null} if none. For example, if you are downloading a
1545 * file from the network to service a "rw" mode request, you
1546 * should periodically call
1547 * {@link CancellationSignal#throwIfCanceled()} to check whether
1548 * the client has canceled the request and abort the download.
1549 *
1550 * @return Returns a new AssetFileDescriptor from which the client can
1551 * read data of the desired type.
1552 *
1553 * @throws FileNotFoundException Throws FileNotFoundException if there is
1554 * no file associated with the given URI or the mode is invalid.
1555 * @throws SecurityException Throws SecurityException if the caller does
1556 * not have permission to access the data.
1557 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1558 * content provider does not support the requested MIME type.
1559 *
1560 * @see #getStreamTypes(Uri, String)
1561 * @see #openAssetFile(Uri, String)
1562 * @see ClipDescription#compareMimeTypes(String, String)
1563 */
1564 public AssetFileDescriptor openTypedAssetFile(
1565 Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)
1566 throws FileNotFoundException {
1567 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1568 }
1569
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001570 /**
1571 * Interface to write a stream of data to a pipe. Use with
1572 * {@link ContentProvider#openPipeHelper}.
1573 */
1574 public interface PipeDataWriter<T> {
1575 /**
1576 * Called from a background thread to stream data out to a pipe.
1577 * Note that the pipe is blocking, so this thread can block on
1578 * writes for an arbitrary amount of time if the client is slow
1579 * at reading.
1580 *
1581 * @param output The pipe where data should be written. This will be
1582 * closed for you upon returning from this function.
1583 * @param uri The URI whose data is to be written.
1584 * @param mimeType The desired type of data to be written.
1585 * @param opts Options supplied by caller.
1586 * @param args Your own custom arguments.
1587 */
1588 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
1589 Bundle opts, T args);
1590 }
1591
1592 /**
1593 * A helper function for implementing {@link #openTypedAssetFile}, for
1594 * creating a data pipe and background thread allowing you to stream
1595 * generated data back to the client. This function returns a new
1596 * ParcelFileDescriptor that should be returned to the caller (the caller
1597 * is responsible for closing it).
1598 *
1599 * @param uri The URI whose data is to be written.
1600 * @param mimeType The desired type of data to be written.
1601 * @param opts Options supplied by caller.
1602 * @param args Your own custom arguments.
1603 * @param func Interface implementing the function that will actually
1604 * stream the data.
1605 * @return Returns a new ParcelFileDescriptor holding the read side of
1606 * the pipe. This should be returned to the caller for reading; the caller
1607 * is responsible for closing it when done.
1608 */
1609 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
1610 final Bundle opts, final T args, final PipeDataWriter<T> func)
1611 throws FileNotFoundException {
1612 try {
1613 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1614
1615 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1616 @Override
1617 protected Object doInBackground(Object... params) {
1618 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1619 try {
1620 fds[1].close();
1621 } catch (IOException e) {
1622 Log.w(TAG, "Failure closing pipe", e);
1623 }
1624 return null;
1625 }
1626 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001627 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001628
1629 return fds[0];
1630 } catch (IOException e) {
1631 throw new FileNotFoundException("failure making pipe");
1632 }
1633 }
1634
1635 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 * Returns true if this instance is a temporary content provider.
1637 * @return true if this instance is a temporary content provider
1638 */
1639 protected boolean isTemporary() {
1640 return false;
1641 }
1642
1643 /**
1644 * Returns the Binder object for this provider.
1645 *
1646 * @return the Binder object for this provider
1647 * @hide
1648 */
1649 public IContentProvider getIContentProvider() {
1650 return mTransport;
1651 }
1652
1653 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001654 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1655 * when directly instantiating the provider for testing.
1656 * @hide
1657 */
1658 public void attachInfoForTesting(Context context, ProviderInfo info) {
1659 attachInfo(context, info, true);
1660 }
1661
1662 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 * After being instantiated, this is called to tell the content provider
1664 * about itself.
1665 *
1666 * @param context The context this provider is running in
1667 * @param info Registered information about this content provider
1668 */
1669 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001670 attachInfo(context, info, false);
1671 }
1672
1673 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001674 mNoPerms = testing;
1675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 /*
1677 * Only allow it to be set once, so after the content service gives
1678 * this to us clients can't change it.
1679 */
1680 if (mContext == null) {
1681 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001682 if (context != null) {
1683 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1684 Context.APP_OPS_SERVICE);
1685 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001686 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 if (info != null) {
1688 setReadPermission(info.readPermission);
1689 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001690 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001691 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001692 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001693 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
1695 ContentProvider.this.onCreate();
1696 }
1697 }
Fred Quintanace31b232009-05-04 16:01:15 -07001698
1699 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001700 * Override this to handle requests to perform a batch of operations, or the
1701 * default implementation will iterate over the operations and call
1702 * {@link ContentProviderOperation#apply} on each of them.
1703 * If all calls to {@link ContentProviderOperation#apply} succeed
1704 * then a {@link ContentProviderResult} array with as many
1705 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001706 * fail, it is up to the implementation how many of the others take effect.
1707 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001708 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1709 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001710 *
Fred Quintanace31b232009-05-04 16:01:15 -07001711 * @param operations the operations to apply
1712 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001713 * @throws OperationApplicationException thrown if any operation fails.
1714 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001715 */
Fred Quintana03d94902009-05-22 14:23:31 -07001716 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001717 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001718 final int numOperations = operations.size();
1719 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1720 for (int i = 0; i < numOperations; i++) {
1721 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001722 }
1723 return results;
1724 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001725
1726 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001727 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001728 * interfaces that are cheaper and/or unnatural for a table-like
1729 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001730 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001731 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1732 * on this entry into the content provider besides the basic ability for the application
1733 * to get access to the provider at all. For example, it has no idea whether the call
1734 * being executed may read or write data in the provider, so can't enforce those
1735 * individual permissions. Any implementation of this method <strong>must</strong>
1736 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1737 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001738 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1739 * @param arg provider-defined String argument. May be {@code null}.
1740 * @param extras provider-defined Bundle argument. May be {@code null}.
1741 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001742 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001743 */
Scott Kennedy9f78f652015-03-01 15:29:25 -08001744 public Bundle call(String method, @Nullable String arg, @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001745 return null;
1746 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001747
1748 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001749 * Implement this to shut down the ContentProvider instance. You can then
1750 * invoke this method in unit tests.
1751 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001752 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001753 * Android normally handles ContentProvider startup and shutdown
1754 * automatically. You do not need to start up or shut down a
1755 * ContentProvider. When you invoke a test method on a ContentProvider,
1756 * however, a ContentProvider instance is started and keeps running after
1757 * the test finishes, even if a succeeding test instantiates another
1758 * ContentProvider. A conflict develops because the two instances are
1759 * usually running against the same underlying data source (for example, an
1760 * sqlite database).
1761 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001762 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001763 * Implementing shutDown() avoids this conflict by providing a way to
1764 * terminate the ContentProvider. This method can also prevent memory leaks
1765 * from multiple instantiations of the ContentProvider, and it can ensure
1766 * unit test isolation by allowing you to completely clean up the test
1767 * fixture before moving on to the next test.
1768 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001769 */
1770 public void shutdown() {
1771 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1772 "connections are gracefully shutdown");
1773 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001774
1775 /**
1776 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001777 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001778 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001779 * @param fd The raw file descriptor that the dump is being sent to.
1780 * @param writer The PrintWriter to which you should dump your state. This will be
1781 * closed for you after you return.
1782 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001783 */
1784 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1785 writer.println("nothing to dump");
1786 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001787
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001788 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001789 private void validateIncomingUri(Uri uri) throws SecurityException {
1790 String auth = uri.getAuthority();
1791 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001792 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
1793 throw new SecurityException("trying to query a ContentProvider in user "
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001794 + mContext.getUserId() + " with a uri belonging to user " + userId);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001795 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001796 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
1797 String message = "The authority of the uri " + uri + " does not match the one of the "
1798 + "contentProvider: ";
1799 if (mAuthority != null) {
1800 message += mAuthority;
1801 } else {
1802 message += mAuthorities;
1803 }
1804 throw new SecurityException(message);
1805 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001806 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001807
1808 /** @hide */
1809 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1810 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001811 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001812 if (end == -1) return defaultUserId;
1813 String userIdString = auth.substring(0, end);
1814 try {
1815 return Integer.parseInt(userIdString);
1816 } catch (NumberFormatException e) {
1817 Log.w(TAG, "Error parsing userId.", e);
1818 return UserHandle.USER_NULL;
1819 }
1820 }
1821
1822 /** @hide */
1823 public static int getUserIdFromAuthority(String auth) {
1824 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1825 }
1826
1827 /** @hide */
1828 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1829 if (uri == null) return defaultUserId;
1830 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1831 }
1832
1833 /** @hide */
1834 public static int getUserIdFromUri(Uri uri) {
1835 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1836 }
1837
1838 /**
1839 * Removes userId part from authority string. Expects format:
1840 * userId@some.authority
1841 * If there is no userId in the authority, it symply returns the argument
1842 * @hide
1843 */
1844 public static String getAuthorityWithoutUserId(String auth) {
1845 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001846 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001847 return auth.substring(end+1);
1848 }
1849
1850 /** @hide */
1851 public static Uri getUriWithoutUserId(Uri uri) {
1852 if (uri == null) return null;
1853 Uri.Builder builder = uri.buildUpon();
1854 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1855 return builder.build();
1856 }
1857
1858 /** @hide */
1859 public static boolean uriHasUserId(Uri uri) {
1860 if (uri == null) return false;
1861 return !TextUtils.isEmpty(uri.getUserInfo());
1862 }
1863
1864 /** @hide */
1865 public static Uri maybeAddUserId(Uri uri, int userId) {
1866 if (uri == null) return null;
1867 if (userId != UserHandle.USER_CURRENT
1868 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1869 if (!uriHasUserId(uri)) {
1870 //We don't add the user Id if there's already one
1871 Uri.Builder builder = uri.buildUpon();
1872 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1873 return builder.build();
1874 }
1875 }
1876 return uri;
1877 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001878}