blob: c8f9b7dd80e2b5021c12de596c90e31b9ad1d484 [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
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800518 final int callingUserId = UserHandle.getUserId(uid);
519 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
520 ? maybeAddUserId(uri, callingUserId) : uri;
521 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION)
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700522 == PERMISSION_GRANTED) {
523 return;
524 }
525
526 final String failReason = mExported
527 ? " requires " + missingPerm + ", or grantUriPermission()"
528 : " requires the provider be exported, or grantUriPermission()";
529 throw new SecurityException("Permission Denial: reading "
530 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
531 + ", uid=" + uid + failReason);
532 }
533
534 /** {@hide} */
535 protected void enforceWritePermissionInner(Uri uri) throws SecurityException {
536 final Context context = getContext();
537 final int pid = Binder.getCallingPid();
538 final int uid = Binder.getCallingUid();
539 String missingPerm = null;
540
541 if (UserHandle.isSameApp(uid, mMyUid)) {
542 return;
543 }
544
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100545 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700546 final String componentPerm = getWritePermission();
547 if (componentPerm != null) {
548 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
549 return;
550 } else {
551 missingPerm = componentPerm;
552 }
553 }
554
555 // track if unprotected write is allowed; any denied
556 // <path-permission> below removes this ability
557 boolean allowDefaultWrite = (componentPerm == null);
558
559 final PathPermission[] pps = getPathPermissions();
560 if (pps != null) {
561 final String path = uri.getPath();
562 for (PathPermission pp : pps) {
563 final String pathPerm = pp.getWritePermission();
564 if (pathPerm != null && pp.match(path)) {
565 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
566 return;
567 } else {
568 // any denied <path-permission> means we lose
569 // default <provider> access.
570 allowDefaultWrite = false;
571 missingPerm = pathPerm;
572 }
573 }
574 }
575 }
576
577 // if we passed <path-permission> checks above, and no default
578 // <provider> permission, then allow access.
579 if (allowDefaultWrite) return;
580 }
581
582 // last chance, check against any uri grants
583 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
584 == PERMISSION_GRANTED) {
585 return;
586 }
587
588 final String failReason = mExported
589 ? " requires " + missingPerm + ", or grantUriPermission()"
590 : " requires the provider be exported, or grantUriPermission()";
591 throw new SecurityException("Permission Denial: writing "
592 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
593 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 }
595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700597 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800598 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 * constructor.
600 */
601 public final Context getContext() {
602 return mContext;
603 }
604
605 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700606 * Set the calling package, returning the current value (or {@code null})
607 * which can be used later to restore the previous state.
608 */
609 private String setCallingPackage(String callingPackage) {
610 final String original = mCallingPackage.get();
611 mCallingPackage.set(callingPackage);
612 return original;
613 }
614
615 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700616 * Return the package name of the caller that initiated the request being
617 * processed on the current thread. The returned package will have been
618 * verified to belong to the calling UID. Returns {@code null} if not
619 * currently processing a request.
620 * <p>
621 * This will always return {@code null} when processing
622 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
623 *
624 * @see Binder#getCallingUid()
625 * @see Context#grantUriPermission(String, Uri, int)
626 * @throws SecurityException if the calling package doesn't belong to the
627 * calling UID.
628 */
629 public final String getCallingPackage() {
630 final String pkg = mCallingPackage.get();
631 if (pkg != null) {
632 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
633 }
634 return pkg;
635 }
636
637 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100638 * Change the authorities of the ContentProvider.
639 * This is normally set for you from its manifest information when the provider is first
640 * created.
641 * @hide
642 * @param authorities the semi-colon separated authorities of the ContentProvider.
643 */
644 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100645 if (authorities != null) {
646 if (authorities.indexOf(';') == -1) {
647 mAuthority = authorities;
648 mAuthorities = null;
649 } else {
650 mAuthority = null;
651 mAuthorities = authorities.split(";");
652 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100653 }
654 }
655
656 /** @hide */
657 protected final boolean matchesOurAuthorities(String authority) {
658 if (mAuthority != null) {
659 return mAuthority.equals(authority);
660 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100661 if (mAuthorities != null) {
662 int length = mAuthorities.length;
663 for (int i = 0; i < length; i++) {
664 if (mAuthorities[i].equals(authority)) return true;
665 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100666 }
667 return false;
668 }
669
670
671 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 * Change the permission required to read data from the content
673 * provider. This is normally set for you from its manifest information
674 * when the provider is first created.
675 *
676 * @param permission Name of the permission required for read-only access.
677 */
678 protected final void setReadPermission(String permission) {
679 mReadPermission = permission;
680 }
681
682 /**
683 * Return the name of the permission required for read-only access to
684 * this content provider. This method can be called from multiple
685 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800686 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
687 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 */
689 public final String getReadPermission() {
690 return mReadPermission;
691 }
692
693 /**
694 * Change the permission required to read and write data in the content
695 * provider. This is normally set for you from its manifest information
696 * when the provider is first created.
697 *
698 * @param permission Name of the permission required for read/write access.
699 */
700 protected final void setWritePermission(String permission) {
701 mWritePermission = permission;
702 }
703
704 /**
705 * Return the name of the permission required for read/write access to
706 * this content provider. This method can be called from multiple
707 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800708 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
709 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 */
711 public final String getWritePermission() {
712 return mWritePermission;
713 }
714
715 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700716 * Change the path-based permission required to read and/or write data in
717 * the content provider. This is normally set for you from its manifest
718 * information when the provider is first created.
719 *
720 * @param permissions Array of path permission descriptions.
721 */
722 protected final void setPathPermissions(PathPermission[] permissions) {
723 mPathPermissions = permissions;
724 }
725
726 /**
727 * Return the path-based permissions required for read and/or write access to
728 * this content provider. This method can be called from multiple
729 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800730 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
731 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700732 */
733 public final PathPermission[] getPathPermissions() {
734 return mPathPermissions;
735 }
736
Dianne Hackborn35654b62013-01-14 17:38:02 -0800737 /** @hide */
738 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800739 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800740 mTransport.mReadOp = readOp;
741 mTransport.mWriteOp = writeOp;
742 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800743 }
744
Dianne Hackborn961321f2013-02-05 17:22:41 -0800745 /** @hide */
746 public AppOpsManager getAppOpsManager() {
747 return mTransport.mAppOpsManager;
748 }
749
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700750 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700751 * Implement this to initialize your content provider on startup.
752 * This method is called for all registered content providers on the
753 * application main thread at application launch time. It must not perform
754 * lengthy operations, or application startup will be delayed.
755 *
756 * <p>You should defer nontrivial initialization (such as opening,
757 * upgrading, and scanning databases) until the content provider is used
758 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
759 * keeps application startup fast, avoids unnecessary work if the provider
760 * turns out not to be needed, and stops database errors (such as a full
761 * disk) from halting application launch.
762 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700763 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700764 * is a helpful utility class that makes it easy to manage databases,
765 * and will automatically defer opening until first use. If you do use
766 * SQLiteOpenHelper, make sure to avoid calling
767 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
768 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
769 * from this method. (Instead, override
770 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
771 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 *
773 * @return true if the provider was successfully loaded, false otherwise
774 */
775 public abstract boolean onCreate();
776
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700777 /**
778 * {@inheritDoc}
779 * This method is always called on the application main thread, and must
780 * not perform lengthy operations.
781 *
782 * <p>The default content provider implementation does nothing.
783 * Override this method to take appropriate action.
784 * (Content providers do not usually care about things like screen
785 * orientation, but may want to know about locale changes.)
786 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 public void onConfigurationChanged(Configuration newConfig) {
788 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700789
790 /**
791 * {@inheritDoc}
792 * This method is always called on the application main thread, and must
793 * not perform lengthy operations.
794 *
795 * <p>The default content provider implementation does nothing.
796 * Subclasses may override this method to take appropriate action.
797 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 public void onLowMemory() {
799 }
800
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700801 public void onTrimMemory(int level) {
802 }
803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800805 * @hide
806 * Implementation when a caller has performed a query on the content
807 * provider, but that call has been rejected for the operation given
808 * to {@link #setAppOps(int, int)}. The default implementation
809 * rewrites the <var>selection</var> argument to include a condition
810 * that is never true (so will always result in an empty cursor)
811 * and calls through to {@link #query(android.net.Uri, String[], String, String[],
812 * String, android.os.CancellationSignal)} with that.
813 */
814 public Cursor rejectQuery(Uri uri, String[] projection,
815 String selection, String[] selectionArgs, String sortOrder,
816 CancellationSignal cancellationSignal) {
817 // The read is not allowed... to fake it out, we replace the given
818 // selection statement with a dummy one that will always be false.
819 // This way we will get a cursor back that has the correct structure
820 // but contains no rows.
Dianne Hackborn9fa39bd2013-03-22 18:42:14 -0700821 if (selection == null || selection.isEmpty()) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800822 selection = "'A' = 'B'";
823 } else {
824 selection = "'A' = 'B' AND (" + selection + ")";
825 }
826 return query(uri, projection, selection, selectionArgs, sortOrder, cancellationSignal);
827 }
828
829 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700830 * Implement this to handle query requests from clients.
831 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800832 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
833 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 * <p>
835 * Example client call:<p>
836 * <pre>// Request a specific record.
837 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000838 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 projection, // Which columns to return.
840 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000841 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 People.NAME + " ASC"); // Sort order.</pre>
843 * Example implementation:<p>
844 * <pre>// SQLiteQueryBuilder is a helper class that creates the
845 // proper SQL syntax for us.
846 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
847
848 // Set the table we're querying.
849 qBuilder.setTables(DATABASE_TABLE_NAME);
850
851 // If the query ends in a specific record number, we're
852 // being asked for a specific record, so set the
853 // WHERE clause in our query.
854 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
855 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
856 }
857
858 // Make the query.
859 Cursor c = qBuilder.query(mDb,
860 projection,
861 selection,
862 selectionArgs,
863 groupBy,
864 having,
865 sortOrder);
866 c.setNotificationUri(getContext().getContentResolver(), uri);
867 return c;</pre>
868 *
869 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000870 * if the client is requesting a specific record, the URI will end in a record number
871 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
872 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800874 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800876 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000877 * @param selectionArgs You may include ?s in selection, which will be replaced by
878 * the values from selectionArgs, in order that they appear in the selection.
879 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800881 * If {@code null} then the provider is free to define the sort order.
882 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 */
884 public abstract Cursor query(Uri uri, String[] projection,
885 String selection, String[] selectionArgs, String sortOrder);
886
Fred Quintana5bba6322009-10-05 14:21:12 -0700887 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800888 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800889 * This method can be called from multiple threads, as described in
890 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
891 * and Threads</a>.
892 * <p>
893 * Example client call:<p>
894 * <pre>// Request a specific record.
895 * Cursor managedCursor = managedQuery(
896 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
897 projection, // Which columns to return.
898 null, // WHERE clause.
899 null, // WHERE clause value substitution
900 People.NAME + " ASC"); // Sort order.</pre>
901 * Example implementation:<p>
902 * <pre>// SQLiteQueryBuilder is a helper class that creates the
903 // proper SQL syntax for us.
904 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
905
906 // Set the table we're querying.
907 qBuilder.setTables(DATABASE_TABLE_NAME);
908
909 // If the query ends in a specific record number, we're
910 // being asked for a specific record, so set the
911 // WHERE clause in our query.
912 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
913 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
914 }
915
916 // Make the query.
917 Cursor c = qBuilder.query(mDb,
918 projection,
919 selection,
920 selectionArgs,
921 groupBy,
922 having,
923 sortOrder);
924 c.setNotificationUri(getContext().getContentResolver(), uri);
925 return c;</pre>
926 * <p>
927 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800928 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
929 * signal to ensure correct operation on older versions of the Android Framework in
930 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800931 *
932 * @param uri The URI to query. This will be the full URI sent by the client;
933 * if the client is requesting a specific record, the URI will end in a record number
934 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
935 * that _id value.
936 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800937 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800938 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800939 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800940 * @param selectionArgs You may include ?s in selection, which will be replaced by
941 * the values from selectionArgs, in order that they appear in the selection.
942 * The values will be bound as Strings.
943 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800944 * If {@code null} then the provider is free to define the sort order.
945 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800946 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
947 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800948 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800949 */
950 public Cursor query(Uri uri, String[] projection,
951 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800952 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800953 return query(uri, projection, selection, selectionArgs, sortOrder);
954 }
955
956 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700957 * Implement this to handle requests for the MIME type of the data at the
958 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 * <code>vnd.android.cursor.item</code> for a single record,
960 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700961 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800962 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
963 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700965 * <p>Note that there are no permissions needed for an application to
966 * access this information; if your content provider requires read and/or
967 * write permissions, or is not exported, all applications can still call
968 * this method regardless of their access permissions. This allows them
969 * to retrieve the MIME type for a URI when dispatching intents.
970 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800972 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 */
974 public abstract String getType(Uri uri);
975
976 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700977 * Implement this to support canonicalization of URIs that refer to your
978 * content provider. A canonical URI is one that can be transported across
979 * devices, backup/restore, and other contexts, and still be able to refer
980 * to the same data item. Typically this is implemented by adding query
981 * params to the URI allowing the content provider to verify that an incoming
982 * canonical URI references the same data as it was originally intended for and,
983 * if it doesn't, to find that data (if it exists) in the current environment.
984 *
985 * <p>For example, if the content provider holds people and a normal URI in it
986 * is created with a row index into that people database, the cananical representation
987 * may have an additional query param at the end which specifies the name of the
988 * person it is intended for. Later calls into the provider with that URI will look
989 * up the row of that URI's base index and, if it doesn't match or its entry's
990 * name doesn't match the name in the query param, perform a query on its database
991 * to find the correct row to operate on.</p>
992 *
993 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
994 * URIs (including this one) must perform this verification and recovery of any
995 * canonical URIs they receive. In addition, you must also implement
996 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
997 *
998 * <p>The default implementation of this method returns null, indicating that
999 * canonical URIs are not supported.</p>
1000 *
1001 * @param url The Uri to canonicalize.
1002 *
1003 * @return Return the canonical representation of <var>url</var>, or null if
1004 * canonicalization of that Uri is not supported.
1005 */
1006 public Uri canonicalize(Uri url) {
1007 return null;
1008 }
1009
1010 /**
1011 * Remove canonicalization from canonical URIs previously returned by
1012 * {@link #canonicalize}. For example, if your implementation is to add
1013 * a query param to canonicalize a URI, this method can simply trip any
1014 * query params on the URI. The default implementation always returns the
1015 * same <var>url</var> that was passed in.
1016 *
1017 * @param url The Uri to remove any canonicalization from.
1018 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001019 * @return Return the non-canonical representation of <var>url</var>, return
1020 * the <var>url</var> as-is if there is nothing to do, or return null if
1021 * the data identified by the canonical representation can not be found in
1022 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001023 */
1024 public Uri uncanonicalize(Uri url) {
1025 return url;
1026 }
1027
1028 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001029 * @hide
1030 * Implementation when a caller has performed an insert on the content
1031 * provider, but that call has been rejected for the operation given
1032 * to {@link #setAppOps(int, int)}. The default implementation simply
1033 * returns a dummy URI that is the base URI with a 0 path element
1034 * appended.
1035 */
1036 public Uri rejectInsert(Uri uri, ContentValues values) {
1037 // If not allowed, we need to return some reasonable URI. Maybe the
1038 // content provider should be responsible for this, but for now we
1039 // will just return the base URI with a dummy '0' tagged on to it.
1040 // You shouldn't be able to read if you can't write, anyway, so it
1041 // shouldn't matter much what is returned.
1042 return uri.buildUpon().appendPath("0").build();
1043 }
1044
1045 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001046 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1048 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001049 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001050 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1051 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001052 * @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 -08001053 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001054 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 * @return The URI for the newly inserted item.
1056 */
1057 public abstract Uri insert(Uri uri, ContentValues values);
1058
1059 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001060 * Override this to handle requests to insert a set of new rows, or the
1061 * default implementation will iterate over the values and call
1062 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1064 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001065 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001066 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1067 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 *
1069 * @param uri The content:// URI of the insertion request.
1070 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001071 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 * @return The number of values that were inserted.
1073 */
1074 public int bulkInsert(Uri uri, ContentValues[] values) {
1075 int numValues = values.length;
1076 for (int i = 0; i < numValues; i++) {
1077 insert(uri, values[i]);
1078 }
1079 return numValues;
1080 }
1081
1082 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001083 * Implement this to handle requests to delete one or more rows.
1084 * The implementation should apply the selection clause when performing
1085 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001086 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001088 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001089 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1090 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 *
1092 * <p>The implementation is responsible for parsing out a row ID at the end
1093 * of the URI, if a specific row is being deleted. That is, the client would
1094 * pass in <code>content://contacts/people/22</code> and the implementation is
1095 * responsible for parsing the record number (22) when creating a SQL statement.
1096 *
1097 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1098 * @param selection An optional restriction to apply to rows when deleting.
1099 * @return The number of rows affected.
1100 * @throws SQLException
1101 */
1102 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
1103
1104 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001105 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001106 * The implementation should update all rows matching the selection
1107 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1109 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001110 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001111 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1112 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 *
1114 * @param uri The URI to query. This can potentially have a record ID if this
1115 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001116 * @param values A set of column_name/value pairs to update in the database.
1117 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 * @param selection An optional filter to match rows to update.
1119 * @return the number of rows affected.
1120 */
1121 public abstract int update(Uri uri, ContentValues values, String selection,
1122 String[] selectionArgs);
1123
1124 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001125 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001126 * The default implementation always throws {@link FileNotFoundException}.
1127 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001128 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1129 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001130 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001131 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1132 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001133 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 *
1135 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1136 * their responsibility to close it when done. That is, the implementation
1137 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001138 * <p>
1139 * If opened with the exclusive "r" or "w" modes, the returned
1140 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1141 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1142 * supports seeking.
1143 * <p>
1144 * If you need to detect when the returned ParcelFileDescriptor has been
1145 * closed, or if the remote process has crashed or encountered some other
1146 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1147 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1148 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1149 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001151 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1152 * to return the appropriate MIME type for the data returned here with
1153 * the same URI. This will allow intent resolution to automatically determine the data MIME
1154 * type and select the appropriate matching targets as part of its operation.</p>
1155 *
1156 * <p class="note">For better interoperability with other applications, it is recommended
1157 * that for any URIs that can be opened, you also support queries on them
1158 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1159 * You may also want to support other common columns if you have additional meta-data
1160 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1161 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1162 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 * @param uri The URI whose file is to be opened.
1164 * @param mode Access mode for the file. May be "r" for read-only access,
1165 * "rw" for read and write access, or "rwt" for read and write access
1166 * that truncates any existing file.
1167 *
1168 * @return Returns a new ParcelFileDescriptor which you can use to access
1169 * the file.
1170 *
1171 * @throws FileNotFoundException Throws FileNotFoundException if there is
1172 * no file associated with the given URI or the mode is invalid.
1173 * @throws SecurityException Throws SecurityException if the caller does
1174 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001175 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 * @see #openAssetFile(Uri, String)
1177 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001178 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001179 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001180 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 public ParcelFileDescriptor openFile(Uri uri, String mode)
1182 throws FileNotFoundException {
1183 throw new FileNotFoundException("No files supported by provider at "
1184 + uri);
1185 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001188 * Override this to handle requests to open a file blob.
1189 * The default implementation always throws {@link FileNotFoundException}.
1190 * This method can be called from multiple threads, as described in
1191 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1192 * and Threads</a>.
1193 *
1194 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1195 * to the caller. This way large data (such as images and documents) can be
1196 * returned without copying the content.
1197 *
1198 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1199 * their responsibility to close it when done. That is, the implementation
1200 * of this method should create a new ParcelFileDescriptor for each call.
1201 * <p>
1202 * If opened with the exclusive "r" or "w" modes, the returned
1203 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1204 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1205 * supports seeking.
1206 * <p>
1207 * If you need to detect when the returned ParcelFileDescriptor has been
1208 * closed, or if the remote process has crashed or encountered some other
1209 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1210 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1211 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1212 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1213 *
1214 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1215 * to return the appropriate MIME type for the data returned here with
1216 * the same URI. This will allow intent resolution to automatically determine the data MIME
1217 * type and select the appropriate matching targets as part of its operation.</p>
1218 *
1219 * <p class="note">For better interoperability with other applications, it is recommended
1220 * that for any URIs that can be opened, you also support queries on them
1221 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1222 * You may also want to support other common columns if you have additional meta-data
1223 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1224 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1225 *
1226 * @param uri The URI whose file is to be opened.
1227 * @param mode Access mode for the file. May be "r" for read-only access,
1228 * "w" for write-only access, "rw" for read and write access, or
1229 * "rwt" for read and write access that truncates any existing
1230 * file.
1231 * @param signal A signal to cancel the operation in progress, or
1232 * {@code null} if none. For example, if you are downloading a
1233 * file from the network to service a "rw" mode request, you
1234 * should periodically call
1235 * {@link CancellationSignal#throwIfCanceled()} to check whether
1236 * the client has canceled the request and abort the download.
1237 *
1238 * @return Returns a new ParcelFileDescriptor which you can use to access
1239 * the file.
1240 *
1241 * @throws FileNotFoundException Throws FileNotFoundException if there is
1242 * no file associated with the given URI or the mode is invalid.
1243 * @throws SecurityException Throws SecurityException if the caller does
1244 * not have permission to access the file.
1245 *
1246 * @see #openAssetFile(Uri, String)
1247 * @see #openFileHelper(Uri, String)
1248 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001249 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001250 */
1251 public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
1252 throws FileNotFoundException {
1253 return openFile(uri, mode);
1254 }
1255
1256 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 * This is like {@link #openFile}, but can be implemented by providers
1258 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001259 * inside of their .apk.
1260 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001261 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1262 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001263 *
1264 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001265 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001266 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1268 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1269 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001270 * <p>
1271 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1272 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001273 *
1274 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 * should create the AssetFileDescriptor with
1276 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001277 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001279 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1280 * to return the appropriate MIME type for the data returned here with
1281 * the same URI. This will allow intent resolution to automatically determine the data MIME
1282 * type and select the appropriate matching targets as part of its operation.</p>
1283 *
1284 * <p class="note">For better interoperability with other applications, it is recommended
1285 * that for any URIs that can be opened, you also support queries on them
1286 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1287 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 * @param uri The URI whose file is to be opened.
1289 * @param mode Access mode for the file. May be "r" for read-only access,
1290 * "w" for write-only access (erasing whatever data is currently in
1291 * the file), "wa" for write-only access to append to any existing data,
1292 * "rw" for read and write access on any existing data, and "rwt" for read
1293 * and write access that truncates any existing file.
1294 *
1295 * @return Returns a new AssetFileDescriptor which you can use to access
1296 * the file.
1297 *
1298 * @throws FileNotFoundException Throws FileNotFoundException if there is
1299 * no file associated with the given URI or the mode is invalid.
1300 * @throws SecurityException Throws SecurityException if the caller does
1301 * not have permission to access the file.
1302 *
1303 * @see #openFile(Uri, String)
1304 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001305 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 */
1307 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
1308 throws FileNotFoundException {
1309 ParcelFileDescriptor fd = openFile(uri, mode);
1310 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1311 }
1312
1313 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001314 * This is like {@link #openFile}, but can be implemented by providers
1315 * that need to be able to return sub-sections of files, often assets
1316 * inside of their .apk.
1317 * This method can be called from multiple threads, as described in
1318 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1319 * and Threads</a>.
1320 *
1321 * <p>If you implement this, your clients must be able to deal with such
1322 * file slices, either directly with
1323 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1324 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1325 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1326 * methods.
1327 * <p>
1328 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1329 * streaming of data.
1330 *
1331 * <p class="note">If you are implementing this to return a full file, you
1332 * should create the AssetFileDescriptor with
1333 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1334 * applications that cannot handle sub-sections of files.</p>
1335 *
1336 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1337 * to return the appropriate MIME type for the data returned here with
1338 * the same URI. This will allow intent resolution to automatically determine the data MIME
1339 * type and select the appropriate matching targets as part of its operation.</p>
1340 *
1341 * <p class="note">For better interoperability with other applications, it is recommended
1342 * that for any URIs that can be opened, you also support queries on them
1343 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1344 *
1345 * @param uri The URI whose file is to be opened.
1346 * @param mode Access mode for the file. May be "r" for read-only access,
1347 * "w" for write-only access (erasing whatever data is currently in
1348 * the file), "wa" for write-only access to append to any existing data,
1349 * "rw" for read and write access on any existing data, and "rwt" for read
1350 * and write access that truncates any existing file.
1351 * @param signal A signal to cancel the operation in progress, or
1352 * {@code null} if none. For example, if you are downloading a
1353 * file from the network to service a "rw" mode request, you
1354 * should periodically call
1355 * {@link CancellationSignal#throwIfCanceled()} to check whether
1356 * the client has canceled the request and abort the download.
1357 *
1358 * @return Returns a new AssetFileDescriptor which you can use to access
1359 * the file.
1360 *
1361 * @throws FileNotFoundException Throws FileNotFoundException if there is
1362 * no file associated with the given URI or the mode is invalid.
1363 * @throws SecurityException Throws SecurityException if the caller does
1364 * not have permission to access the file.
1365 *
1366 * @see #openFile(Uri, String)
1367 * @see #openFileHelper(Uri, String)
1368 * @see #getType(android.net.Uri)
1369 */
1370 public AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)
1371 throws FileNotFoundException {
1372 return openAssetFile(uri, mode);
1373 }
1374
1375 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 * Convenience for subclasses that wish to implement {@link #openFile}
1377 * by looking up a column named "_data" at the given URI.
1378 *
1379 * @param uri The URI to be opened.
1380 * @param mode The file mode. May be "r" for read-only access,
1381 * "w" for write-only access (erasing whatever data is currently in
1382 * the file), "wa" for write-only access to append to any existing data,
1383 * "rw" for read and write access on any existing data, and "rwt" for read
1384 * and write access that truncates any existing file.
1385 *
1386 * @return Returns a new ParcelFileDescriptor that can be used by the
1387 * client to access the file.
1388 */
1389 protected final ParcelFileDescriptor openFileHelper(Uri uri,
1390 String mode) throws FileNotFoundException {
1391 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1392 int count = (c != null) ? c.getCount() : 0;
1393 if (count != 1) {
1394 // If there is not exactly one result, throw an appropriate
1395 // exception.
1396 if (c != null) {
1397 c.close();
1398 }
1399 if (count == 0) {
1400 throw new FileNotFoundException("No entry for " + uri);
1401 }
1402 throw new FileNotFoundException("Multiple items at " + uri);
1403 }
1404
1405 c.moveToFirst();
1406 int i = c.getColumnIndex("_data");
1407 String path = (i >= 0 ? c.getString(i) : null);
1408 c.close();
1409 if (path == null) {
1410 throw new FileNotFoundException("Column _data not found.");
1411 }
1412
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001413 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 return ParcelFileDescriptor.open(new File(path), modeBits);
1415 }
1416
1417 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001418 * Called by a client to determine the types of data streams that this
1419 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001420 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001421 * of a particular type, return that MIME type if it matches the given
1422 * mimeTypeFilter. If it can perform type conversions, return an array
1423 * of all supported MIME types that match mimeTypeFilter.
1424 *
1425 * @param uri The data in the content provider being queried.
1426 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001427 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001428 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001429 * given mimeTypeFilter. Otherwise returns an array of all available
1430 * concrete MIME types.
1431 *
1432 * @see #getType(Uri)
1433 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001434 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001435 */
1436 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
1437 return null;
1438 }
1439
1440 /**
1441 * Called by a client to open a read-only stream containing data of a
1442 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1443 * except the file can only be read-only and the content provider may
1444 * perform data conversions to generate data of the desired type.
1445 *
1446 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001447 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001448 * {@link #openAssetFile(Uri, String)}.
1449 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001450 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001451 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001452 * <p>
1453 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1454 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001455 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001456 * <p class="note">For better interoperability with other applications, it is recommended
1457 * that for any URIs that can be opened, you also support queries on them
1458 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1459 * You may also want to support other common columns if you have additional meta-data
1460 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1461 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1462 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001463 * @param uri The data in the content provider being queried.
1464 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001465 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001466 * requirements; in this case the content provider will pick its best
1467 * type matching the pattern.
1468 * @param opts Additional options from the client. The definitions of
1469 * these are specific to the content provider being called.
1470 *
1471 * @return Returns a new AssetFileDescriptor from which the client can
1472 * read data of the desired type.
1473 *
1474 * @throws FileNotFoundException Throws FileNotFoundException if there is
1475 * no file associated with the given URI or the mode is invalid.
1476 * @throws SecurityException Throws SecurityException if the caller does
1477 * not have permission to access the data.
1478 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1479 * content provider does not support the requested MIME type.
1480 *
1481 * @see #getStreamTypes(Uri, String)
1482 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001483 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001484 */
1485 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
1486 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001487 if ("*/*".equals(mimeTypeFilter)) {
1488 // If they can take anything, the untyped open call is good enough.
1489 return openAssetFile(uri, "r");
1490 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001491 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001492 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001493 // Use old untyped open call if this provider has a type for this
1494 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001495 return openAssetFile(uri, "r");
1496 }
1497 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1498 }
1499
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001500
1501 /**
1502 * Called by a client to open a read-only stream containing data of a
1503 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1504 * except the file can only be read-only and the content provider may
1505 * perform data conversions to generate data of the desired type.
1506 *
1507 * <p>The default implementation compares the given mimeType against the
1508 * result of {@link #getType(Uri)} and, if they match, simply calls
1509 * {@link #openAssetFile(Uri, String)}.
1510 *
1511 * <p>See {@link ClipData} for examples of the use and implementation
1512 * of this method.
1513 * <p>
1514 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1515 * streaming of data.
1516 *
1517 * <p class="note">For better interoperability with other applications, it is recommended
1518 * that for any URIs that can be opened, you also support queries on them
1519 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1520 * You may also want to support other common columns if you have additional meta-data
1521 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1522 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1523 *
1524 * @param uri The data in the content provider being queried.
1525 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001526 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001527 * requirements; in this case the content provider will pick its best
1528 * type matching the pattern.
1529 * @param opts Additional options from the client. The definitions of
1530 * these are specific to the content provider being called.
1531 * @param signal A signal to cancel the operation in progress, or
1532 * {@code null} if none. For example, if you are downloading a
1533 * file from the network to service a "rw" mode request, you
1534 * should periodically call
1535 * {@link CancellationSignal#throwIfCanceled()} to check whether
1536 * the client has canceled the request and abort the download.
1537 *
1538 * @return Returns a new AssetFileDescriptor from which the client can
1539 * read data of the desired type.
1540 *
1541 * @throws FileNotFoundException Throws FileNotFoundException if there is
1542 * no file associated with the given URI or the mode is invalid.
1543 * @throws SecurityException Throws SecurityException if the caller does
1544 * not have permission to access the data.
1545 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1546 * content provider does not support the requested MIME type.
1547 *
1548 * @see #getStreamTypes(Uri, String)
1549 * @see #openAssetFile(Uri, String)
1550 * @see ClipDescription#compareMimeTypes(String, String)
1551 */
1552 public AssetFileDescriptor openTypedAssetFile(
1553 Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)
1554 throws FileNotFoundException {
1555 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1556 }
1557
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001558 /**
1559 * Interface to write a stream of data to a pipe. Use with
1560 * {@link ContentProvider#openPipeHelper}.
1561 */
1562 public interface PipeDataWriter<T> {
1563 /**
1564 * Called from a background thread to stream data out to a pipe.
1565 * Note that the pipe is blocking, so this thread can block on
1566 * writes for an arbitrary amount of time if the client is slow
1567 * at reading.
1568 *
1569 * @param output The pipe where data should be written. This will be
1570 * closed for you upon returning from this function.
1571 * @param uri The URI whose data is to be written.
1572 * @param mimeType The desired type of data to be written.
1573 * @param opts Options supplied by caller.
1574 * @param args Your own custom arguments.
1575 */
1576 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
1577 Bundle opts, T args);
1578 }
1579
1580 /**
1581 * A helper function for implementing {@link #openTypedAssetFile}, for
1582 * creating a data pipe and background thread allowing you to stream
1583 * generated data back to the client. This function returns a new
1584 * ParcelFileDescriptor that should be returned to the caller (the caller
1585 * is responsible for closing it).
1586 *
1587 * @param uri The URI whose data is to be written.
1588 * @param mimeType The desired type of data to be written.
1589 * @param opts Options supplied by caller.
1590 * @param args Your own custom arguments.
1591 * @param func Interface implementing the function that will actually
1592 * stream the data.
1593 * @return Returns a new ParcelFileDescriptor holding the read side of
1594 * the pipe. This should be returned to the caller for reading; the caller
1595 * is responsible for closing it when done.
1596 */
1597 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
1598 final Bundle opts, final T args, final PipeDataWriter<T> func)
1599 throws FileNotFoundException {
1600 try {
1601 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1602
1603 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1604 @Override
1605 protected Object doInBackground(Object... params) {
1606 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1607 try {
1608 fds[1].close();
1609 } catch (IOException e) {
1610 Log.w(TAG, "Failure closing pipe", e);
1611 }
1612 return null;
1613 }
1614 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001615 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001616
1617 return fds[0];
1618 } catch (IOException e) {
1619 throw new FileNotFoundException("failure making pipe");
1620 }
1621 }
1622
1623 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 * Returns true if this instance is a temporary content provider.
1625 * @return true if this instance is a temporary content provider
1626 */
1627 protected boolean isTemporary() {
1628 return false;
1629 }
1630
1631 /**
1632 * Returns the Binder object for this provider.
1633 *
1634 * @return the Binder object for this provider
1635 * @hide
1636 */
1637 public IContentProvider getIContentProvider() {
1638 return mTransport;
1639 }
1640
1641 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001642 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1643 * when directly instantiating the provider for testing.
1644 * @hide
1645 */
1646 public void attachInfoForTesting(Context context, ProviderInfo info) {
1647 attachInfo(context, info, true);
1648 }
1649
1650 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 * After being instantiated, this is called to tell the content provider
1652 * about itself.
1653 *
1654 * @param context The context this provider is running in
1655 * @param info Registered information about this content provider
1656 */
1657 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001658 attachInfo(context, info, false);
1659 }
1660
1661 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001662 /*
1663 * We may be using AsyncTask from binder threads. Make it init here
1664 * so its static handler is on the main thread.
1665 */
1666 AsyncTask.init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001668 mNoPerms = testing;
1669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 /*
1671 * Only allow it to be set once, so after the content service gives
1672 * this to us clients can't change it.
1673 */
1674 if (mContext == null) {
1675 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001676 if (context != null) {
1677 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1678 Context.APP_OPS_SERVICE);
1679 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001680 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 if (info != null) {
1682 setReadPermission(info.readPermission);
1683 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001684 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001685 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001686 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001687 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
1689 ContentProvider.this.onCreate();
1690 }
1691 }
Fred Quintanace31b232009-05-04 16:01:15 -07001692
1693 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001694 * Override this to handle requests to perform a batch of operations, or the
1695 * default implementation will iterate over the operations and call
1696 * {@link ContentProviderOperation#apply} on each of them.
1697 * If all calls to {@link ContentProviderOperation#apply} succeed
1698 * then a {@link ContentProviderResult} array with as many
1699 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001700 * fail, it is up to the implementation how many of the others take effect.
1701 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001702 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1703 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001704 *
Fred Quintanace31b232009-05-04 16:01:15 -07001705 * @param operations the operations to apply
1706 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001707 * @throws OperationApplicationException thrown if any operation fails.
1708 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001709 */
Fred Quintana03d94902009-05-22 14:23:31 -07001710 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001711 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001712 final int numOperations = operations.size();
1713 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1714 for (int i = 0; i < numOperations; i++) {
1715 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001716 }
1717 return results;
1718 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001719
1720 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001721 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001722 * interfaces that are cheaper and/or unnatural for a table-like
1723 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001724 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001725 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1726 * on this entry into the content provider besides the basic ability for the application
1727 * to get access to the provider at all. For example, it has no idea whether the call
1728 * being executed may read or write data in the provider, so can't enforce those
1729 * individual permissions. Any implementation of this method <strong>must</strong>
1730 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1731 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001732 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1733 * @param arg provider-defined String argument. May be {@code null}.
1734 * @param extras provider-defined Bundle argument. May be {@code null}.
1735 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001736 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001737 */
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001738 public Bundle call(String method, String arg, Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001739 return null;
1740 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001741
1742 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001743 * Implement this to shut down the ContentProvider instance. You can then
1744 * invoke this method in unit tests.
1745 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001746 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001747 * Android normally handles ContentProvider startup and shutdown
1748 * automatically. You do not need to start up or shut down a
1749 * ContentProvider. When you invoke a test method on a ContentProvider,
1750 * however, a ContentProvider instance is started and keeps running after
1751 * the test finishes, even if a succeeding test instantiates another
1752 * ContentProvider. A conflict develops because the two instances are
1753 * usually running against the same underlying data source (for example, an
1754 * sqlite database).
1755 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001756 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001757 * Implementing shutDown() avoids this conflict by providing a way to
1758 * terminate the ContentProvider. This method can also prevent memory leaks
1759 * from multiple instantiations of the ContentProvider, and it can ensure
1760 * unit test isolation by allowing you to completely clean up the test
1761 * fixture before moving on to the next test.
1762 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001763 */
1764 public void shutdown() {
1765 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1766 "connections are gracefully shutdown");
1767 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001768
1769 /**
1770 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001771 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001772 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001773 * @param fd The raw file descriptor that the dump is being sent to.
1774 * @param writer The PrintWriter to which you should dump your state. This will be
1775 * closed for you after you return.
1776 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001777 */
1778 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1779 writer.println("nothing to dump");
1780 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001781
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001782 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001783 private void validateIncomingUri(Uri uri) throws SecurityException {
1784 String auth = uri.getAuthority();
1785 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001786 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
1787 throw new SecurityException("trying to query a ContentProvider in user "
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001788 + mContext.getUserId() + " with a uri belonging to user " + userId);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001789 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001790 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
1791 String message = "The authority of the uri " + uri + " does not match the one of the "
1792 + "contentProvider: ";
1793 if (mAuthority != null) {
1794 message += mAuthority;
1795 } else {
1796 message += mAuthorities;
1797 }
1798 throw new SecurityException(message);
1799 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001800 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001801
1802 /** @hide */
1803 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1804 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001805 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001806 if (end == -1) return defaultUserId;
1807 String userIdString = auth.substring(0, end);
1808 try {
1809 return Integer.parseInt(userIdString);
1810 } catch (NumberFormatException e) {
1811 Log.w(TAG, "Error parsing userId.", e);
1812 return UserHandle.USER_NULL;
1813 }
1814 }
1815
1816 /** @hide */
1817 public static int getUserIdFromAuthority(String auth) {
1818 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1819 }
1820
1821 /** @hide */
1822 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1823 if (uri == null) return defaultUserId;
1824 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1825 }
1826
1827 /** @hide */
1828 public static int getUserIdFromUri(Uri uri) {
1829 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1830 }
1831
1832 /**
1833 * Removes userId part from authority string. Expects format:
1834 * userId@some.authority
1835 * If there is no userId in the authority, it symply returns the argument
1836 * @hide
1837 */
1838 public static String getAuthorityWithoutUserId(String auth) {
1839 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001840 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001841 return auth.substring(end+1);
1842 }
1843
1844 /** @hide */
1845 public static Uri getUriWithoutUserId(Uri uri) {
1846 if (uri == null) return null;
1847 Uri.Builder builder = uri.buildUpon();
1848 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1849 return builder.build();
1850 }
1851
1852 /** @hide */
1853 public static boolean uriHasUserId(Uri uri) {
1854 if (uri == null) return false;
1855 return !TextUtils.isEmpty(uri.getUserInfo());
1856 }
1857
1858 /** @hide */
1859 public static Uri maybeAddUserId(Uri uri, int userId) {
1860 if (uri == null) return null;
1861 if (userId != UserHandle.USER_CURRENT
1862 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1863 if (!uriHasUserId(uri)) {
1864 //We don't add the user Id if there's already one
1865 Uri.Builder builder = uri.buildUpon();
1866 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1867 return builder.build();
1868 }
1869 }
1870 return uri;
1871 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001872}