blob: 2853c58d4b0729b4f62b06a5c952de997e732a9d [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;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700110 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700112 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<String>();
113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 private Transport mTransport = new Transport();
115
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700116 /**
117 * Construct a ContentProvider instance. Content providers must be
118 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
119 * in the manifest</a>, accessed with {@link ContentResolver}, and created
120 * automatically by the system, so applications usually do not create
121 * ContentProvider instances directly.
122 *
123 * <p>At construction time, the object is uninitialized, and most fields and
124 * methods are unavailable. Subclasses should initialize themselves in
125 * {@link #onCreate}, not the constructor.
126 *
127 * <p>Content providers are created on the application main thread at
128 * application launch time. The constructor must not perform lengthy
129 * operations, or application startup will be delayed.
130 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900131 public ContentProvider() {
132 }
133
134 /**
135 * Constructor just for mocking.
136 *
137 * @param context A Context object which should be some mock instance (like the
138 * instance of {@link android.test.mock.MockContext}).
139 * @param readPermission The read permision you want this instance should have in the
140 * test, which is available via {@link #getReadPermission()}.
141 * @param writePermission The write permission you want this instance should have
142 * in the test, which is available via {@link #getWritePermission()}.
143 * @param pathPermissions The PathPermissions you want this instance should have
144 * in the test, which is available via {@link #getPathPermissions()}.
145 * @hide
146 */
147 public ContentProvider(
148 Context context,
149 String readPermission,
150 String writePermission,
151 PathPermission[] pathPermissions) {
152 mContext = context;
153 mReadPermission = readPermission;
154 mWritePermission = writePermission;
155 mPathPermissions = pathPermissions;
156 }
157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 /**
159 * Given an IContentProvider, try to coerce it back to the real
160 * ContentProvider object if it is running in the local process. This can
161 * be used if you know you are running in the same process as a provider,
162 * and want to get direct access to its implementation details. Most
163 * clients should not nor have a reason to use it.
164 *
165 * @param abstractInterface The ContentProvider interface that is to be
166 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800167 * @return If the IContentProvider is non-{@code null} and local, returns its actual
168 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 * @hide
170 */
171 public static ContentProvider coerceToLocalContentProvider(
172 IContentProvider abstractInterface) {
173 if (abstractInterface instanceof Transport) {
174 return ((Transport)abstractInterface).getContentProvider();
175 }
176 return null;
177 }
178
179 /**
180 * Binder object that deals with remoting.
181 *
182 * @hide
183 */
184 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800185 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800186 int mReadOp = AppOpsManager.OP_NONE;
187 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 ContentProvider getContentProvider() {
190 return ContentProvider.this;
191 }
192
Jeff Brownd2183652011-10-09 12:39:53 -0700193 @Override
194 public String getProviderName() {
195 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 }
197
Jeff Brown75ea64f2012-01-25 19:37:13 -0800198 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800199 public Cursor query(String callingPkg, Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800200 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800201 ICancellationSignal cancellationSignal) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100202 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100203 uri = getUriWithoutUserId(uri);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800204 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800205 return rejectQuery(uri, projection, selection, selectionArgs, sortOrder,
206 CancellationSignal.fromTransport(cancellationSignal));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800207 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700208 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700209 try {
210 return ContentProvider.this.query(
211 uri, projection, selection, selectionArgs, sortOrder,
212 CancellationSignal.fromTransport(cancellationSignal));
213 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700214 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 }
217
Jeff Brown75ea64f2012-01-25 19:37:13 -0800218 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100220 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100221 uri = getUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 return ContentProvider.this.getType(uri);
223 }
224
Jeff Brown75ea64f2012-01-25 19:37:13 -0800225 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800226 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100227 validateIncomingUri(uri);
228 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100229 uri = getUriWithoutUserId(uri);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800230 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800231 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800232 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700233 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700234 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100235 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700236 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700237 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 }
240
Jeff Brown75ea64f2012-01-25 19:37:13 -0800241 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800242 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100243 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100244 uri = getUriWithoutUserId(uri);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800245 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
246 return 0;
247 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700248 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700249 try {
250 return ContentProvider.this.bulkInsert(uri, initialValues);
251 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700252 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 }
255
Jeff Brown75ea64f2012-01-25 19:37:13 -0800256 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800257 public ContentProviderResult[] applyBatch(String callingPkg,
258 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700259 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100260 int numOperations = operations.size();
261 final int[] userIds = new int[numOperations];
262 for (int i = 0; i < numOperations; i++) {
263 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100264 Uri uri = operation.getUri();
265 validateIncomingUri(uri);
266 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100267 if (userIds[i] != UserHandle.USER_CURRENT) {
268 // Removing the user id from the uri.
269 operation = new ContentProviderOperation(operation, true);
270 operations.set(i, operation);
271 }
Fred Quintana89437372009-05-15 15:10:40 -0700272 if (operation.isReadOperation()) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100273 if (enforceReadPermission(callingPkg, uri)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800274 != AppOpsManager.MODE_ALLOWED) {
275 throw new OperationApplicationException("App op not allowed", 0);
276 }
Fred Quintana89437372009-05-15 15:10:40 -0700277 }
Fred Quintana89437372009-05-15 15:10:40 -0700278 if (operation.isWriteOperation()) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100279 if (enforceWritePermission(callingPkg, uri)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800280 != AppOpsManager.MODE_ALLOWED) {
281 throw new OperationApplicationException("App op not allowed", 0);
282 }
Fred Quintana89437372009-05-15 15:10:40 -0700283 }
284 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700285 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700286 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100287 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
288 for (int i = 0; i < results.length ; i++) {
289 if (userIds[i] != UserHandle.USER_CURRENT) {
290 // Adding the userId to the uri.
291 results[i] = new ContentProviderResult(results[i], userIds[i]);
292 }
293 }
294 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700295 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700296 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700297 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700298 }
299
Jeff Brown75ea64f2012-01-25 19:37:13 -0800300 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800301 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100302 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100303 uri = getUriWithoutUserId(uri);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800304 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
305 return 0;
306 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700307 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700308 try {
309 return ContentProvider.this.delete(uri, selection, selectionArgs);
310 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700311 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 }
314
Jeff Brown75ea64f2012-01-25 19:37:13 -0800315 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800316 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100318 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100319 uri = getUriWithoutUserId(uri);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800320 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
321 return 0;
322 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700323 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700324 try {
325 return ContentProvider.this.update(uri, values, selection, selectionArgs);
326 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700327 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 }
330
Jeff Brown75ea64f2012-01-25 19:37:13 -0800331 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700332 public ParcelFileDescriptor openFile(
333 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100335 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100336 uri = getUriWithoutUserId(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100337 enforceFilePermission(callingPkg, uri, mode);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700338 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700339 try {
340 return ContentProvider.this.openFile(
341 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
342 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700343 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 }
346
Jeff Brown75ea64f2012-01-25 19:37:13 -0800347 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700348 public AssetFileDescriptor openAssetFile(
349 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100351 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100352 uri = getUriWithoutUserId(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100353 enforceFilePermission(callingPkg, uri, mode);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700354 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700355 try {
356 return ContentProvider.this.openAssetFile(
357 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
358 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700359 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 }
362
Jeff Brown75ea64f2012-01-25 19:37:13 -0800363 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800364 public Bundle call(String callingPkg, String method, String arg, Bundle extras) {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700365 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700366 try {
367 return ContentProvider.this.call(method, arg, extras);
368 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700369 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700370 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800371 }
372
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700373 @Override
374 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100375 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100376 uri = getUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700377 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
378 }
379
380 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800381 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700382 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100383 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100384 uri = getUriWithoutUserId(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100385 enforceFilePermission(callingPkg, uri, "r");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700386 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700387 try {
388 return ContentProvider.this.openTypedAssetFile(
389 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
390 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700391 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700392 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700393 }
394
Jeff Brown75ea64f2012-01-25 19:37:13 -0800395 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700396 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800397 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800398 }
399
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700400 @Override
401 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100402 validateIncomingUri(uri);
403 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100404 uri = getUriWithoutUserId(uri);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700405 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
406 return null;
407 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700408 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700409 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100410 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700411 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700412 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700413 }
414 }
415
416 @Override
417 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100418 validateIncomingUri(uri);
419 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100420 uri = getUriWithoutUserId(uri);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700421 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
422 return null;
423 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700424 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700425 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100426 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700427 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700428 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700429 }
430 }
431
Dianne Hackborn35654b62013-01-14 17:38:02 -0800432 private void enforceFilePermission(String callingPkg, Uri uri, String mode)
433 throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800434 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800435 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
436 throw new FileNotFoundException("App op not allowed");
437 }
438 } else {
439 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
440 throw new FileNotFoundException("App op not allowed");
441 }
442 }
443 }
444
445 private int enforceReadPermission(String callingPkg, Uri uri) throws SecurityException {
446 enforceReadPermissionInner(uri);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800447 if (mReadOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800448 return mAppOpsManager.noteOp(mReadOp, Binder.getCallingUid(), callingPkg);
449 }
450 return AppOpsManager.MODE_ALLOWED;
451 }
452
Dianne Hackborn35654b62013-01-14 17:38:02 -0800453 private int enforceWritePermission(String callingPkg, Uri uri) throws SecurityException {
454 enforceWritePermissionInner(uri);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800455 if (mWriteOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800456 return mAppOpsManager.noteOp(mWriteOp, Binder.getCallingUid(), callingPkg);
457 }
458 return AppOpsManager.MODE_ALLOWED;
459 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700460 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800461
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100462 boolean checkUser(int pid, int uid, Context context) {
463 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700464 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100465 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
466 == PERMISSION_GRANTED;
467 }
468
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700469 /** {@hide} */
470 protected void enforceReadPermissionInner(Uri uri) throws SecurityException {
471 final Context context = getContext();
472 final int pid = Binder.getCallingPid();
473 final int uid = Binder.getCallingUid();
474 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700475
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700476 if (UserHandle.isSameApp(uid, mMyUid)) {
477 return;
478 }
479
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100480 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700481 final String componentPerm = getReadPermission();
482 if (componentPerm != null) {
483 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
484 return;
485 } else {
486 missingPerm = componentPerm;
487 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700488 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700489
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700490 // track if unprotected read is allowed; any denied
491 // <path-permission> below removes this ability
492 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700493
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700494 final PathPermission[] pps = getPathPermissions();
495 if (pps != null) {
496 final String path = uri.getPath();
497 for (PathPermission pp : pps) {
498 final String pathPerm = pp.getReadPermission();
499 if (pathPerm != null && pp.match(path)) {
500 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
501 return;
502 } else {
503 // any denied <path-permission> means we lose
504 // default <provider> access.
505 allowDefaultRead = false;
506 missingPerm = pathPerm;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700507 }
508 }
509 }
510 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700511
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700512 // if we passed <path-permission> checks above, and no default
513 // <provider> permission, then allow access.
514 if (allowDefaultRead) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700516
517 // last chance, check against any uri grants
518 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION)
519 == PERMISSION_GRANTED) {
520 return;
521 }
522
523 final String failReason = mExported
524 ? " requires " + missingPerm + ", or grantUriPermission()"
525 : " requires the provider be exported, or grantUriPermission()";
526 throw new SecurityException("Permission Denial: reading "
527 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
528 + ", uid=" + uid + failReason);
529 }
530
531 /** {@hide} */
532 protected void enforceWritePermissionInner(Uri uri) throws SecurityException {
533 final Context context = getContext();
534 final int pid = Binder.getCallingPid();
535 final int uid = Binder.getCallingUid();
536 String missingPerm = null;
537
538 if (UserHandle.isSameApp(uid, mMyUid)) {
539 return;
540 }
541
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100542 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700543 final String componentPerm = getWritePermission();
544 if (componentPerm != null) {
545 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
546 return;
547 } else {
548 missingPerm = componentPerm;
549 }
550 }
551
552 // track if unprotected write is allowed; any denied
553 // <path-permission> below removes this ability
554 boolean allowDefaultWrite = (componentPerm == null);
555
556 final PathPermission[] pps = getPathPermissions();
557 if (pps != null) {
558 final String path = uri.getPath();
559 for (PathPermission pp : pps) {
560 final String pathPerm = pp.getWritePermission();
561 if (pathPerm != null && pp.match(path)) {
562 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
563 return;
564 } else {
565 // any denied <path-permission> means we lose
566 // default <provider> access.
567 allowDefaultWrite = false;
568 missingPerm = pathPerm;
569 }
570 }
571 }
572 }
573
574 // if we passed <path-permission> checks above, and no default
575 // <provider> permission, then allow access.
576 if (allowDefaultWrite) return;
577 }
578
579 // last chance, check against any uri grants
580 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
581 == PERMISSION_GRANTED) {
582 return;
583 }
584
585 final String failReason = mExported
586 ? " requires " + missingPerm + ", or grantUriPermission()"
587 : " requires the provider be exported, or grantUriPermission()";
588 throw new SecurityException("Permission Denial: writing "
589 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
590 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 }
592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700594 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800595 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 * constructor.
597 */
598 public final Context getContext() {
599 return mContext;
600 }
601
602 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700603 * Set the calling package, returning the current value (or {@code null})
604 * which can be used later to restore the previous state.
605 */
606 private String setCallingPackage(String callingPackage) {
607 final String original = mCallingPackage.get();
608 mCallingPackage.set(callingPackage);
609 return original;
610 }
611
612 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700613 * Return the package name of the caller that initiated the request being
614 * processed on the current thread. The returned package will have been
615 * verified to belong to the calling UID. Returns {@code null} if not
616 * currently processing a request.
617 * <p>
618 * This will always return {@code null} when processing
619 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
620 *
621 * @see Binder#getCallingUid()
622 * @see Context#grantUriPermission(String, Uri, int)
623 * @throws SecurityException if the calling package doesn't belong to the
624 * calling UID.
625 */
626 public final String getCallingPackage() {
627 final String pkg = mCallingPackage.get();
628 if (pkg != null) {
629 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
630 }
631 return pkg;
632 }
633
634 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100635 * Change the authorities of the ContentProvider.
636 * This is normally set for you from its manifest information when the provider is first
637 * created.
638 * @hide
639 * @param authorities the semi-colon separated authorities of the ContentProvider.
640 */
641 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100642 if (authorities != null) {
643 if (authorities.indexOf(';') == -1) {
644 mAuthority = authorities;
645 mAuthorities = null;
646 } else {
647 mAuthority = null;
648 mAuthorities = authorities.split(";");
649 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100650 }
651 }
652
653 /** @hide */
654 protected final boolean matchesOurAuthorities(String authority) {
655 if (mAuthority != null) {
656 return mAuthority.equals(authority);
657 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100658 if (mAuthorities != null) {
659 int length = mAuthorities.length;
660 for (int i = 0; i < length; i++) {
661 if (mAuthorities[i].equals(authority)) return true;
662 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100663 }
664 return false;
665 }
666
667
668 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 * Change the permission required to read data from the content
670 * provider. This is normally set for you from its manifest information
671 * when the provider is first created.
672 *
673 * @param permission Name of the permission required for read-only access.
674 */
675 protected final void setReadPermission(String permission) {
676 mReadPermission = permission;
677 }
678
679 /**
680 * Return the name of the permission required for read-only access to
681 * this content provider. This method can be called from multiple
682 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800683 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
684 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 */
686 public final String getReadPermission() {
687 return mReadPermission;
688 }
689
690 /**
691 * Change the permission required to read and write data in the content
692 * provider. This is normally set for you from its manifest information
693 * when the provider is first created.
694 *
695 * @param permission Name of the permission required for read/write access.
696 */
697 protected final void setWritePermission(String permission) {
698 mWritePermission = permission;
699 }
700
701 /**
702 * Return the name of the permission required for read/write access to
703 * this content provider. This method can be called from multiple
704 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800705 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
706 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 */
708 public final String getWritePermission() {
709 return mWritePermission;
710 }
711
712 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700713 * Change the path-based permission required to read and/or write data in
714 * the content provider. This is normally set for you from its manifest
715 * information when the provider is first created.
716 *
717 * @param permissions Array of path permission descriptions.
718 */
719 protected final void setPathPermissions(PathPermission[] permissions) {
720 mPathPermissions = permissions;
721 }
722
723 /**
724 * Return the path-based permissions required for read and/or write access to
725 * this content provider. This method can be called from multiple
726 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800727 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
728 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700729 */
730 public final PathPermission[] getPathPermissions() {
731 return mPathPermissions;
732 }
733
Dianne Hackborn35654b62013-01-14 17:38:02 -0800734 /** @hide */
735 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800736 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800737 mTransport.mReadOp = readOp;
738 mTransport.mWriteOp = writeOp;
739 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800740 }
741
Dianne Hackborn961321f2013-02-05 17:22:41 -0800742 /** @hide */
743 public AppOpsManager getAppOpsManager() {
744 return mTransport.mAppOpsManager;
745 }
746
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700747 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700748 * Implement this to initialize your content provider on startup.
749 * This method is called for all registered content providers on the
750 * application main thread at application launch time. It must not perform
751 * lengthy operations, or application startup will be delayed.
752 *
753 * <p>You should defer nontrivial initialization (such as opening,
754 * upgrading, and scanning databases) until the content provider is used
755 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
756 * keeps application startup fast, avoids unnecessary work if the provider
757 * turns out not to be needed, and stops database errors (such as a full
758 * disk) from halting application launch.
759 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700760 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700761 * is a helpful utility class that makes it easy to manage databases,
762 * and will automatically defer opening until first use. If you do use
763 * SQLiteOpenHelper, make sure to avoid calling
764 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
765 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
766 * from this method. (Instead, override
767 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
768 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 *
770 * @return true if the provider was successfully loaded, false otherwise
771 */
772 public abstract boolean onCreate();
773
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700774 /**
775 * {@inheritDoc}
776 * This method is always called on the application main thread, and must
777 * not perform lengthy operations.
778 *
779 * <p>The default content provider implementation does nothing.
780 * Override this method to take appropriate action.
781 * (Content providers do not usually care about things like screen
782 * orientation, but may want to know about locale changes.)
783 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 public void onConfigurationChanged(Configuration newConfig) {
785 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700786
787 /**
788 * {@inheritDoc}
789 * This method is always called on the application main thread, and must
790 * not perform lengthy operations.
791 *
792 * <p>The default content provider implementation does nothing.
793 * Subclasses may override this method to take appropriate action.
794 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 public void onLowMemory() {
796 }
797
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700798 public void onTrimMemory(int level) {
799 }
800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800802 * @hide
803 * Implementation when a caller has performed a query on the content
804 * provider, but that call has been rejected for the operation given
805 * to {@link #setAppOps(int, int)}. The default implementation
806 * rewrites the <var>selection</var> argument to include a condition
807 * that is never true (so will always result in an empty cursor)
808 * and calls through to {@link #query(android.net.Uri, String[], String, String[],
809 * String, android.os.CancellationSignal)} with that.
810 */
811 public Cursor rejectQuery(Uri uri, String[] projection,
812 String selection, String[] selectionArgs, String sortOrder,
813 CancellationSignal cancellationSignal) {
814 // The read is not allowed... to fake it out, we replace the given
815 // selection statement with a dummy one that will always be false.
816 // This way we will get a cursor back that has the correct structure
817 // but contains no rows.
Dianne Hackborn9fa39bd2013-03-22 18:42:14 -0700818 if (selection == null || selection.isEmpty()) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800819 selection = "'A' = 'B'";
820 } else {
821 selection = "'A' = 'B' AND (" + selection + ")";
822 }
823 return query(uri, projection, selection, selectionArgs, sortOrder, cancellationSignal);
824 }
825
826 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700827 * Implement this to handle query requests from clients.
828 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800829 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
830 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 * <p>
832 * Example client call:<p>
833 * <pre>// Request a specific record.
834 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000835 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 projection, // Which columns to return.
837 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000838 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 People.NAME + " ASC"); // Sort order.</pre>
840 * Example implementation:<p>
841 * <pre>// SQLiteQueryBuilder is a helper class that creates the
842 // proper SQL syntax for us.
843 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
844
845 // Set the table we're querying.
846 qBuilder.setTables(DATABASE_TABLE_NAME);
847
848 // If the query ends in a specific record number, we're
849 // being asked for a specific record, so set the
850 // WHERE clause in our query.
851 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
852 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
853 }
854
855 // Make the query.
856 Cursor c = qBuilder.query(mDb,
857 projection,
858 selection,
859 selectionArgs,
860 groupBy,
861 having,
862 sortOrder);
863 c.setNotificationUri(getContext().getContentResolver(), uri);
864 return c;</pre>
865 *
866 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000867 * if the client is requesting a specific record, the URI will end in a record number
868 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
869 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800871 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800873 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000874 * @param selectionArgs You may include ?s in selection, which will be replaced by
875 * the values from selectionArgs, in order that they appear in the selection.
876 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800878 * If {@code null} then the provider is free to define the sort order.
879 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 */
881 public abstract Cursor query(Uri uri, String[] projection,
882 String selection, String[] selectionArgs, String sortOrder);
883
Fred Quintana5bba6322009-10-05 14:21:12 -0700884 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800885 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800886 * This method can be called from multiple threads, as described in
887 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
888 * and Threads</a>.
889 * <p>
890 * Example client call:<p>
891 * <pre>// Request a specific record.
892 * Cursor managedCursor = managedQuery(
893 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
894 projection, // Which columns to return.
895 null, // WHERE clause.
896 null, // WHERE clause value substitution
897 People.NAME + " ASC"); // Sort order.</pre>
898 * Example implementation:<p>
899 * <pre>// SQLiteQueryBuilder is a helper class that creates the
900 // proper SQL syntax for us.
901 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
902
903 // Set the table we're querying.
904 qBuilder.setTables(DATABASE_TABLE_NAME);
905
906 // If the query ends in a specific record number, we're
907 // being asked for a specific record, so set the
908 // WHERE clause in our query.
909 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
910 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
911 }
912
913 // Make the query.
914 Cursor c = qBuilder.query(mDb,
915 projection,
916 selection,
917 selectionArgs,
918 groupBy,
919 having,
920 sortOrder);
921 c.setNotificationUri(getContext().getContentResolver(), uri);
922 return c;</pre>
923 * <p>
924 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800925 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
926 * signal to ensure correct operation on older versions of the Android Framework in
927 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800928 *
929 * @param uri The URI to query. This will be the full URI sent by the client;
930 * if the client is requesting a specific record, the URI will end in a record number
931 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
932 * that _id value.
933 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800934 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800935 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800936 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800937 * @param selectionArgs You may include ?s in selection, which will be replaced by
938 * the values from selectionArgs, in order that they appear in the selection.
939 * The values will be bound as Strings.
940 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800941 * If {@code null} then the provider is free to define the sort order.
942 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800943 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
944 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800945 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800946 */
947 public Cursor query(Uri uri, String[] projection,
948 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800949 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800950 return query(uri, projection, selection, selectionArgs, sortOrder);
951 }
952
953 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700954 * Implement this to handle requests for the MIME type of the data at the
955 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 * <code>vnd.android.cursor.item</code> for a single record,
957 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700958 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800959 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
960 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700962 * <p>Note that there are no permissions needed for an application to
963 * access this information; if your content provider requires read and/or
964 * write permissions, or is not exported, all applications can still call
965 * this method regardless of their access permissions. This allows them
966 * to retrieve the MIME type for a URI when dispatching intents.
967 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800969 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 */
971 public abstract String getType(Uri uri);
972
973 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700974 * Implement this to support canonicalization of URIs that refer to your
975 * content provider. A canonical URI is one that can be transported across
976 * devices, backup/restore, and other contexts, and still be able to refer
977 * to the same data item. Typically this is implemented by adding query
978 * params to the URI allowing the content provider to verify that an incoming
979 * canonical URI references the same data as it was originally intended for and,
980 * if it doesn't, to find that data (if it exists) in the current environment.
981 *
982 * <p>For example, if the content provider holds people and a normal URI in it
983 * is created with a row index into that people database, the cananical representation
984 * may have an additional query param at the end which specifies the name of the
985 * person it is intended for. Later calls into the provider with that URI will look
986 * up the row of that URI's base index and, if it doesn't match or its entry's
987 * name doesn't match the name in the query param, perform a query on its database
988 * to find the correct row to operate on.</p>
989 *
990 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
991 * URIs (including this one) must perform this verification and recovery of any
992 * canonical URIs they receive. In addition, you must also implement
993 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
994 *
995 * <p>The default implementation of this method returns null, indicating that
996 * canonical URIs are not supported.</p>
997 *
998 * @param url The Uri to canonicalize.
999 *
1000 * @return Return the canonical representation of <var>url</var>, or null if
1001 * canonicalization of that Uri is not supported.
1002 */
1003 public Uri canonicalize(Uri url) {
1004 return null;
1005 }
1006
1007 /**
1008 * Remove canonicalization from canonical URIs previously returned by
1009 * {@link #canonicalize}. For example, if your implementation is to add
1010 * a query param to canonicalize a URI, this method can simply trip any
1011 * query params on the URI. The default implementation always returns the
1012 * same <var>url</var> that was passed in.
1013 *
1014 * @param url The Uri to remove any canonicalization from.
1015 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001016 * @return Return the non-canonical representation of <var>url</var>, return
1017 * the <var>url</var> as-is if there is nothing to do, or return null if
1018 * the data identified by the canonical representation can not be found in
1019 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001020 */
1021 public Uri uncanonicalize(Uri url) {
1022 return url;
1023 }
1024
1025 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001026 * @hide
1027 * Implementation when a caller has performed an insert on the content
1028 * provider, but that call has been rejected for the operation given
1029 * to {@link #setAppOps(int, int)}. The default implementation simply
1030 * returns a dummy URI that is the base URI with a 0 path element
1031 * appended.
1032 */
1033 public Uri rejectInsert(Uri uri, ContentValues values) {
1034 // If not allowed, we need to return some reasonable URI. Maybe the
1035 // content provider should be responsible for this, but for now we
1036 // will just return the base URI with a dummy '0' tagged on to it.
1037 // You shouldn't be able to read if you can't write, anyway, so it
1038 // shouldn't matter much what is returned.
1039 return uri.buildUpon().appendPath("0").build();
1040 }
1041
1042 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001043 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1045 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001046 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001047 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1048 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001049 * @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 -08001050 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001051 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 * @return The URI for the newly inserted item.
1053 */
1054 public abstract Uri insert(Uri uri, ContentValues values);
1055
1056 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001057 * Override this to handle requests to insert a set of new rows, or the
1058 * default implementation will iterate over the values and call
1059 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1061 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001062 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001063 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1064 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 *
1066 * @param uri The content:// URI of the insertion request.
1067 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001068 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 * @return The number of values that were inserted.
1070 */
1071 public int bulkInsert(Uri uri, ContentValues[] values) {
1072 int numValues = values.length;
1073 for (int i = 0; i < numValues; i++) {
1074 insert(uri, values[i]);
1075 }
1076 return numValues;
1077 }
1078
1079 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001080 * Implement this to handle requests to delete one or more rows.
1081 * The implementation should apply the selection clause when performing
1082 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001083 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001085 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001086 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1087 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 *
1089 * <p>The implementation is responsible for parsing out a row ID at the end
1090 * of the URI, if a specific row is being deleted. That is, the client would
1091 * pass in <code>content://contacts/people/22</code> and the implementation is
1092 * responsible for parsing the record number (22) when creating a SQL statement.
1093 *
1094 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1095 * @param selection An optional restriction to apply to rows when deleting.
1096 * @return The number of rows affected.
1097 * @throws SQLException
1098 */
1099 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
1100
1101 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001102 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001103 * The implementation should update all rows matching the selection
1104 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1106 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001107 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001108 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1109 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 *
1111 * @param uri The URI to query. This can potentially have a record ID if this
1112 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001113 * @param values A set of column_name/value pairs to update in the database.
1114 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 * @param selection An optional filter to match rows to update.
1116 * @return the number of rows affected.
1117 */
1118 public abstract int update(Uri uri, ContentValues values, String selection,
1119 String[] selectionArgs);
1120
1121 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001122 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001123 * The default implementation always throws {@link FileNotFoundException}.
1124 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001125 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1126 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001127 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001128 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1129 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001130 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 *
1132 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1133 * their responsibility to close it when done. That is, the implementation
1134 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001135 * <p>
1136 * If opened with the exclusive "r" or "w" modes, the returned
1137 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1138 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1139 * supports seeking.
1140 * <p>
1141 * If you need to detect when the returned ParcelFileDescriptor has been
1142 * closed, or if the remote process has crashed or encountered some other
1143 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1144 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1145 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1146 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001148 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1149 * to return the appropriate MIME type for the data returned here with
1150 * the same URI. This will allow intent resolution to automatically determine the data MIME
1151 * type and select the appropriate matching targets as part of its operation.</p>
1152 *
1153 * <p class="note">For better interoperability with other applications, it is recommended
1154 * that for any URIs that can be opened, you also support queries on them
1155 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1156 * You may also want to support other common columns if you have additional meta-data
1157 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1158 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1159 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 * @param uri The URI whose file is to be opened.
1161 * @param mode Access mode for the file. May be "r" for read-only access,
1162 * "rw" for read and write access, or "rwt" for read and write access
1163 * that truncates any existing file.
1164 *
1165 * @return Returns a new ParcelFileDescriptor which you can use to access
1166 * the file.
1167 *
1168 * @throws FileNotFoundException Throws FileNotFoundException if there is
1169 * no file associated with the given URI or the mode is invalid.
1170 * @throws SecurityException Throws SecurityException if the caller does
1171 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001172 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 * @see #openAssetFile(Uri, String)
1174 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001175 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001176 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001177 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 public ParcelFileDescriptor openFile(Uri uri, String mode)
1179 throws FileNotFoundException {
1180 throw new FileNotFoundException("No files supported by provider at "
1181 + uri);
1182 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001185 * Override this to handle requests to open a file blob.
1186 * The default implementation always throws {@link FileNotFoundException}.
1187 * This method can be called from multiple threads, as described in
1188 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1189 * and Threads</a>.
1190 *
1191 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1192 * to the caller. This way large data (such as images and documents) can be
1193 * returned without copying the content.
1194 *
1195 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1196 * their responsibility to close it when done. That is, the implementation
1197 * of this method should create a new ParcelFileDescriptor for each call.
1198 * <p>
1199 * If opened with the exclusive "r" or "w" modes, the returned
1200 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1201 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1202 * supports seeking.
1203 * <p>
1204 * If you need to detect when the returned ParcelFileDescriptor has been
1205 * closed, or if the remote process has crashed or encountered some other
1206 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1207 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1208 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1209 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1210 *
1211 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1212 * to return the appropriate MIME type for the data returned here with
1213 * the same URI. This will allow intent resolution to automatically determine the data MIME
1214 * type and select the appropriate matching targets as part of its operation.</p>
1215 *
1216 * <p class="note">For better interoperability with other applications, it is recommended
1217 * that for any URIs that can be opened, you also support queries on them
1218 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1219 * You may also want to support other common columns if you have additional meta-data
1220 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1221 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1222 *
1223 * @param uri The URI whose file is to be opened.
1224 * @param mode Access mode for the file. May be "r" for read-only access,
1225 * "w" for write-only access, "rw" for read and write access, or
1226 * "rwt" for read and write access that truncates any existing
1227 * file.
1228 * @param signal A signal to cancel the operation in progress, or
1229 * {@code null} if none. For example, if you are downloading a
1230 * file from the network to service a "rw" mode request, you
1231 * should periodically call
1232 * {@link CancellationSignal#throwIfCanceled()} to check whether
1233 * the client has canceled the request and abort the download.
1234 *
1235 * @return Returns a new ParcelFileDescriptor which you can use to access
1236 * the file.
1237 *
1238 * @throws FileNotFoundException Throws FileNotFoundException if there is
1239 * no file associated with the given URI or the mode is invalid.
1240 * @throws SecurityException Throws SecurityException if the caller does
1241 * not have permission to access the file.
1242 *
1243 * @see #openAssetFile(Uri, String)
1244 * @see #openFileHelper(Uri, String)
1245 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001246 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001247 */
1248 public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
1249 throws FileNotFoundException {
1250 return openFile(uri, mode);
1251 }
1252
1253 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 * This is like {@link #openFile}, but can be implemented by providers
1255 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001256 * inside of their .apk.
1257 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001258 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1259 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001260 *
1261 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001262 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001263 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1265 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1266 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001267 * <p>
1268 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1269 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001270 *
1271 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 * should create the AssetFileDescriptor with
1273 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001274 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001276 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1277 * to return the appropriate MIME type for the data returned here with
1278 * the same URI. This will allow intent resolution to automatically determine the data MIME
1279 * type and select the appropriate matching targets as part of its operation.</p>
1280 *
1281 * <p class="note">For better interoperability with other applications, it is recommended
1282 * that for any URIs that can be opened, you also support queries on them
1283 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1284 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 * @param uri The URI whose file is to be opened.
1286 * @param mode Access mode for the file. May be "r" for read-only access,
1287 * "w" for write-only access (erasing whatever data is currently in
1288 * the file), "wa" for write-only access to append to any existing data,
1289 * "rw" for read and write access on any existing data, and "rwt" for read
1290 * and write access that truncates any existing file.
1291 *
1292 * @return Returns a new AssetFileDescriptor which you can use to access
1293 * the file.
1294 *
1295 * @throws FileNotFoundException Throws FileNotFoundException if there is
1296 * no file associated with the given URI or the mode is invalid.
1297 * @throws SecurityException Throws SecurityException if the caller does
1298 * not have permission to access the file.
1299 *
1300 * @see #openFile(Uri, String)
1301 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001302 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 */
1304 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
1305 throws FileNotFoundException {
1306 ParcelFileDescriptor fd = openFile(uri, mode);
1307 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1308 }
1309
1310 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001311 * This is like {@link #openFile}, but can be implemented by providers
1312 * that need to be able to return sub-sections of files, often assets
1313 * inside of their .apk.
1314 * This method can be called from multiple threads, as described in
1315 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1316 * and Threads</a>.
1317 *
1318 * <p>If you implement this, your clients must be able to deal with such
1319 * file slices, either directly with
1320 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1321 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1322 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1323 * methods.
1324 * <p>
1325 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1326 * streaming of data.
1327 *
1328 * <p class="note">If you are implementing this to return a full file, you
1329 * should create the AssetFileDescriptor with
1330 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1331 * applications that cannot handle sub-sections of files.</p>
1332 *
1333 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1334 * to return the appropriate MIME type for the data returned here with
1335 * the same URI. This will allow intent resolution to automatically determine the data MIME
1336 * type and select the appropriate matching targets as part of its operation.</p>
1337 *
1338 * <p class="note">For better interoperability with other applications, it is recommended
1339 * that for any URIs that can be opened, you also support queries on them
1340 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1341 *
1342 * @param uri The URI whose file is to be opened.
1343 * @param mode Access mode for the file. May be "r" for read-only access,
1344 * "w" for write-only access (erasing whatever data is currently in
1345 * the file), "wa" for write-only access to append to any existing data,
1346 * "rw" for read and write access on any existing data, and "rwt" for read
1347 * and write access that truncates any existing file.
1348 * @param signal A signal to cancel the operation in progress, or
1349 * {@code null} if none. For example, if you are downloading a
1350 * file from the network to service a "rw" mode request, you
1351 * should periodically call
1352 * {@link CancellationSignal#throwIfCanceled()} to check whether
1353 * the client has canceled the request and abort the download.
1354 *
1355 * @return Returns a new AssetFileDescriptor which you can use to access
1356 * the file.
1357 *
1358 * @throws FileNotFoundException Throws FileNotFoundException if there is
1359 * no file associated with the given URI or the mode is invalid.
1360 * @throws SecurityException Throws SecurityException if the caller does
1361 * not have permission to access the file.
1362 *
1363 * @see #openFile(Uri, String)
1364 * @see #openFileHelper(Uri, String)
1365 * @see #getType(android.net.Uri)
1366 */
1367 public AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)
1368 throws FileNotFoundException {
1369 return openAssetFile(uri, mode);
1370 }
1371
1372 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 * Convenience for subclasses that wish to implement {@link #openFile}
1374 * by looking up a column named "_data" at the given URI.
1375 *
1376 * @param uri The URI to be opened.
1377 * @param mode The file mode. May be "r" for read-only access,
1378 * "w" for write-only access (erasing whatever data is currently in
1379 * the file), "wa" for write-only access to append to any existing data,
1380 * "rw" for read and write access on any existing data, and "rwt" for read
1381 * and write access that truncates any existing file.
1382 *
1383 * @return Returns a new ParcelFileDescriptor that can be used by the
1384 * client to access the file.
1385 */
1386 protected final ParcelFileDescriptor openFileHelper(Uri uri,
1387 String mode) throws FileNotFoundException {
1388 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1389 int count = (c != null) ? c.getCount() : 0;
1390 if (count != 1) {
1391 // If there is not exactly one result, throw an appropriate
1392 // exception.
1393 if (c != null) {
1394 c.close();
1395 }
1396 if (count == 0) {
1397 throw new FileNotFoundException("No entry for " + uri);
1398 }
1399 throw new FileNotFoundException("Multiple items at " + uri);
1400 }
1401
1402 c.moveToFirst();
1403 int i = c.getColumnIndex("_data");
1404 String path = (i >= 0 ? c.getString(i) : null);
1405 c.close();
1406 if (path == null) {
1407 throw new FileNotFoundException("Column _data not found.");
1408 }
1409
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001410 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 return ParcelFileDescriptor.open(new File(path), modeBits);
1412 }
1413
1414 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001415 * Called by a client to determine the types of data streams that this
1416 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001417 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001418 * of a particular type, return that MIME type if it matches the given
1419 * mimeTypeFilter. If it can perform type conversions, return an array
1420 * of all supported MIME types that match mimeTypeFilter.
1421 *
1422 * @param uri The data in the content provider being queried.
1423 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001424 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001425 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001426 * given mimeTypeFilter. Otherwise returns an array of all available
1427 * concrete MIME types.
1428 *
1429 * @see #getType(Uri)
1430 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001431 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001432 */
1433 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
1434 return null;
1435 }
1436
1437 /**
1438 * Called by a client to open a read-only stream containing data of a
1439 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1440 * except the file can only be read-only and the content provider may
1441 * perform data conversions to generate data of the desired type.
1442 *
1443 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001444 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001445 * {@link #openAssetFile(Uri, String)}.
1446 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001447 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001448 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001449 * <p>
1450 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1451 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001452 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001453 * <p class="note">For better interoperability with other applications, it is recommended
1454 * that for any URIs that can be opened, you also support queries on them
1455 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1456 * You may also want to support other common columns if you have additional meta-data
1457 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1458 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1459 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001460 * @param uri The data in the content provider being queried.
1461 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001462 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001463 * requirements; in this case the content provider will pick its best
1464 * type matching the pattern.
1465 * @param opts Additional options from the client. The definitions of
1466 * these are specific to the content provider being called.
1467 *
1468 * @return Returns a new AssetFileDescriptor from which the client can
1469 * read data of the desired type.
1470 *
1471 * @throws FileNotFoundException Throws FileNotFoundException if there is
1472 * no file associated with the given URI or the mode is invalid.
1473 * @throws SecurityException Throws SecurityException if the caller does
1474 * not have permission to access the data.
1475 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1476 * content provider does not support the requested MIME type.
1477 *
1478 * @see #getStreamTypes(Uri, String)
1479 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001480 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001481 */
1482 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
1483 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001484 if ("*/*".equals(mimeTypeFilter)) {
1485 // If they can take anything, the untyped open call is good enough.
1486 return openAssetFile(uri, "r");
1487 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001488 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001489 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001490 // Use old untyped open call if this provider has a type for this
1491 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001492 return openAssetFile(uri, "r");
1493 }
1494 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1495 }
1496
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001497
1498 /**
1499 * Called by a client to open a read-only stream containing data of a
1500 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1501 * except the file can only be read-only and the content provider may
1502 * perform data conversions to generate data of the desired type.
1503 *
1504 * <p>The default implementation compares the given mimeType against the
1505 * result of {@link #getType(Uri)} and, if they match, simply calls
1506 * {@link #openAssetFile(Uri, String)}.
1507 *
1508 * <p>See {@link ClipData} for examples of the use and implementation
1509 * of this method.
1510 * <p>
1511 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1512 * streaming of data.
1513 *
1514 * <p class="note">For better interoperability with other applications, it is recommended
1515 * that for any URIs that can be opened, you also support queries on them
1516 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1517 * You may also want to support other common columns if you have additional meta-data
1518 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1519 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1520 *
1521 * @param uri The data in the content provider being queried.
1522 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001523 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001524 * requirements; in this case the content provider will pick its best
1525 * type matching the pattern.
1526 * @param opts Additional options from the client. The definitions of
1527 * these are specific to the content provider being called.
1528 * @param signal A signal to cancel the operation in progress, or
1529 * {@code null} if none. For example, if you are downloading a
1530 * file from the network to service a "rw" mode request, you
1531 * should periodically call
1532 * {@link CancellationSignal#throwIfCanceled()} to check whether
1533 * the client has canceled the request and abort the download.
1534 *
1535 * @return Returns a new AssetFileDescriptor from which the client can
1536 * read data of the desired type.
1537 *
1538 * @throws FileNotFoundException Throws FileNotFoundException if there is
1539 * no file associated with the given URI or the mode is invalid.
1540 * @throws SecurityException Throws SecurityException if the caller does
1541 * not have permission to access the data.
1542 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1543 * content provider does not support the requested MIME type.
1544 *
1545 * @see #getStreamTypes(Uri, String)
1546 * @see #openAssetFile(Uri, String)
1547 * @see ClipDescription#compareMimeTypes(String, String)
1548 */
1549 public AssetFileDescriptor openTypedAssetFile(
1550 Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)
1551 throws FileNotFoundException {
1552 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1553 }
1554
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001555 /**
1556 * Interface to write a stream of data to a pipe. Use with
1557 * {@link ContentProvider#openPipeHelper}.
1558 */
1559 public interface PipeDataWriter<T> {
1560 /**
1561 * Called from a background thread to stream data out to a pipe.
1562 * Note that the pipe is blocking, so this thread can block on
1563 * writes for an arbitrary amount of time if the client is slow
1564 * at reading.
1565 *
1566 * @param output The pipe where data should be written. This will be
1567 * closed for you upon returning from this function.
1568 * @param uri The URI whose data is to be written.
1569 * @param mimeType The desired type of data to be written.
1570 * @param opts Options supplied by caller.
1571 * @param args Your own custom arguments.
1572 */
1573 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
1574 Bundle opts, T args);
1575 }
1576
1577 /**
1578 * A helper function for implementing {@link #openTypedAssetFile}, for
1579 * creating a data pipe and background thread allowing you to stream
1580 * generated data back to the client. This function returns a new
1581 * ParcelFileDescriptor that should be returned to the caller (the caller
1582 * is responsible for closing it).
1583 *
1584 * @param uri The URI whose data is to be written.
1585 * @param mimeType The desired type of data to be written.
1586 * @param opts Options supplied by caller.
1587 * @param args Your own custom arguments.
1588 * @param func Interface implementing the function that will actually
1589 * stream the data.
1590 * @return Returns a new ParcelFileDescriptor holding the read side of
1591 * the pipe. This should be returned to the caller for reading; the caller
1592 * is responsible for closing it when done.
1593 */
1594 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
1595 final Bundle opts, final T args, final PipeDataWriter<T> func)
1596 throws FileNotFoundException {
1597 try {
1598 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1599
1600 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1601 @Override
1602 protected Object doInBackground(Object... params) {
1603 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1604 try {
1605 fds[1].close();
1606 } catch (IOException e) {
1607 Log.w(TAG, "Failure closing pipe", e);
1608 }
1609 return null;
1610 }
1611 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001612 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001613
1614 return fds[0];
1615 } catch (IOException e) {
1616 throw new FileNotFoundException("failure making pipe");
1617 }
1618 }
1619
1620 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 * Returns true if this instance is a temporary content provider.
1622 * @return true if this instance is a temporary content provider
1623 */
1624 protected boolean isTemporary() {
1625 return false;
1626 }
1627
1628 /**
1629 * Returns the Binder object for this provider.
1630 *
1631 * @return the Binder object for this provider
1632 * @hide
1633 */
1634 public IContentProvider getIContentProvider() {
1635 return mTransport;
1636 }
1637
1638 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001639 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1640 * when directly instantiating the provider for testing.
1641 * @hide
1642 */
1643 public void attachInfoForTesting(Context context, ProviderInfo info) {
1644 attachInfo(context, info, true);
1645 }
1646
1647 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 * After being instantiated, this is called to tell the content provider
1649 * about itself.
1650 *
1651 * @param context The context this provider is running in
1652 * @param info Registered information about this content provider
1653 */
1654 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001655 attachInfo(context, info, false);
1656 }
1657
1658 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001659 /*
1660 * We may be using AsyncTask from binder threads. Make it init here
1661 * so its static handler is on the main thread.
1662 */
1663 AsyncTask.init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001665 mNoPerms = testing;
1666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 /*
1668 * Only allow it to be set once, so after the content service gives
1669 * this to us clients can't change it.
1670 */
1671 if (mContext == null) {
1672 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001673 if (context != null) {
1674 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1675 Context.APP_OPS_SERVICE);
1676 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001677 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 if (info != null) {
1679 setReadPermission(info.readPermission);
1680 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001681 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001682 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001683 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001684 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 }
1686 ContentProvider.this.onCreate();
1687 }
1688 }
Fred Quintanace31b232009-05-04 16:01:15 -07001689
1690 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001691 * Override this to handle requests to perform a batch of operations, or the
1692 * default implementation will iterate over the operations and call
1693 * {@link ContentProviderOperation#apply} on each of them.
1694 * If all calls to {@link ContentProviderOperation#apply} succeed
1695 * then a {@link ContentProviderResult} array with as many
1696 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001697 * fail, it is up to the implementation how many of the others take effect.
1698 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001699 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1700 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001701 *
Fred Quintanace31b232009-05-04 16:01:15 -07001702 * @param operations the operations to apply
1703 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001704 * @throws OperationApplicationException thrown if any operation fails.
1705 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001706 */
Fred Quintana03d94902009-05-22 14:23:31 -07001707 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001708 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001709 final int numOperations = operations.size();
1710 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1711 for (int i = 0; i < numOperations; i++) {
1712 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001713 }
1714 return results;
1715 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001716
1717 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001718 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001719 * interfaces that are cheaper and/or unnatural for a table-like
1720 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001721 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001722 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1723 * on this entry into the content provider besides the basic ability for the application
1724 * to get access to the provider at all. For example, it has no idea whether the call
1725 * being executed may read or write data in the provider, so can't enforce those
1726 * individual permissions. Any implementation of this method <strong>must</strong>
1727 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1728 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001729 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1730 * @param arg provider-defined String argument. May be {@code null}.
1731 * @param extras provider-defined Bundle argument. May be {@code null}.
1732 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001733 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001734 */
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001735 public Bundle call(String method, String arg, Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001736 return null;
1737 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001738
1739 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001740 * Implement this to shut down the ContentProvider instance. You can then
1741 * invoke this method in unit tests.
1742 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001743 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001744 * Android normally handles ContentProvider startup and shutdown
1745 * automatically. You do not need to start up or shut down a
1746 * ContentProvider. When you invoke a test method on a ContentProvider,
1747 * however, a ContentProvider instance is started and keeps running after
1748 * the test finishes, even if a succeeding test instantiates another
1749 * ContentProvider. A conflict develops because the two instances are
1750 * usually running against the same underlying data source (for example, an
1751 * sqlite database).
1752 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001753 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001754 * Implementing shutDown() avoids this conflict by providing a way to
1755 * terminate the ContentProvider. This method can also prevent memory leaks
1756 * from multiple instantiations of the ContentProvider, and it can ensure
1757 * unit test isolation by allowing you to completely clean up the test
1758 * fixture before moving on to the next test.
1759 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001760 */
1761 public void shutdown() {
1762 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1763 "connections are gracefully shutdown");
1764 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001765
1766 /**
1767 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001768 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001769 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001770 * @param fd The raw file descriptor that the dump is being sent to.
1771 * @param writer The PrintWriter to which you should dump your state. This will be
1772 * closed for you after you return.
1773 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001774 */
1775 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1776 writer.println("nothing to dump");
1777 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001778
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001779 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001780 private void validateIncomingUri(Uri uri) throws SecurityException {
1781 String auth = uri.getAuthority();
1782 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001783 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
1784 throw new SecurityException("trying to query a ContentProvider in user "
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001785 + mContext.getUserId() + " with a uri belonging to user " + userId);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001786 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001787 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
1788 String message = "The authority of the uri " + uri + " does not match the one of the "
1789 + "contentProvider: ";
1790 if (mAuthority != null) {
1791 message += mAuthority;
1792 } else {
1793 message += mAuthorities;
1794 }
1795 throw new SecurityException(message);
1796 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001797 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001798
1799 /** @hide */
1800 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1801 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001802 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001803 if (end == -1) return defaultUserId;
1804 String userIdString = auth.substring(0, end);
1805 try {
1806 return Integer.parseInt(userIdString);
1807 } catch (NumberFormatException e) {
1808 Log.w(TAG, "Error parsing userId.", e);
1809 return UserHandle.USER_NULL;
1810 }
1811 }
1812
1813 /** @hide */
1814 public static int getUserIdFromAuthority(String auth) {
1815 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1816 }
1817
1818 /** @hide */
1819 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1820 if (uri == null) return defaultUserId;
1821 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1822 }
1823
1824 /** @hide */
1825 public static int getUserIdFromUri(Uri uri) {
1826 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1827 }
1828
1829 /**
1830 * Removes userId part from authority string. Expects format:
1831 * userId@some.authority
1832 * If there is no userId in the authority, it symply returns the argument
1833 * @hide
1834 */
1835 public static String getAuthorityWithoutUserId(String auth) {
1836 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001837 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001838 return auth.substring(end+1);
1839 }
1840
1841 /** @hide */
1842 public static Uri getUriWithoutUserId(Uri uri) {
1843 if (uri == null) return null;
1844 Uri.Builder builder = uri.buildUpon();
1845 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1846 return builder.build();
1847 }
1848
1849 /** @hide */
1850 public static boolean uriHasUserId(Uri uri) {
1851 if (uri == null) return false;
1852 return !TextUtils.isEmpty(uri.getUserInfo());
1853 }
1854
1855 /** @hide */
1856 public static Uri maybeAddUserId(Uri uri, int userId) {
1857 if (uri == null) return null;
1858 if (userId != UserHandle.USER_CURRENT
1859 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1860 if (!uriHasUserId(uri)) {
1861 //We don't add the user Id if there's already one
1862 Uri.Builder builder = uri.buildUpon();
1863 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1864 return builder.build();
1865 }
1866 }
1867 return uri;
1868 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001869}