blob: 5b722e27f123765501f6f6482cc7145415f977c8 [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
Dianne Hackborn35654b62013-01-14 17:38:02 -080022import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070023import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.pm.ProviderInfo;
25import android.content.res.AssetFileDescriptor;
26import android.content.res.Configuration;
27import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.database.SQLException;
29import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070030import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080032import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070033import android.os.CancellationSignal;
34import android.os.ICancellationSignal;
35import android.os.OperationCanceledException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070037import android.os.Process;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070038import android.os.UserHandle;
Vasu Nori0c9e14a2010-08-04 13:31:48 -070039import android.util.Log;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010040import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041
42import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080043import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070045import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080046import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070047import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048
49/**
50 * Content providers are one of the primary building blocks of Android applications, providing
51 * content to applications. They encapsulate data and provide it to applications through the single
52 * {@link ContentResolver} interface. A content provider is only required if you need to share
53 * data between multiple applications. For example, the contacts data is used by multiple
54 * applications and must be stored in a content provider. If you don't need to share data amongst
55 * multiple applications you can use a database directly via
56 * {@link android.database.sqlite.SQLiteDatabase}.
57 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058 * <p>When a request is made via
59 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
60 * request to the content provider registered with the authority. The content provider can interpret
61 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
62 * URIs.</p>
63 *
64 * <p>The primary methods that need to be implemented are:
65 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070066 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 * <li>{@link #query} which returns data to the caller</li>
68 * <li>{@link #insert} which inserts new data into the content provider</li>
69 * <li>{@link #update} which updates existing data in the content provider</li>
70 * <li>{@link #delete} which deletes data from the content provider</li>
71 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
72 * </ul></p>
73 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070074 * <p class="caution">Data access methods (such as {@link #insert} and
75 * {@link #update}) may be called from many threads at once, and must be thread-safe.
76 * Other methods (such as {@link #onCreate}) are only called from the application
77 * main thread, and must avoid performing lengthy operations. See the method
78 * descriptions for their expected thread behavior.</p>
79 *
80 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
81 * ContentProvider instance, so subclasses don't have to worry about the details of
82 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070083 *
84 * <div class="special reference">
85 * <h3>Developer Guides</h3>
86 * <p>For more information about using content providers, read the
87 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
88 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -070090public abstract class ContentProvider implements ComponentCallbacks2 {
Vasu Nori0c9e14a2010-08-04 13:31:48 -070091 private static final String TAG = "ContentProvider";
92
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +090093 /*
94 * Note: if you add methods to ContentProvider, you must add similar methods to
95 * MockContentProvider.
96 */
97
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070099 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100100
101 // Since most Providers have only one authority, we keep both a String and a String[] to improve
102 // performance.
103 private String mAuthority;
104 private String[] mAuthorities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 private String mReadPermission;
106 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700107 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700108 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800109 private boolean mNoPerms;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700111 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<String>();
112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 private Transport mTransport = new Transport();
114
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700115 /**
116 * Construct a ContentProvider instance. Content providers must be
117 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
118 * in the manifest</a>, accessed with {@link ContentResolver}, and created
119 * automatically by the system, so applications usually do not create
120 * ContentProvider instances directly.
121 *
122 * <p>At construction time, the object is uninitialized, and most fields and
123 * methods are unavailable. Subclasses should initialize themselves in
124 * {@link #onCreate}, not the constructor.
125 *
126 * <p>Content providers are created on the application main thread at
127 * application launch time. The constructor must not perform lengthy
128 * operations, or application startup will be delayed.
129 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900130 public ContentProvider() {
131 }
132
133 /**
134 * Constructor just for mocking.
135 *
136 * @param context A Context object which should be some mock instance (like the
137 * instance of {@link android.test.mock.MockContext}).
138 * @param readPermission The read permision you want this instance should have in the
139 * test, which is available via {@link #getReadPermission()}.
140 * @param writePermission The write permission you want this instance should have
141 * in the test, which is available via {@link #getWritePermission()}.
142 * @param pathPermissions The PathPermissions you want this instance should have
143 * in the test, which is available via {@link #getPathPermissions()}.
144 * @hide
145 */
146 public ContentProvider(
147 Context context,
148 String readPermission,
149 String writePermission,
150 PathPermission[] pathPermissions) {
151 mContext = context;
152 mReadPermission = readPermission;
153 mWritePermission = writePermission;
154 mPathPermissions = pathPermissions;
155 }
156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 /**
158 * Given an IContentProvider, try to coerce it back to the real
159 * ContentProvider object if it is running in the local process. This can
160 * be used if you know you are running in the same process as a provider,
161 * and want to get direct access to its implementation details. Most
162 * clients should not nor have a reason to use it.
163 *
164 * @param abstractInterface The ContentProvider interface that is to be
165 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800166 * @return If the IContentProvider is non-{@code null} and local, returns its actual
167 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 * @hide
169 */
170 public static ContentProvider coerceToLocalContentProvider(
171 IContentProvider abstractInterface) {
172 if (abstractInterface instanceof Transport) {
173 return ((Transport)abstractInterface).getContentProvider();
174 }
175 return null;
176 }
177
178 /**
179 * Binder object that deals with remoting.
180 *
181 * @hide
182 */
183 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800184 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800185 int mReadOp = AppOpsManager.OP_NONE;
186 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 ContentProvider getContentProvider() {
189 return ContentProvider.this;
190 }
191
Jeff Brownd2183652011-10-09 12:39:53 -0700192 @Override
193 public String getProviderName() {
194 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 }
196
Jeff Brown75ea64f2012-01-25 19:37:13 -0800197 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800198 public Cursor query(String callingPkg, Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800199 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800200 ICancellationSignal cancellationSignal) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100201 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100202 uri = getUriWithoutUserId(uri);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800203 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800204 return rejectQuery(uri, projection, selection, selectionArgs, sortOrder,
205 CancellationSignal.fromTransport(cancellationSignal));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800206 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700207 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700208 try {
209 return ContentProvider.this.query(
210 uri, projection, selection, selectionArgs, sortOrder,
211 CancellationSignal.fromTransport(cancellationSignal));
212 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700213 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 }
216
Jeff Brown75ea64f2012-01-25 19:37:13 -0800217 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100219 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100220 uri = getUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 return ContentProvider.this.getType(uri);
222 }
223
Jeff Brown75ea64f2012-01-25 19:37:13 -0800224 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800225 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100226 validateIncomingUri(uri);
227 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100228 uri = getUriWithoutUserId(uri);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800229 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800230 return rejectInsert(uri, initialValues);
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 {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100234 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700235 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700236 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 }
239
Jeff Brown75ea64f2012-01-25 19:37:13 -0800240 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800241 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100242 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100243 uri = getUriWithoutUserId(uri);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800244 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
245 return 0;
246 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700247 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700248 try {
249 return ContentProvider.this.bulkInsert(uri, initialValues);
250 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700251 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 }
254
Jeff Brown75ea64f2012-01-25 19:37:13 -0800255 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800256 public ContentProviderResult[] applyBatch(String callingPkg,
257 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700258 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100259 int numOperations = operations.size();
260 final int[] userIds = new int[numOperations];
261 for (int i = 0; i < numOperations; i++) {
262 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100263 Uri uri = operation.getUri();
264 validateIncomingUri(uri);
265 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100266 if (userIds[i] != UserHandle.USER_CURRENT) {
267 // Removing the user id from the uri.
268 operation = new ContentProviderOperation(operation, true);
269 operations.set(i, operation);
270 }
Fred Quintana89437372009-05-15 15:10:40 -0700271 if (operation.isReadOperation()) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100272 if (enforceReadPermission(callingPkg, uri)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800273 != AppOpsManager.MODE_ALLOWED) {
274 throw new OperationApplicationException("App op not allowed", 0);
275 }
Fred Quintana89437372009-05-15 15:10:40 -0700276 }
Fred Quintana89437372009-05-15 15:10:40 -0700277 if (operation.isWriteOperation()) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100278 if (enforceWritePermission(callingPkg, uri)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800279 != AppOpsManager.MODE_ALLOWED) {
280 throw new OperationApplicationException("App op not allowed", 0);
281 }
Fred Quintana89437372009-05-15 15:10:40 -0700282 }
283 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700284 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700285 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100286 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
287 for (int i = 0; i < results.length ; i++) {
288 if (userIds[i] != UserHandle.USER_CURRENT) {
289 // Adding the userId to the uri.
290 results[i] = new ContentProviderResult(results[i], userIds[i]);
291 }
292 }
293 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700294 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700295 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700296 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700297 }
298
Jeff Brown75ea64f2012-01-25 19:37:13 -0800299 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800300 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100301 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100302 uri = getUriWithoutUserId(uri);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800303 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
304 return 0;
305 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700306 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700307 try {
308 return ContentProvider.this.delete(uri, selection, selectionArgs);
309 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700310 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 }
313
Jeff Brown75ea64f2012-01-25 19:37:13 -0800314 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800315 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100317 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100318 uri = getUriWithoutUserId(uri);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800319 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
320 return 0;
321 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700322 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700323 try {
324 return ContentProvider.this.update(uri, values, selection, selectionArgs);
325 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700326 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 }
329
Jeff Brown75ea64f2012-01-25 19:37:13 -0800330 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700331 public ParcelFileDescriptor openFile(
332 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100334 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100335 uri = getUriWithoutUserId(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100336 enforceFilePermission(callingPkg, uri, mode);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700337 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700338 try {
339 return ContentProvider.this.openFile(
340 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
341 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700342 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 }
345
Jeff Brown75ea64f2012-01-25 19:37:13 -0800346 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700347 public AssetFileDescriptor openAssetFile(
348 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100350 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100351 uri = getUriWithoutUserId(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100352 enforceFilePermission(callingPkg, uri, mode);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700353 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700354 try {
355 return ContentProvider.this.openAssetFile(
356 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
357 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700358 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 }
361
Jeff Brown75ea64f2012-01-25 19:37:13 -0800362 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800363 public Bundle call(String callingPkg, String method, String arg, Bundle extras) {
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.call(method, arg, extras);
367 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700368 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700369 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800370 }
371
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700372 @Override
373 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100374 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100375 uri = getUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700376 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
377 }
378
379 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800380 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700381 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100382 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100383 uri = getUriWithoutUserId(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100384 enforceFilePermission(callingPkg, uri, "r");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700385 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700386 try {
387 return ContentProvider.this.openTypedAssetFile(
388 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
389 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700390 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700391 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700392 }
393
Jeff Brown75ea64f2012-01-25 19:37:13 -0800394 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700395 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800396 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800397 }
398
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700399 @Override
400 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100401 validateIncomingUri(uri);
402 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100403 uri = getUriWithoutUserId(uri);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700404 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
405 return null;
406 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700407 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700408 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100409 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700410 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700411 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700412 }
413 }
414
415 @Override
416 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100417 validateIncomingUri(uri);
418 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100419 uri = getUriWithoutUserId(uri);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700420 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
421 return null;
422 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700423 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700424 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100425 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700426 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700427 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700428 }
429 }
430
Dianne Hackborn35654b62013-01-14 17:38:02 -0800431 private void enforceFilePermission(String callingPkg, Uri uri, String mode)
432 throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800433 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800434 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
435 throw new FileNotFoundException("App op not allowed");
436 }
437 } else {
438 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
439 throw new FileNotFoundException("App op not allowed");
440 }
441 }
442 }
443
444 private int enforceReadPermission(String callingPkg, Uri uri) throws SecurityException {
445 enforceReadPermissionInner(uri);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800446 if (mReadOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800447 return mAppOpsManager.noteOp(mReadOp, Binder.getCallingUid(), callingPkg);
448 }
449 return AppOpsManager.MODE_ALLOWED;
450 }
451
Dianne Hackborn35654b62013-01-14 17:38:02 -0800452 private int enforceWritePermission(String callingPkg, Uri uri) throws SecurityException {
453 enforceWritePermissionInner(uri);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800454 if (mWriteOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800455 return mAppOpsManager.noteOp(mWriteOp, Binder.getCallingUid(), callingPkg);
456 }
457 return AppOpsManager.MODE_ALLOWED;
458 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700459 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800460
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100461 boolean checkUser(int pid, int uid, Context context) {
462 return UserHandle.getUserId(uid) == context.getUserId()
463 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
464 == PERMISSION_GRANTED;
465 }
466
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700467 /** {@hide} */
468 protected void enforceReadPermissionInner(Uri uri) throws SecurityException {
469 final Context context = getContext();
470 final int pid = Binder.getCallingPid();
471 final int uid = Binder.getCallingUid();
472 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700473
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700474 if (UserHandle.isSameApp(uid, mMyUid)) {
475 return;
476 }
477
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100478 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700479 final String componentPerm = getReadPermission();
480 if (componentPerm != null) {
481 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
482 return;
483 } else {
484 missingPerm = componentPerm;
485 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700486 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700487
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700488 // track if unprotected read is allowed; any denied
489 // <path-permission> below removes this ability
490 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700491
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700492 final PathPermission[] pps = getPathPermissions();
493 if (pps != null) {
494 final String path = uri.getPath();
495 for (PathPermission pp : pps) {
496 final String pathPerm = pp.getReadPermission();
497 if (pathPerm != null && pp.match(path)) {
498 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
499 return;
500 } else {
501 // any denied <path-permission> means we lose
502 // default <provider> access.
503 allowDefaultRead = false;
504 missingPerm = pathPerm;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700505 }
506 }
507 }
508 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700509
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700510 // if we passed <path-permission> checks above, and no default
511 // <provider> permission, then allow access.
512 if (allowDefaultRead) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700514
515 // last chance, check against any uri grants
516 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION)
517 == PERMISSION_GRANTED) {
518 return;
519 }
520
521 final String failReason = mExported
522 ? " requires " + missingPerm + ", or grantUriPermission()"
523 : " requires the provider be exported, or grantUriPermission()";
524 throw new SecurityException("Permission Denial: reading "
525 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
526 + ", uid=" + uid + failReason);
527 }
528
529 /** {@hide} */
530 protected void enforceWritePermissionInner(Uri uri) throws SecurityException {
531 final Context context = getContext();
532 final int pid = Binder.getCallingPid();
533 final int uid = Binder.getCallingUid();
534 String missingPerm = null;
535
536 if (UserHandle.isSameApp(uid, mMyUid)) {
537 return;
538 }
539
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100540 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700541 final String componentPerm = getWritePermission();
542 if (componentPerm != null) {
543 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
544 return;
545 } else {
546 missingPerm = componentPerm;
547 }
548 }
549
550 // track if unprotected write is allowed; any denied
551 // <path-permission> below removes this ability
552 boolean allowDefaultWrite = (componentPerm == null);
553
554 final PathPermission[] pps = getPathPermissions();
555 if (pps != null) {
556 final String path = uri.getPath();
557 for (PathPermission pp : pps) {
558 final String pathPerm = pp.getWritePermission();
559 if (pathPerm != null && pp.match(path)) {
560 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
561 return;
562 } else {
563 // any denied <path-permission> means we lose
564 // default <provider> access.
565 allowDefaultWrite = false;
566 missingPerm = pathPerm;
567 }
568 }
569 }
570 }
571
572 // if we passed <path-permission> checks above, and no default
573 // <provider> permission, then allow access.
574 if (allowDefaultWrite) return;
575 }
576
577 // last chance, check against any uri grants
578 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
579 == PERMISSION_GRANTED) {
580 return;
581 }
582
583 final String failReason = mExported
584 ? " requires " + missingPerm + ", or grantUriPermission()"
585 : " requires the provider be exported, or grantUriPermission()";
586 throw new SecurityException("Permission Denial: writing "
587 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
588 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 }
590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700592 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800593 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 * constructor.
595 */
596 public final Context getContext() {
597 return mContext;
598 }
599
600 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700601 * Set the calling package, returning the current value (or {@code null})
602 * which can be used later to restore the previous state.
603 */
604 private String setCallingPackage(String callingPackage) {
605 final String original = mCallingPackage.get();
606 mCallingPackage.set(callingPackage);
607 return original;
608 }
609
610 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700611 * Return the package name of the caller that initiated the request being
612 * processed on the current thread. The returned package will have been
613 * verified to belong to the calling UID. Returns {@code null} if not
614 * currently processing a request.
615 * <p>
616 * This will always return {@code null} when processing
617 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
618 *
619 * @see Binder#getCallingUid()
620 * @see Context#grantUriPermission(String, Uri, int)
621 * @throws SecurityException if the calling package doesn't belong to the
622 * calling UID.
623 */
624 public final String getCallingPackage() {
625 final String pkg = mCallingPackage.get();
626 if (pkg != null) {
627 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
628 }
629 return pkg;
630 }
631
632 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100633 * Change the authorities of the ContentProvider.
634 * This is normally set for you from its manifest information when the provider is first
635 * created.
636 * @hide
637 * @param authorities the semi-colon separated authorities of the ContentProvider.
638 */
639 protected final void setAuthorities(String authorities) {
640 if (authorities.indexOf(';') == -1) {
641 mAuthority = authorities;
642 mAuthorities = null;
643 } else {
644 mAuthority = null;
645 mAuthorities = authorities.split(";");
646 }
647 }
648
649 /** @hide */
650 protected final boolean matchesOurAuthorities(String authority) {
651 if (mAuthority != null) {
652 return mAuthority.equals(authority);
653 }
654 int length = mAuthorities.length;
655 for (int i = 0; i < length; i++) {
656 if (mAuthorities[i].equals(authority)) return true;
657 }
658 return false;
659 }
660
661
662 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 * Change the permission required to read data from the content
664 * provider. This is normally set for you from its manifest information
665 * when the provider is first created.
666 *
667 * @param permission Name of the permission required for read-only access.
668 */
669 protected final void setReadPermission(String permission) {
670 mReadPermission = permission;
671 }
672
673 /**
674 * Return the name of the permission required for read-only access to
675 * this content provider. This method can be called from multiple
676 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800677 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
678 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 */
680 public final String getReadPermission() {
681 return mReadPermission;
682 }
683
684 /**
685 * Change the permission required to read and write data in the content
686 * provider. This is normally set for you from its manifest information
687 * when the provider is first created.
688 *
689 * @param permission Name of the permission required for read/write access.
690 */
691 protected final void setWritePermission(String permission) {
692 mWritePermission = permission;
693 }
694
695 /**
696 * Return the name of the permission required for read/write access to
697 * this content provider. This method can be called from multiple
698 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800699 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
700 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 */
702 public final String getWritePermission() {
703 return mWritePermission;
704 }
705
706 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700707 * Change the path-based permission required to read and/or write data in
708 * the content provider. This is normally set for you from its manifest
709 * information when the provider is first created.
710 *
711 * @param permissions Array of path permission descriptions.
712 */
713 protected final void setPathPermissions(PathPermission[] permissions) {
714 mPathPermissions = permissions;
715 }
716
717 /**
718 * Return the path-based permissions required for read and/or write access to
719 * this content provider. This method can be called from multiple
720 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800721 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
722 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700723 */
724 public final PathPermission[] getPathPermissions() {
725 return mPathPermissions;
726 }
727
Dianne Hackborn35654b62013-01-14 17:38:02 -0800728 /** @hide */
729 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800730 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800731 mTransport.mReadOp = readOp;
732 mTransport.mWriteOp = writeOp;
733 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800734 }
735
Dianne Hackborn961321f2013-02-05 17:22:41 -0800736 /** @hide */
737 public AppOpsManager getAppOpsManager() {
738 return mTransport.mAppOpsManager;
739 }
740
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700741 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700742 * Implement this to initialize your content provider on startup.
743 * This method is called for all registered content providers on the
744 * application main thread at application launch time. It must not perform
745 * lengthy operations, or application startup will be delayed.
746 *
747 * <p>You should defer nontrivial initialization (such as opening,
748 * upgrading, and scanning databases) until the content provider is used
749 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
750 * keeps application startup fast, avoids unnecessary work if the provider
751 * turns out not to be needed, and stops database errors (such as a full
752 * disk) from halting application launch.
753 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700754 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700755 * is a helpful utility class that makes it easy to manage databases,
756 * and will automatically defer opening until first use. If you do use
757 * SQLiteOpenHelper, make sure to avoid calling
758 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
759 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
760 * from this method. (Instead, override
761 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
762 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 *
764 * @return true if the provider was successfully loaded, false otherwise
765 */
766 public abstract boolean onCreate();
767
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700768 /**
769 * {@inheritDoc}
770 * This method is always called on the application main thread, and must
771 * not perform lengthy operations.
772 *
773 * <p>The default content provider implementation does nothing.
774 * Override this method to take appropriate action.
775 * (Content providers do not usually care about things like screen
776 * orientation, but may want to know about locale changes.)
777 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 public void onConfigurationChanged(Configuration newConfig) {
779 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700780
781 /**
782 * {@inheritDoc}
783 * This method is always called on the application main thread, and must
784 * not perform lengthy operations.
785 *
786 * <p>The default content provider implementation does nothing.
787 * Subclasses may override this method to take appropriate action.
788 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 public void onLowMemory() {
790 }
791
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700792 public void onTrimMemory(int level) {
793 }
794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800796 * @hide
797 * Implementation when a caller has performed a query on the content
798 * provider, but that call has been rejected for the operation given
799 * to {@link #setAppOps(int, int)}. The default implementation
800 * rewrites the <var>selection</var> argument to include a condition
801 * that is never true (so will always result in an empty cursor)
802 * and calls through to {@link #query(android.net.Uri, String[], String, String[],
803 * String, android.os.CancellationSignal)} with that.
804 */
805 public Cursor rejectQuery(Uri uri, String[] projection,
806 String selection, String[] selectionArgs, String sortOrder,
807 CancellationSignal cancellationSignal) {
808 // The read is not allowed... to fake it out, we replace the given
809 // selection statement with a dummy one that will always be false.
810 // This way we will get a cursor back that has the correct structure
811 // but contains no rows.
Dianne Hackborn9fa39bd2013-03-22 18:42:14 -0700812 if (selection == null || selection.isEmpty()) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800813 selection = "'A' = 'B'";
814 } else {
815 selection = "'A' = 'B' AND (" + selection + ")";
816 }
817 return query(uri, projection, selection, selectionArgs, sortOrder, cancellationSignal);
818 }
819
820 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700821 * Implement this to handle query requests from clients.
822 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800823 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
824 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 * <p>
826 * Example client call:<p>
827 * <pre>// Request a specific record.
828 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000829 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 projection, // Which columns to return.
831 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000832 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 People.NAME + " ASC"); // Sort order.</pre>
834 * Example implementation:<p>
835 * <pre>// SQLiteQueryBuilder is a helper class that creates the
836 // proper SQL syntax for us.
837 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
838
839 // Set the table we're querying.
840 qBuilder.setTables(DATABASE_TABLE_NAME);
841
842 // If the query ends in a specific record number, we're
843 // being asked for a specific record, so set the
844 // WHERE clause in our query.
845 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
846 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
847 }
848
849 // Make the query.
850 Cursor c = qBuilder.query(mDb,
851 projection,
852 selection,
853 selectionArgs,
854 groupBy,
855 having,
856 sortOrder);
857 c.setNotificationUri(getContext().getContentResolver(), uri);
858 return c;</pre>
859 *
860 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000861 * if the client is requesting a specific record, the URI will end in a record number
862 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
863 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800865 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800867 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000868 * @param selectionArgs You may include ?s in selection, which will be replaced by
869 * the values from selectionArgs, in order that they appear in the selection.
870 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800872 * If {@code null} then the provider is free to define the sort order.
873 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 */
875 public abstract Cursor query(Uri uri, String[] projection,
876 String selection, String[] selectionArgs, String sortOrder);
877
Fred Quintana5bba6322009-10-05 14:21:12 -0700878 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800879 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800880 * This method can be called from multiple threads, as described in
881 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
882 * and Threads</a>.
883 * <p>
884 * Example client call:<p>
885 * <pre>// Request a specific record.
886 * Cursor managedCursor = managedQuery(
887 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
888 projection, // Which columns to return.
889 null, // WHERE clause.
890 null, // WHERE clause value substitution
891 People.NAME + " ASC"); // Sort order.</pre>
892 * Example implementation:<p>
893 * <pre>// SQLiteQueryBuilder is a helper class that creates the
894 // proper SQL syntax for us.
895 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
896
897 // Set the table we're querying.
898 qBuilder.setTables(DATABASE_TABLE_NAME);
899
900 // If the query ends in a specific record number, we're
901 // being asked for a specific record, so set the
902 // WHERE clause in our query.
903 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
904 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
905 }
906
907 // Make the query.
908 Cursor c = qBuilder.query(mDb,
909 projection,
910 selection,
911 selectionArgs,
912 groupBy,
913 having,
914 sortOrder);
915 c.setNotificationUri(getContext().getContentResolver(), uri);
916 return c;</pre>
917 * <p>
918 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800919 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
920 * signal to ensure correct operation on older versions of the Android Framework in
921 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800922 *
923 * @param uri The URI to query. This will be the full URI sent by the client;
924 * if the client is requesting a specific record, the URI will end in a record number
925 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
926 * that _id value.
927 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800928 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800929 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800930 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800931 * @param selectionArgs You may include ?s in selection, which will be replaced by
932 * the values from selectionArgs, in order that they appear in the selection.
933 * The values will be bound as Strings.
934 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800935 * If {@code null} then the provider is free to define the sort order.
936 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800937 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
938 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800939 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800940 */
941 public Cursor query(Uri uri, String[] projection,
942 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800943 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800944 return query(uri, projection, selection, selectionArgs, sortOrder);
945 }
946
947 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700948 * Implement this to handle requests for the MIME type of the data at the
949 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 * <code>vnd.android.cursor.item</code> for a single record,
951 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700952 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800953 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
954 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700956 * <p>Note that there are no permissions needed for an application to
957 * access this information; if your content provider requires read and/or
958 * write permissions, or is not exported, all applications can still call
959 * this method regardless of their access permissions. This allows them
960 * to retrieve the MIME type for a URI when dispatching intents.
961 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800963 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 */
965 public abstract String getType(Uri uri);
966
967 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700968 * Implement this to support canonicalization of URIs that refer to your
969 * content provider. A canonical URI is one that can be transported across
970 * devices, backup/restore, and other contexts, and still be able to refer
971 * to the same data item. Typically this is implemented by adding query
972 * params to the URI allowing the content provider to verify that an incoming
973 * canonical URI references the same data as it was originally intended for and,
974 * if it doesn't, to find that data (if it exists) in the current environment.
975 *
976 * <p>For example, if the content provider holds people and a normal URI in it
977 * is created with a row index into that people database, the cananical representation
978 * may have an additional query param at the end which specifies the name of the
979 * person it is intended for. Later calls into the provider with that URI will look
980 * up the row of that URI's base index and, if it doesn't match or its entry's
981 * name doesn't match the name in the query param, perform a query on its database
982 * to find the correct row to operate on.</p>
983 *
984 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
985 * URIs (including this one) must perform this verification and recovery of any
986 * canonical URIs they receive. In addition, you must also implement
987 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
988 *
989 * <p>The default implementation of this method returns null, indicating that
990 * canonical URIs are not supported.</p>
991 *
992 * @param url The Uri to canonicalize.
993 *
994 * @return Return the canonical representation of <var>url</var>, or null if
995 * canonicalization of that Uri is not supported.
996 */
997 public Uri canonicalize(Uri url) {
998 return null;
999 }
1000
1001 /**
1002 * Remove canonicalization from canonical URIs previously returned by
1003 * {@link #canonicalize}. For example, if your implementation is to add
1004 * a query param to canonicalize a URI, this method can simply trip any
1005 * query params on the URI. The default implementation always returns the
1006 * same <var>url</var> that was passed in.
1007 *
1008 * @param url The Uri to remove any canonicalization from.
1009 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001010 * @return Return the non-canonical representation of <var>url</var>, return
1011 * the <var>url</var> as-is if there is nothing to do, or return null if
1012 * the data identified by the canonical representation can not be found in
1013 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001014 */
1015 public Uri uncanonicalize(Uri url) {
1016 return url;
1017 }
1018
1019 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001020 * @hide
1021 * Implementation when a caller has performed an insert on the content
1022 * provider, but that call has been rejected for the operation given
1023 * to {@link #setAppOps(int, int)}. The default implementation simply
1024 * returns a dummy URI that is the base URI with a 0 path element
1025 * appended.
1026 */
1027 public Uri rejectInsert(Uri uri, ContentValues values) {
1028 // If not allowed, we need to return some reasonable URI. Maybe the
1029 // content provider should be responsible for this, but for now we
1030 // will just return the base URI with a dummy '0' tagged on to it.
1031 // You shouldn't be able to read if you can't write, anyway, so it
1032 // shouldn't matter much what is returned.
1033 return uri.buildUpon().appendPath("0").build();
1034 }
1035
1036 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001037 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1039 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001040 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001041 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1042 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001043 * @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 -08001044 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001045 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 * @return The URI for the newly inserted item.
1047 */
1048 public abstract Uri insert(Uri uri, ContentValues values);
1049
1050 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001051 * Override this to handle requests to insert a set of new rows, or the
1052 * default implementation will iterate over the values and call
1053 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1055 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001056 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001057 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1058 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 *
1060 * @param uri The content:// URI of the insertion request.
1061 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001062 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 * @return The number of values that were inserted.
1064 */
1065 public int bulkInsert(Uri uri, ContentValues[] values) {
1066 int numValues = values.length;
1067 for (int i = 0; i < numValues; i++) {
1068 insert(uri, values[i]);
1069 }
1070 return numValues;
1071 }
1072
1073 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001074 * Implement this to handle requests to delete one or more rows.
1075 * The implementation should apply the selection clause when performing
1076 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001077 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001079 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001080 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1081 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 *
1083 * <p>The implementation is responsible for parsing out a row ID at the end
1084 * of the URI, if a specific row is being deleted. That is, the client would
1085 * pass in <code>content://contacts/people/22</code> and the implementation is
1086 * responsible for parsing the record number (22) when creating a SQL statement.
1087 *
1088 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1089 * @param selection An optional restriction to apply to rows when deleting.
1090 * @return The number of rows affected.
1091 * @throws SQLException
1092 */
1093 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
1094
1095 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001096 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001097 * The implementation should update all rows matching the selection
1098 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1100 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001101 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001102 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1103 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 *
1105 * @param uri The URI to query. This can potentially have a record ID if this
1106 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001107 * @param values A set of column_name/value pairs to update in the database.
1108 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 * @param selection An optional filter to match rows to update.
1110 * @return the number of rows affected.
1111 */
1112 public abstract int update(Uri uri, ContentValues values, String selection,
1113 String[] selectionArgs);
1114
1115 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001116 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001117 * The default implementation always throws {@link FileNotFoundException}.
1118 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001119 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1120 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001121 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001122 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1123 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001124 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 *
1126 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1127 * their responsibility to close it when done. That is, the implementation
1128 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001129 * <p>
1130 * If opened with the exclusive "r" or "w" modes, the returned
1131 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1132 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1133 * supports seeking.
1134 * <p>
1135 * If you need to detect when the returned ParcelFileDescriptor has been
1136 * closed, or if the remote process has crashed or encountered some other
1137 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1138 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1139 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1140 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001142 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1143 * to return the appropriate MIME type for the data returned here with
1144 * the same URI. This will allow intent resolution to automatically determine the data MIME
1145 * type and select the appropriate matching targets as part of its operation.</p>
1146 *
1147 * <p class="note">For better interoperability with other applications, it is recommended
1148 * that for any URIs that can be opened, you also support queries on them
1149 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1150 * You may also want to support other common columns if you have additional meta-data
1151 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1152 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1153 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 * @param uri The URI whose file is to be opened.
1155 * @param mode Access mode for the file. May be "r" for read-only access,
1156 * "rw" for read and write access, or "rwt" for read and write access
1157 * that truncates any existing file.
1158 *
1159 * @return Returns a new ParcelFileDescriptor which you can use to access
1160 * the file.
1161 *
1162 * @throws FileNotFoundException Throws FileNotFoundException if there is
1163 * no file associated with the given URI or the mode is invalid.
1164 * @throws SecurityException Throws SecurityException if the caller does
1165 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001166 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 * @see #openAssetFile(Uri, String)
1168 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001169 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001170 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001171 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 public ParcelFileDescriptor openFile(Uri uri, String mode)
1173 throws FileNotFoundException {
1174 throw new FileNotFoundException("No files supported by provider at "
1175 + uri);
1176 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001179 * Override this to handle requests to open a file blob.
1180 * The default implementation always throws {@link FileNotFoundException}.
1181 * This method can be called from multiple threads, as described in
1182 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1183 * and Threads</a>.
1184 *
1185 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1186 * to the caller. This way large data (such as images and documents) can be
1187 * returned without copying the content.
1188 *
1189 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1190 * their responsibility to close it when done. That is, the implementation
1191 * of this method should create a new ParcelFileDescriptor for each call.
1192 * <p>
1193 * If opened with the exclusive "r" or "w" modes, the returned
1194 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1195 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1196 * supports seeking.
1197 * <p>
1198 * If you need to detect when the returned ParcelFileDescriptor has been
1199 * closed, or if the remote process has crashed or encountered some other
1200 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1201 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1202 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1203 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1204 *
1205 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1206 * to return the appropriate MIME type for the data returned here with
1207 * the same URI. This will allow intent resolution to automatically determine the data MIME
1208 * type and select the appropriate matching targets as part of its operation.</p>
1209 *
1210 * <p class="note">For better interoperability with other applications, it is recommended
1211 * that for any URIs that can be opened, you also support queries on them
1212 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1213 * You may also want to support other common columns if you have additional meta-data
1214 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1215 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1216 *
1217 * @param uri The URI whose file is to be opened.
1218 * @param mode Access mode for the file. May be "r" for read-only access,
1219 * "w" for write-only access, "rw" for read and write access, or
1220 * "rwt" for read and write access that truncates any existing
1221 * file.
1222 * @param signal A signal to cancel the operation in progress, or
1223 * {@code null} if none. For example, if you are downloading a
1224 * file from the network to service a "rw" mode request, you
1225 * should periodically call
1226 * {@link CancellationSignal#throwIfCanceled()} to check whether
1227 * the client has canceled the request and abort the download.
1228 *
1229 * @return Returns a new ParcelFileDescriptor which you can use to access
1230 * the file.
1231 *
1232 * @throws FileNotFoundException Throws FileNotFoundException if there is
1233 * no file associated with the given URI or the mode is invalid.
1234 * @throws SecurityException Throws SecurityException if the caller does
1235 * not have permission to access the file.
1236 *
1237 * @see #openAssetFile(Uri, String)
1238 * @see #openFileHelper(Uri, String)
1239 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001240 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001241 */
1242 public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
1243 throws FileNotFoundException {
1244 return openFile(uri, mode);
1245 }
1246
1247 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 * This is like {@link #openFile}, but can be implemented by providers
1249 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001250 * inside of their .apk.
1251 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001252 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1253 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001254 *
1255 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001256 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001257 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1259 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1260 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001261 * <p>
1262 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1263 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001264 *
1265 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 * should create the AssetFileDescriptor with
1267 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001268 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001270 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1271 * to return the appropriate MIME type for the data returned here with
1272 * the same URI. This will allow intent resolution to automatically determine the data MIME
1273 * type and select the appropriate matching targets as part of its operation.</p>
1274 *
1275 * <p class="note">For better interoperability with other applications, it is recommended
1276 * that for any URIs that can be opened, you also support queries on them
1277 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1278 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 * @param uri The URI whose file is to be opened.
1280 * @param mode Access mode for the file. May be "r" for read-only access,
1281 * "w" for write-only access (erasing whatever data is currently in
1282 * the file), "wa" for write-only access to append to any existing data,
1283 * "rw" for read and write access on any existing data, and "rwt" for read
1284 * and write access that truncates any existing file.
1285 *
1286 * @return Returns a new AssetFileDescriptor which you can use to access
1287 * the file.
1288 *
1289 * @throws FileNotFoundException Throws FileNotFoundException if there is
1290 * no file associated with the given URI or the mode is invalid.
1291 * @throws SecurityException Throws SecurityException if the caller does
1292 * not have permission to access the file.
1293 *
1294 * @see #openFile(Uri, String)
1295 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001296 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 */
1298 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
1299 throws FileNotFoundException {
1300 ParcelFileDescriptor fd = openFile(uri, mode);
1301 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1302 }
1303
1304 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001305 * This is like {@link #openFile}, but can be implemented by providers
1306 * that need to be able to return sub-sections of files, often assets
1307 * inside of their .apk.
1308 * This method can be called from multiple threads, as described in
1309 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1310 * and Threads</a>.
1311 *
1312 * <p>If you implement this, your clients must be able to deal with such
1313 * file slices, either directly with
1314 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1315 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1316 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1317 * methods.
1318 * <p>
1319 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1320 * streaming of data.
1321 *
1322 * <p class="note">If you are implementing this to return a full file, you
1323 * should create the AssetFileDescriptor with
1324 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1325 * applications that cannot handle sub-sections of files.</p>
1326 *
1327 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1328 * to return the appropriate MIME type for the data returned here with
1329 * the same URI. This will allow intent resolution to automatically determine the data MIME
1330 * type and select the appropriate matching targets as part of its operation.</p>
1331 *
1332 * <p class="note">For better interoperability with other applications, it is recommended
1333 * that for any URIs that can be opened, you also support queries on them
1334 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1335 *
1336 * @param uri The URI whose file is to be opened.
1337 * @param mode Access mode for the file. May be "r" for read-only access,
1338 * "w" for write-only access (erasing whatever data is currently in
1339 * the file), "wa" for write-only access to append to any existing data,
1340 * "rw" for read and write access on any existing data, and "rwt" for read
1341 * and write access that truncates any existing file.
1342 * @param signal A signal to cancel the operation in progress, or
1343 * {@code null} if none. For example, if you are downloading a
1344 * file from the network to service a "rw" mode request, you
1345 * should periodically call
1346 * {@link CancellationSignal#throwIfCanceled()} to check whether
1347 * the client has canceled the request and abort the download.
1348 *
1349 * @return Returns a new AssetFileDescriptor which you can use to access
1350 * the file.
1351 *
1352 * @throws FileNotFoundException Throws FileNotFoundException if there is
1353 * no file associated with the given URI or the mode is invalid.
1354 * @throws SecurityException Throws SecurityException if the caller does
1355 * not have permission to access the file.
1356 *
1357 * @see #openFile(Uri, String)
1358 * @see #openFileHelper(Uri, String)
1359 * @see #getType(android.net.Uri)
1360 */
1361 public AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)
1362 throws FileNotFoundException {
1363 return openAssetFile(uri, mode);
1364 }
1365
1366 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 * Convenience for subclasses that wish to implement {@link #openFile}
1368 * by looking up a column named "_data" at the given URI.
1369 *
1370 * @param uri The URI to be opened.
1371 * @param mode The file mode. May be "r" for read-only access,
1372 * "w" for write-only access (erasing whatever data is currently in
1373 * the file), "wa" for write-only access to append to any existing data,
1374 * "rw" for read and write access on any existing data, and "rwt" for read
1375 * and write access that truncates any existing file.
1376 *
1377 * @return Returns a new ParcelFileDescriptor that can be used by the
1378 * client to access the file.
1379 */
1380 protected final ParcelFileDescriptor openFileHelper(Uri uri,
1381 String mode) throws FileNotFoundException {
1382 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1383 int count = (c != null) ? c.getCount() : 0;
1384 if (count != 1) {
1385 // If there is not exactly one result, throw an appropriate
1386 // exception.
1387 if (c != null) {
1388 c.close();
1389 }
1390 if (count == 0) {
1391 throw new FileNotFoundException("No entry for " + uri);
1392 }
1393 throw new FileNotFoundException("Multiple items at " + uri);
1394 }
1395
1396 c.moveToFirst();
1397 int i = c.getColumnIndex("_data");
1398 String path = (i >= 0 ? c.getString(i) : null);
1399 c.close();
1400 if (path == null) {
1401 throw new FileNotFoundException("Column _data not found.");
1402 }
1403
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001404 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 return ParcelFileDescriptor.open(new File(path), modeBits);
1406 }
1407
1408 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001409 * Called by a client to determine the types of data streams that this
1410 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001411 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001412 * of a particular type, return that MIME type if it matches the given
1413 * mimeTypeFilter. If it can perform type conversions, return an array
1414 * of all supported MIME types that match mimeTypeFilter.
1415 *
1416 * @param uri The data in the content provider being queried.
1417 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001418 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001419 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001420 * given mimeTypeFilter. Otherwise returns an array of all available
1421 * concrete MIME types.
1422 *
1423 * @see #getType(Uri)
1424 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001425 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001426 */
1427 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
1428 return null;
1429 }
1430
1431 /**
1432 * Called by a client to open a read-only stream containing data of a
1433 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1434 * except the file can only be read-only and the content provider may
1435 * perform data conversions to generate data of the desired type.
1436 *
1437 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001438 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001439 * {@link #openAssetFile(Uri, String)}.
1440 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001441 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001442 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001443 * <p>
1444 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1445 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001446 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001447 * <p class="note">For better interoperability with other applications, it is recommended
1448 * that for any URIs that can be opened, you also support queries on them
1449 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1450 * You may also want to support other common columns if you have additional meta-data
1451 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1452 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1453 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001454 * @param uri The data in the content provider being queried.
1455 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001456 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001457 * requirements; in this case the content provider will pick its best
1458 * type matching the pattern.
1459 * @param opts Additional options from the client. The definitions of
1460 * these are specific to the content provider being called.
1461 *
1462 * @return Returns a new AssetFileDescriptor from which the client can
1463 * read data of the desired type.
1464 *
1465 * @throws FileNotFoundException Throws FileNotFoundException if there is
1466 * no file associated with the given URI or the mode is invalid.
1467 * @throws SecurityException Throws SecurityException if the caller does
1468 * not have permission to access the data.
1469 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1470 * content provider does not support the requested MIME type.
1471 *
1472 * @see #getStreamTypes(Uri, String)
1473 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001474 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001475 */
1476 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
1477 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001478 if ("*/*".equals(mimeTypeFilter)) {
1479 // If they can take anything, the untyped open call is good enough.
1480 return openAssetFile(uri, "r");
1481 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001482 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001483 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001484 // Use old untyped open call if this provider has a type for this
1485 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001486 return openAssetFile(uri, "r");
1487 }
1488 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1489 }
1490
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001491
1492 /**
1493 * Called by a client to open a read-only stream containing data of a
1494 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1495 * except the file can only be read-only and the content provider may
1496 * perform data conversions to generate data of the desired type.
1497 *
1498 * <p>The default implementation compares the given mimeType against the
1499 * result of {@link #getType(Uri)} and, if they match, simply calls
1500 * {@link #openAssetFile(Uri, String)}.
1501 *
1502 * <p>See {@link ClipData} for examples of the use and implementation
1503 * of this method.
1504 * <p>
1505 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1506 * streaming of data.
1507 *
1508 * <p class="note">For better interoperability with other applications, it is recommended
1509 * that for any URIs that can be opened, you also support queries on them
1510 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1511 * You may also want to support other common columns if you have additional meta-data
1512 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1513 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1514 *
1515 * @param uri The data in the content provider being queried.
1516 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001517 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001518 * requirements; in this case the content provider will pick its best
1519 * type matching the pattern.
1520 * @param opts Additional options from the client. The definitions of
1521 * these are specific to the content provider being called.
1522 * @param signal A signal to cancel the operation in progress, or
1523 * {@code null} if none. For example, if you are downloading a
1524 * file from the network to service a "rw" mode request, you
1525 * should periodically call
1526 * {@link CancellationSignal#throwIfCanceled()} to check whether
1527 * the client has canceled the request and abort the download.
1528 *
1529 * @return Returns a new AssetFileDescriptor from which the client can
1530 * read data of the desired type.
1531 *
1532 * @throws FileNotFoundException Throws FileNotFoundException if there is
1533 * no file associated with the given URI or the mode is invalid.
1534 * @throws SecurityException Throws SecurityException if the caller does
1535 * not have permission to access the data.
1536 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1537 * content provider does not support the requested MIME type.
1538 *
1539 * @see #getStreamTypes(Uri, String)
1540 * @see #openAssetFile(Uri, String)
1541 * @see ClipDescription#compareMimeTypes(String, String)
1542 */
1543 public AssetFileDescriptor openTypedAssetFile(
1544 Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)
1545 throws FileNotFoundException {
1546 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1547 }
1548
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001549 /**
1550 * Interface to write a stream of data to a pipe. Use with
1551 * {@link ContentProvider#openPipeHelper}.
1552 */
1553 public interface PipeDataWriter<T> {
1554 /**
1555 * Called from a background thread to stream data out to a pipe.
1556 * Note that the pipe is blocking, so this thread can block on
1557 * writes for an arbitrary amount of time if the client is slow
1558 * at reading.
1559 *
1560 * @param output The pipe where data should be written. This will be
1561 * closed for you upon returning from this function.
1562 * @param uri The URI whose data is to be written.
1563 * @param mimeType The desired type of data to be written.
1564 * @param opts Options supplied by caller.
1565 * @param args Your own custom arguments.
1566 */
1567 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
1568 Bundle opts, T args);
1569 }
1570
1571 /**
1572 * A helper function for implementing {@link #openTypedAssetFile}, for
1573 * creating a data pipe and background thread allowing you to stream
1574 * generated data back to the client. This function returns a new
1575 * ParcelFileDescriptor that should be returned to the caller (the caller
1576 * is responsible for closing it).
1577 *
1578 * @param uri The URI whose data is to be written.
1579 * @param mimeType The desired type of data to be written.
1580 * @param opts Options supplied by caller.
1581 * @param args Your own custom arguments.
1582 * @param func Interface implementing the function that will actually
1583 * stream the data.
1584 * @return Returns a new ParcelFileDescriptor holding the read side of
1585 * the pipe. This should be returned to the caller for reading; the caller
1586 * is responsible for closing it when done.
1587 */
1588 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
1589 final Bundle opts, final T args, final PipeDataWriter<T> func)
1590 throws FileNotFoundException {
1591 try {
1592 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1593
1594 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1595 @Override
1596 protected Object doInBackground(Object... params) {
1597 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1598 try {
1599 fds[1].close();
1600 } catch (IOException e) {
1601 Log.w(TAG, "Failure closing pipe", e);
1602 }
1603 return null;
1604 }
1605 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001606 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001607
1608 return fds[0];
1609 } catch (IOException e) {
1610 throw new FileNotFoundException("failure making pipe");
1611 }
1612 }
1613
1614 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 * Returns true if this instance is a temporary content provider.
1616 * @return true if this instance is a temporary content provider
1617 */
1618 protected boolean isTemporary() {
1619 return false;
1620 }
1621
1622 /**
1623 * Returns the Binder object for this provider.
1624 *
1625 * @return the Binder object for this provider
1626 * @hide
1627 */
1628 public IContentProvider getIContentProvider() {
1629 return mTransport;
1630 }
1631
1632 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001633 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1634 * when directly instantiating the provider for testing.
1635 * @hide
1636 */
1637 public void attachInfoForTesting(Context context, ProviderInfo info) {
1638 attachInfo(context, info, true);
1639 }
1640
1641 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 * After being instantiated, this is called to tell the content provider
1643 * about itself.
1644 *
1645 * @param context The context this provider is running in
1646 * @param info Registered information about this content provider
1647 */
1648 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001649 attachInfo(context, info, false);
1650 }
1651
1652 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001653 /*
1654 * We may be using AsyncTask from binder threads. Make it init here
1655 * so its static handler is on the main thread.
1656 */
1657 AsyncTask.init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001659 mNoPerms = testing;
1660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 /*
1662 * Only allow it to be set once, so after the content service gives
1663 * this to us clients can't change it.
1664 */
1665 if (mContext == null) {
1666 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001667 if (context != null) {
1668 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1669 Context.APP_OPS_SERVICE);
1670 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001671 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 if (info != null) {
1673 setReadPermission(info.readPermission);
1674 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001675 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001676 mExported = info.exported;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001677 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 }
1679 ContentProvider.this.onCreate();
1680 }
1681 }
Fred Quintanace31b232009-05-04 16:01:15 -07001682
1683 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001684 * Override this to handle requests to perform a batch of operations, or the
1685 * default implementation will iterate over the operations and call
1686 * {@link ContentProviderOperation#apply} on each of them.
1687 * If all calls to {@link ContentProviderOperation#apply} succeed
1688 * then a {@link ContentProviderResult} array with as many
1689 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001690 * fail, it is up to the implementation how many of the others take effect.
1691 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001692 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1693 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001694 *
Fred Quintanace31b232009-05-04 16:01:15 -07001695 * @param operations the operations to apply
1696 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001697 * @throws OperationApplicationException thrown if any operation fails.
1698 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001699 */
Fred Quintana03d94902009-05-22 14:23:31 -07001700 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001701 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001702 final int numOperations = operations.size();
1703 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1704 for (int i = 0; i < numOperations; i++) {
1705 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001706 }
1707 return results;
1708 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001709
1710 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001711 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001712 * interfaces that are cheaper and/or unnatural for a table-like
1713 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001714 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001715 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1716 * on this entry into the content provider besides the basic ability for the application
1717 * to get access to the provider at all. For example, it has no idea whether the call
1718 * being executed may read or write data in the provider, so can't enforce those
1719 * individual permissions. Any implementation of this method <strong>must</strong>
1720 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1721 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001722 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1723 * @param arg provider-defined String argument. May be {@code null}.
1724 * @param extras provider-defined Bundle argument. May be {@code null}.
1725 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001726 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001727 */
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001728 public Bundle call(String method, String arg, Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001729 return null;
1730 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001731
1732 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001733 * Implement this to shut down the ContentProvider instance. You can then
1734 * invoke this method in unit tests.
1735 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001736 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001737 * Android normally handles ContentProvider startup and shutdown
1738 * automatically. You do not need to start up or shut down a
1739 * ContentProvider. When you invoke a test method on a ContentProvider,
1740 * however, a ContentProvider instance is started and keeps running after
1741 * the test finishes, even if a succeeding test instantiates another
1742 * ContentProvider. A conflict develops because the two instances are
1743 * usually running against the same underlying data source (for example, an
1744 * sqlite database).
1745 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001746 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001747 * Implementing shutDown() avoids this conflict by providing a way to
1748 * terminate the ContentProvider. This method can also prevent memory leaks
1749 * from multiple instantiations of the ContentProvider, and it can ensure
1750 * unit test isolation by allowing you to completely clean up the test
1751 * fixture before moving on to the next test.
1752 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001753 */
1754 public void shutdown() {
1755 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1756 "connections are gracefully shutdown");
1757 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001758
1759 /**
1760 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001761 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001762 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001763 * @param fd The raw file descriptor that the dump is being sent to.
1764 * @param writer The PrintWriter to which you should dump your state. This will be
1765 * closed for you after you return.
1766 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001767 */
1768 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1769 writer.println("nothing to dump");
1770 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001771
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001772 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001773 private void validateIncomingUri(Uri uri) throws SecurityException {
1774 String auth = uri.getAuthority();
1775 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001776 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
1777 throw new SecurityException("trying to query a ContentProvider in user "
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001778 + mContext.getUserId() + " with a uri belonging to user " + userId);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001779 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001780 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
1781 String message = "The authority of the uri " + uri + " does not match the one of the "
1782 + "contentProvider: ";
1783 if (mAuthority != null) {
1784 message += mAuthority;
1785 } else {
1786 message += mAuthorities;
1787 }
1788 throw new SecurityException(message);
1789 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001790 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001791
1792 /** @hide */
1793 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1794 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001795 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001796 if (end == -1) return defaultUserId;
1797 String userIdString = auth.substring(0, end);
1798 try {
1799 return Integer.parseInt(userIdString);
1800 } catch (NumberFormatException e) {
1801 Log.w(TAG, "Error parsing userId.", e);
1802 return UserHandle.USER_NULL;
1803 }
1804 }
1805
1806 /** @hide */
1807 public static int getUserIdFromAuthority(String auth) {
1808 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1809 }
1810
1811 /** @hide */
1812 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1813 if (uri == null) return defaultUserId;
1814 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1815 }
1816
1817 /** @hide */
1818 public static int getUserIdFromUri(Uri uri) {
1819 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1820 }
1821
1822 /**
1823 * Removes userId part from authority string. Expects format:
1824 * userId@some.authority
1825 * If there is no userId in the authority, it symply returns the argument
1826 * @hide
1827 */
1828 public static String getAuthorityWithoutUserId(String auth) {
1829 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001830 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001831 return auth.substring(end+1);
1832 }
1833
1834 /** @hide */
1835 public static Uri getUriWithoutUserId(Uri uri) {
1836 if (uri == null) return null;
1837 Uri.Builder builder = uri.buildUpon();
1838 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1839 return builder.build();
1840 }
1841
1842 /** @hide */
1843 public static boolean uriHasUserId(Uri uri) {
1844 if (uri == null) return false;
1845 return !TextUtils.isEmpty(uri.getUserInfo());
1846 }
1847
1848 /** @hide */
1849 public static Uri maybeAddUserId(Uri uri, int userId) {
1850 if (uri == null) return null;
1851 if (userId != UserHandle.USER_CURRENT
1852 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1853 if (!uriHasUserId(uri)) {
1854 //We don't add the user Id if there's already one
1855 Uri.Builder builder = uri.buildUpon();
1856 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1857 return builder.build();
1858 }
1859 }
1860 return uri;
1861 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001862}