blob: fde8b2e0c9d9019b3ba6128c13629048fb38c16e [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.content;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Nicolas Prevot504d78e2014-06-26 10:07:33 +010020import static android.Manifest.permission.INTERACT_ACROSS_USERS;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070021
Dianne Hackborn35654b62013-01-14 17:38:02 -080022import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070023import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.pm.ProviderInfo;
25import android.content.res.AssetFileDescriptor;
26import android.content.res.Configuration;
27import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.database.SQLException;
29import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070030import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080032import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070033import android.os.CancellationSignal;
34import android.os.ICancellationSignal;
35import android.os.OperationCanceledException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070037import android.os.Process;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070038import android.os.UserHandle;
Vasu Nori0c9e14a2010-08-04 13:31:48 -070039import android.util.Log;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010040import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041
42import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080043import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070045import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080046import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070047import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048
49/**
50 * Content providers are one of the primary building blocks of Android applications, providing
51 * content to applications. They encapsulate data and provide it to applications through the single
52 * {@link ContentResolver} interface. A content provider is only required if you need to share
53 * data between multiple applications. For example, the contacts data is used by multiple
54 * applications and must be stored in a content provider. If you don't need to share data amongst
55 * multiple applications you can use a database directly via
56 * {@link android.database.sqlite.SQLiteDatabase}.
57 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058 * <p>When a request is made via
59 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
60 * request to the content provider registered with the authority. The content provider can interpret
61 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
62 * URIs.</p>
63 *
64 * <p>The primary methods that need to be implemented are:
65 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070066 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 * <li>{@link #query} which returns data to the caller</li>
68 * <li>{@link #insert} which inserts new data into the content provider</li>
69 * <li>{@link #update} which updates existing data in the content provider</li>
70 * <li>{@link #delete} which deletes data from the content provider</li>
71 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
72 * </ul></p>
73 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070074 * <p class="caution">Data access methods (such as {@link #insert} and
75 * {@link #update}) may be called from many threads at once, and must be thread-safe.
76 * Other methods (such as {@link #onCreate}) are only called from the application
77 * main thread, and must avoid performing lengthy operations. See the method
78 * descriptions for their expected thread behavior.</p>
79 *
80 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
81 * ContentProvider instance, so subclasses don't have to worry about the details of
82 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070083 *
84 * <div class="special reference">
85 * <h3>Developer Guides</h3>
86 * <p>For more information about using content providers, read the
87 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
88 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -070090public abstract class ContentProvider implements ComponentCallbacks2 {
Vasu Nori0c9e14a2010-08-04 13:31:48 -070091 private static final String TAG = "ContentProvider";
92
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +090093 /*
94 * Note: if you add methods to ContentProvider, you must add similar methods to
95 * MockContentProvider.
96 */
97
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070099 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100100
101 // Since most Providers have only one authority, we keep both a String and a String[] to improve
102 // performance.
103 private String mAuthority;
104 private String[] mAuthorities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 private String mReadPermission;
106 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700107 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700108 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800109 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700110 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700112 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<String>();
113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 private Transport mTransport = new Transport();
115
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700116 /**
117 * Construct a ContentProvider instance. Content providers must be
118 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
119 * in the manifest</a>, accessed with {@link ContentResolver}, and created
120 * automatically by the system, so applications usually do not create
121 * ContentProvider instances directly.
122 *
123 * <p>At construction time, the object is uninitialized, and most fields and
124 * methods are unavailable. Subclasses should initialize themselves in
125 * {@link #onCreate}, not the constructor.
126 *
127 * <p>Content providers are created on the application main thread at
128 * application launch time. The constructor must not perform lengthy
129 * operations, or application startup will be delayed.
130 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900131 public ContentProvider() {
132 }
133
134 /**
135 * Constructor just for mocking.
136 *
137 * @param context A Context object which should be some mock instance (like the
138 * instance of {@link android.test.mock.MockContext}).
139 * @param readPermission The read permision you want this instance should have in the
140 * test, which is available via {@link #getReadPermission()}.
141 * @param writePermission The write permission you want this instance should have
142 * in the test, which is available via {@link #getWritePermission()}.
143 * @param pathPermissions The PathPermissions you want this instance should have
144 * in the test, which is available via {@link #getPathPermissions()}.
145 * @hide
146 */
147 public ContentProvider(
148 Context context,
149 String readPermission,
150 String writePermission,
151 PathPermission[] pathPermissions) {
152 mContext = context;
153 mReadPermission = readPermission;
154 mWritePermission = writePermission;
155 mPathPermissions = pathPermissions;
156 }
157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 /**
159 * Given an IContentProvider, try to coerce it back to the real
160 * ContentProvider object if it is running in the local process. This can
161 * be used if you know you are running in the same process as a provider,
162 * and want to get direct access to its implementation details. Most
163 * clients should not nor have a reason to use it.
164 *
165 * @param abstractInterface The ContentProvider interface that is to be
166 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800167 * @return If the IContentProvider is non-{@code null} and local, returns its actual
168 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 * @hide
170 */
171 public static ContentProvider coerceToLocalContentProvider(
172 IContentProvider abstractInterface) {
173 if (abstractInterface instanceof Transport) {
174 return ((Transport)abstractInterface).getContentProvider();
175 }
176 return null;
177 }
178
179 /**
180 * Binder object that deals with remoting.
181 *
182 * @hide
183 */
184 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800185 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800186 int mReadOp = AppOpsManager.OP_NONE;
187 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 ContentProvider getContentProvider() {
190 return ContentProvider.this;
191 }
192
Jeff Brownd2183652011-10-09 12:39:53 -0700193 @Override
194 public String getProviderName() {
195 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196 }
197
Jeff Brown75ea64f2012-01-25 19:37:13 -0800198 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800199 public Cursor query(String callingPkg, Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800200 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800201 ICancellationSignal cancellationSignal) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100202 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100203 uri = getUriWithoutUserId(uri);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800204 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800205 return rejectQuery(uri, projection, selection, selectionArgs, sortOrder,
206 CancellationSignal.fromTransport(cancellationSignal));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800207 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700208 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700209 try {
210 return ContentProvider.this.query(
211 uri, projection, selection, selectionArgs, sortOrder,
212 CancellationSignal.fromTransport(cancellationSignal));
213 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700214 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 }
217
Jeff Brown75ea64f2012-01-25 19:37:13 -0800218 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100220 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100221 uri = getUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 return ContentProvider.this.getType(uri);
223 }
224
Jeff Brown75ea64f2012-01-25 19:37:13 -0800225 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800226 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100227 validateIncomingUri(uri);
228 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100229 uri = getUriWithoutUserId(uri);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800230 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800231 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800232 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700233 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700234 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100235 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700236 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700237 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 }
240
Jeff Brown75ea64f2012-01-25 19:37:13 -0800241 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800242 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100243 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100244 uri = getUriWithoutUserId(uri);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800245 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
246 return 0;
247 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700248 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700249 try {
250 return ContentProvider.this.bulkInsert(uri, initialValues);
251 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700252 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 }
255
Jeff Brown75ea64f2012-01-25 19:37:13 -0800256 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800257 public ContentProviderResult[] applyBatch(String callingPkg,
258 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700259 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100260 int numOperations = operations.size();
261 final int[] userIds = new int[numOperations];
262 for (int i = 0; i < numOperations; i++) {
263 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100264 Uri uri = operation.getUri();
265 validateIncomingUri(uri);
266 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100267 if (userIds[i] != UserHandle.USER_CURRENT) {
268 // Removing the user id from the uri.
269 operation = new ContentProviderOperation(operation, true);
270 operations.set(i, operation);
271 }
Fred Quintana89437372009-05-15 15:10:40 -0700272 if (operation.isReadOperation()) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100273 if (enforceReadPermission(callingPkg, uri)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800274 != AppOpsManager.MODE_ALLOWED) {
275 throw new OperationApplicationException("App op not allowed", 0);
276 }
Fred Quintana89437372009-05-15 15:10:40 -0700277 }
Fred Quintana89437372009-05-15 15:10:40 -0700278 if (operation.isWriteOperation()) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100279 if (enforceWritePermission(callingPkg, uri)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800280 != AppOpsManager.MODE_ALLOWED) {
281 throw new OperationApplicationException("App op not allowed", 0);
282 }
Fred Quintana89437372009-05-15 15:10:40 -0700283 }
284 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700285 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700286 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100287 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
288 for (int i = 0; i < results.length ; i++) {
289 if (userIds[i] != UserHandle.USER_CURRENT) {
290 // Adding the userId to the uri.
291 results[i] = new ContentProviderResult(results[i], userIds[i]);
292 }
293 }
294 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700295 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700296 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700297 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700298 }
299
Jeff Brown75ea64f2012-01-25 19:37:13 -0800300 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800301 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100302 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100303 uri = getUriWithoutUserId(uri);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800304 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
305 return 0;
306 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700307 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700308 try {
309 return ContentProvider.this.delete(uri, selection, selectionArgs);
310 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700311 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 }
314
Jeff Brown75ea64f2012-01-25 19:37:13 -0800315 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800316 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100318 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100319 uri = getUriWithoutUserId(uri);
Dianne Hackborn35654b62013-01-14 17:38:02 -0800320 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
321 return 0;
322 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700323 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700324 try {
325 return ContentProvider.this.update(uri, values, selection, selectionArgs);
326 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700327 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 }
330
Jeff Brown75ea64f2012-01-25 19:37:13 -0800331 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700332 public ParcelFileDescriptor openFile(
333 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100335 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100336 uri = getUriWithoutUserId(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100337 enforceFilePermission(callingPkg, uri, mode);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700338 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700339 try {
340 return ContentProvider.this.openFile(
341 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
342 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700343 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800345 }
346
Jeff Brown75ea64f2012-01-25 19:37:13 -0800347 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700348 public AssetFileDescriptor openAssetFile(
349 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100351 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100352 uri = getUriWithoutUserId(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100353 enforceFilePermission(callingPkg, uri, mode);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700354 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700355 try {
356 return ContentProvider.this.openAssetFile(
357 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
358 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700359 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800361 }
362
Jeff Brown75ea64f2012-01-25 19:37:13 -0800363 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800364 public Bundle call(String callingPkg, String method, String arg, Bundle extras) {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700365 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700366 try {
367 return ContentProvider.this.call(method, arg, extras);
368 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700369 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700370 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800371 }
372
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700373 @Override
374 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100375 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100376 uri = getUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700377 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
378 }
379
380 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800381 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700382 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100383 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100384 uri = getUriWithoutUserId(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100385 enforceFilePermission(callingPkg, uri, "r");
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700386 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700387 try {
388 return ContentProvider.this.openTypedAssetFile(
389 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
390 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700391 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700392 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700393 }
394
Jeff Brown75ea64f2012-01-25 19:37:13 -0800395 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700396 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800397 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800398 }
399
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700400 @Override
401 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100402 validateIncomingUri(uri);
403 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100404 uri = getUriWithoutUserId(uri);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700405 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
406 return null;
407 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700408 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700409 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100410 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700411 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700412 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700413 }
414 }
415
416 @Override
417 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100418 validateIncomingUri(uri);
419 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100420 uri = getUriWithoutUserId(uri);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700421 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
422 return null;
423 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700424 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700425 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100426 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700427 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700428 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700429 }
430 }
431
Dianne Hackborn35654b62013-01-14 17:38:02 -0800432 private void enforceFilePermission(String callingPkg, Uri uri, String mode)
433 throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800434 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800435 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
436 throw new FileNotFoundException("App op not allowed");
437 }
438 } else {
439 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
440 throw new FileNotFoundException("App op not allowed");
441 }
442 }
443 }
444
445 private int enforceReadPermission(String callingPkg, Uri uri) throws SecurityException {
446 enforceReadPermissionInner(uri);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800447 if (mReadOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800448 return mAppOpsManager.noteOp(mReadOp, Binder.getCallingUid(), callingPkg);
449 }
450 return AppOpsManager.MODE_ALLOWED;
451 }
452
Dianne Hackborn35654b62013-01-14 17:38:02 -0800453 private int enforceWritePermission(String callingPkg, Uri uri) throws SecurityException {
454 enforceWritePermissionInner(uri);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800455 if (mWriteOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800456 return mAppOpsManager.noteOp(mWriteOp, Binder.getCallingUid(), callingPkg);
457 }
458 return AppOpsManager.MODE_ALLOWED;
459 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700460 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800461
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100462 boolean checkUser(int pid, int uid, Context context) {
463 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700464 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100465 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
466 == PERMISSION_GRANTED;
467 }
468
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700469 /** {@hide} */
470 protected void enforceReadPermissionInner(Uri uri) throws SecurityException {
471 final Context context = getContext();
472 final int pid = Binder.getCallingPid();
473 final int uid = Binder.getCallingUid();
474 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700475
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700476 if (UserHandle.isSameApp(uid, mMyUid)) {
477 return;
478 }
479
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100480 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700481 final String componentPerm = getReadPermission();
482 if (componentPerm != null) {
483 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
484 return;
485 } else {
486 missingPerm = componentPerm;
487 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700488 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700489
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700490 // track if unprotected read is allowed; any denied
491 // <path-permission> below removes this ability
492 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700493
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700494 final PathPermission[] pps = getPathPermissions();
495 if (pps != null) {
496 final String path = uri.getPath();
497 for (PathPermission pp : pps) {
498 final String pathPerm = pp.getReadPermission();
499 if (pathPerm != null && pp.match(path)) {
500 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
501 return;
502 } else {
503 // any denied <path-permission> means we lose
504 // default <provider> access.
505 allowDefaultRead = false;
506 missingPerm = pathPerm;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700507 }
508 }
509 }
510 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700511
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700512 // if we passed <path-permission> checks above, and no default
513 // <provider> permission, then allow access.
514 if (allowDefaultRead) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800515 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700516
517 // last chance, check against any uri grants
518 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION)
519 == PERMISSION_GRANTED) {
520 return;
521 }
522
523 final String failReason = mExported
524 ? " requires " + missingPerm + ", or grantUriPermission()"
525 : " requires the provider be exported, or grantUriPermission()";
526 throw new SecurityException("Permission Denial: reading "
527 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
528 + ", uid=" + uid + failReason);
529 }
530
531 /** {@hide} */
532 protected void enforceWritePermissionInner(Uri uri) throws SecurityException {
533 final Context context = getContext();
534 final int pid = Binder.getCallingPid();
535 final int uid = Binder.getCallingUid();
536 String missingPerm = null;
537
538 if (UserHandle.isSameApp(uid, mMyUid)) {
539 return;
540 }
541
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100542 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700543 final String componentPerm = getWritePermission();
544 if (componentPerm != null) {
545 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
546 return;
547 } else {
548 missingPerm = componentPerm;
549 }
550 }
551
552 // track if unprotected write is allowed; any denied
553 // <path-permission> below removes this ability
554 boolean allowDefaultWrite = (componentPerm == null);
555
556 final PathPermission[] pps = getPathPermissions();
557 if (pps != null) {
558 final String path = uri.getPath();
559 for (PathPermission pp : pps) {
560 final String pathPerm = pp.getWritePermission();
561 if (pathPerm != null && pp.match(path)) {
562 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
563 return;
564 } else {
565 // any denied <path-permission> means we lose
566 // default <provider> access.
567 allowDefaultWrite = false;
568 missingPerm = pathPerm;
569 }
570 }
571 }
572 }
573
574 // if we passed <path-permission> checks above, and no default
575 // <provider> permission, then allow access.
576 if (allowDefaultWrite) return;
577 }
578
579 // last chance, check against any uri grants
580 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
581 == PERMISSION_GRANTED) {
582 return;
583 }
584
585 final String failReason = mExported
586 ? " requires " + missingPerm + ", or grantUriPermission()"
587 : " requires the provider be exported, or grantUriPermission()";
588 throw new SecurityException("Permission Denial: writing "
589 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
590 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 }
592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700594 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800595 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 * constructor.
597 */
598 public final Context getContext() {
599 return mContext;
600 }
601
602 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700603 * Set the calling package, returning the current value (or {@code null})
604 * which can be used later to restore the previous state.
605 */
606 private String setCallingPackage(String callingPackage) {
607 final String original = mCallingPackage.get();
608 mCallingPackage.set(callingPackage);
609 return original;
610 }
611
612 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700613 * Return the package name of the caller that initiated the request being
614 * processed on the current thread. The returned package will have been
615 * verified to belong to the calling UID. Returns {@code null} if not
616 * currently processing a request.
617 * <p>
618 * This will always return {@code null} when processing
619 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
620 *
621 * @see Binder#getCallingUid()
622 * @see Context#grantUriPermission(String, Uri, int)
623 * @throws SecurityException if the calling package doesn't belong to the
624 * calling UID.
625 */
626 public final String getCallingPackage() {
627 final String pkg = mCallingPackage.get();
628 if (pkg != null) {
629 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
630 }
631 return pkg;
632 }
633
634 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100635 * Change the authorities of the ContentProvider.
636 * This is normally set for you from its manifest information when the provider is first
637 * created.
638 * @hide
639 * @param authorities the semi-colon separated authorities of the ContentProvider.
640 */
641 protected final void setAuthorities(String authorities) {
642 if (authorities.indexOf(';') == -1) {
643 mAuthority = authorities;
644 mAuthorities = null;
645 } else {
646 mAuthority = null;
647 mAuthorities = authorities.split(";");
648 }
649 }
650
651 /** @hide */
652 protected final boolean matchesOurAuthorities(String authority) {
653 if (mAuthority != null) {
654 return mAuthority.equals(authority);
655 }
656 int length = mAuthorities.length;
657 for (int i = 0; i < length; i++) {
658 if (mAuthorities[i].equals(authority)) return true;
659 }
660 return false;
661 }
662
663
664 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 * Change the permission required to read data from the content
666 * provider. This is normally set for you from its manifest information
667 * when the provider is first created.
668 *
669 * @param permission Name of the permission required for read-only access.
670 */
671 protected final void setReadPermission(String permission) {
672 mReadPermission = permission;
673 }
674
675 /**
676 * Return the name of the permission required for read-only access to
677 * this content provider. This method can be called from multiple
678 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800679 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
680 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 */
682 public final String getReadPermission() {
683 return mReadPermission;
684 }
685
686 /**
687 * Change the permission required to read and write data in the content
688 * provider. This is normally set for you from its manifest information
689 * when the provider is first created.
690 *
691 * @param permission Name of the permission required for read/write access.
692 */
693 protected final void setWritePermission(String permission) {
694 mWritePermission = permission;
695 }
696
697 /**
698 * Return the name of the permission required for read/write access to
699 * this content provider. This method can be called from multiple
700 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800701 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
702 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 */
704 public final String getWritePermission() {
705 return mWritePermission;
706 }
707
708 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700709 * Change the path-based permission required to read and/or write data in
710 * the content provider. This is normally set for you from its manifest
711 * information when the provider is first created.
712 *
713 * @param permissions Array of path permission descriptions.
714 */
715 protected final void setPathPermissions(PathPermission[] permissions) {
716 mPathPermissions = permissions;
717 }
718
719 /**
720 * Return the path-based permissions required for read and/or write access to
721 * this content provider. This method can be called from multiple
722 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800723 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
724 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700725 */
726 public final PathPermission[] getPathPermissions() {
727 return mPathPermissions;
728 }
729
Dianne Hackborn35654b62013-01-14 17:38:02 -0800730 /** @hide */
731 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800732 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800733 mTransport.mReadOp = readOp;
734 mTransport.mWriteOp = writeOp;
735 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800736 }
737
Dianne Hackborn961321f2013-02-05 17:22:41 -0800738 /** @hide */
739 public AppOpsManager getAppOpsManager() {
740 return mTransport.mAppOpsManager;
741 }
742
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700743 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700744 * Implement this to initialize your content provider on startup.
745 * This method is called for all registered content providers on the
746 * application main thread at application launch time. It must not perform
747 * lengthy operations, or application startup will be delayed.
748 *
749 * <p>You should defer nontrivial initialization (such as opening,
750 * upgrading, and scanning databases) until the content provider is used
751 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
752 * keeps application startup fast, avoids unnecessary work if the provider
753 * turns out not to be needed, and stops database errors (such as a full
754 * disk) from halting application launch.
755 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700756 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700757 * is a helpful utility class that makes it easy to manage databases,
758 * and will automatically defer opening until first use. If you do use
759 * SQLiteOpenHelper, make sure to avoid calling
760 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
761 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
762 * from this method. (Instead, override
763 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
764 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 *
766 * @return true if the provider was successfully loaded, false otherwise
767 */
768 public abstract boolean onCreate();
769
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700770 /**
771 * {@inheritDoc}
772 * This method is always called on the application main thread, and must
773 * not perform lengthy operations.
774 *
775 * <p>The default content provider implementation does nothing.
776 * Override this method to take appropriate action.
777 * (Content providers do not usually care about things like screen
778 * orientation, but may want to know about locale changes.)
779 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 public void onConfigurationChanged(Configuration newConfig) {
781 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700782
783 /**
784 * {@inheritDoc}
785 * This method is always called on the application main thread, and must
786 * not perform lengthy operations.
787 *
788 * <p>The default content provider implementation does nothing.
789 * Subclasses may override this method to take appropriate action.
790 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 public void onLowMemory() {
792 }
793
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700794 public void onTrimMemory(int level) {
795 }
796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800798 * @hide
799 * Implementation when a caller has performed a query on the content
800 * provider, but that call has been rejected for the operation given
801 * to {@link #setAppOps(int, int)}. The default implementation
802 * rewrites the <var>selection</var> argument to include a condition
803 * that is never true (so will always result in an empty cursor)
804 * and calls through to {@link #query(android.net.Uri, String[], String, String[],
805 * String, android.os.CancellationSignal)} with that.
806 */
807 public Cursor rejectQuery(Uri uri, String[] projection,
808 String selection, String[] selectionArgs, String sortOrder,
809 CancellationSignal cancellationSignal) {
810 // The read is not allowed... to fake it out, we replace the given
811 // selection statement with a dummy one that will always be false.
812 // This way we will get a cursor back that has the correct structure
813 // but contains no rows.
Dianne Hackborn9fa39bd2013-03-22 18:42:14 -0700814 if (selection == null || selection.isEmpty()) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800815 selection = "'A' = 'B'";
816 } else {
817 selection = "'A' = 'B' AND (" + selection + ")";
818 }
819 return query(uri, projection, selection, selectionArgs, sortOrder, cancellationSignal);
820 }
821
822 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700823 * Implement this to handle query requests from clients.
824 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800825 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
826 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 * <p>
828 * Example client call:<p>
829 * <pre>// Request a specific record.
830 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000831 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 projection, // Which columns to return.
833 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000834 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 People.NAME + " ASC"); // Sort order.</pre>
836 * Example implementation:<p>
837 * <pre>// SQLiteQueryBuilder is a helper class that creates the
838 // proper SQL syntax for us.
839 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
840
841 // Set the table we're querying.
842 qBuilder.setTables(DATABASE_TABLE_NAME);
843
844 // If the query ends in a specific record number, we're
845 // being asked for a specific record, so set the
846 // WHERE clause in our query.
847 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
848 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
849 }
850
851 // Make the query.
852 Cursor c = qBuilder.query(mDb,
853 projection,
854 selection,
855 selectionArgs,
856 groupBy,
857 having,
858 sortOrder);
859 c.setNotificationUri(getContext().getContentResolver(), uri);
860 return c;</pre>
861 *
862 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000863 * if the client is requesting a specific record, the URI will end in a record number
864 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
865 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800867 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800869 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000870 * @param selectionArgs You may include ?s in selection, which will be replaced by
871 * the values from selectionArgs, in order that they appear in the selection.
872 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800874 * If {@code null} then the provider is free to define the sort order.
875 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 */
877 public abstract Cursor query(Uri uri, String[] projection,
878 String selection, String[] selectionArgs, String sortOrder);
879
Fred Quintana5bba6322009-10-05 14:21:12 -0700880 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800881 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800882 * This method can be called from multiple threads, as described in
883 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
884 * and Threads</a>.
885 * <p>
886 * Example client call:<p>
887 * <pre>// Request a specific record.
888 * Cursor managedCursor = managedQuery(
889 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
890 projection, // Which columns to return.
891 null, // WHERE clause.
892 null, // WHERE clause value substitution
893 People.NAME + " ASC"); // Sort order.</pre>
894 * Example implementation:<p>
895 * <pre>// SQLiteQueryBuilder is a helper class that creates the
896 // proper SQL syntax for us.
897 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
898
899 // Set the table we're querying.
900 qBuilder.setTables(DATABASE_TABLE_NAME);
901
902 // If the query ends in a specific record number, we're
903 // being asked for a specific record, so set the
904 // WHERE clause in our query.
905 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
906 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
907 }
908
909 // Make the query.
910 Cursor c = qBuilder.query(mDb,
911 projection,
912 selection,
913 selectionArgs,
914 groupBy,
915 having,
916 sortOrder);
917 c.setNotificationUri(getContext().getContentResolver(), uri);
918 return c;</pre>
919 * <p>
920 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800921 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
922 * signal to ensure correct operation on older versions of the Android Framework in
923 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800924 *
925 * @param uri The URI to query. This will be the full URI sent by the client;
926 * if the client is requesting a specific record, the URI will end in a record number
927 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
928 * that _id value.
929 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800930 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800931 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800932 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800933 * @param selectionArgs You may include ?s in selection, which will be replaced by
934 * the values from selectionArgs, in order that they appear in the selection.
935 * The values will be bound as Strings.
936 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800937 * If {@code null} then the provider is free to define the sort order.
938 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800939 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
940 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800941 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800942 */
943 public Cursor query(Uri uri, String[] projection,
944 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800945 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800946 return query(uri, projection, selection, selectionArgs, sortOrder);
947 }
948
949 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700950 * Implement this to handle requests for the MIME type of the data at the
951 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 * <code>vnd.android.cursor.item</code> for a single record,
953 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700954 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800955 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
956 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700958 * <p>Note that there are no permissions needed for an application to
959 * access this information; if your content provider requires read and/or
960 * write permissions, or is not exported, all applications can still call
961 * this method regardless of their access permissions. This allows them
962 * to retrieve the MIME type for a URI when dispatching intents.
963 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800965 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 */
967 public abstract String getType(Uri uri);
968
969 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700970 * Implement this to support canonicalization of URIs that refer to your
971 * content provider. A canonical URI is one that can be transported across
972 * devices, backup/restore, and other contexts, and still be able to refer
973 * to the same data item. Typically this is implemented by adding query
974 * params to the URI allowing the content provider to verify that an incoming
975 * canonical URI references the same data as it was originally intended for and,
976 * if it doesn't, to find that data (if it exists) in the current environment.
977 *
978 * <p>For example, if the content provider holds people and a normal URI in it
979 * is created with a row index into that people database, the cananical representation
980 * may have an additional query param at the end which specifies the name of the
981 * person it is intended for. Later calls into the provider with that URI will look
982 * up the row of that URI's base index and, if it doesn't match or its entry's
983 * name doesn't match the name in the query param, perform a query on its database
984 * to find the correct row to operate on.</p>
985 *
986 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
987 * URIs (including this one) must perform this verification and recovery of any
988 * canonical URIs they receive. In addition, you must also implement
989 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
990 *
991 * <p>The default implementation of this method returns null, indicating that
992 * canonical URIs are not supported.</p>
993 *
994 * @param url The Uri to canonicalize.
995 *
996 * @return Return the canonical representation of <var>url</var>, or null if
997 * canonicalization of that Uri is not supported.
998 */
999 public Uri canonicalize(Uri url) {
1000 return null;
1001 }
1002
1003 /**
1004 * Remove canonicalization from canonical URIs previously returned by
1005 * {@link #canonicalize}. For example, if your implementation is to add
1006 * a query param to canonicalize a URI, this method can simply trip any
1007 * query params on the URI. The default implementation always returns the
1008 * same <var>url</var> that was passed in.
1009 *
1010 * @param url The Uri to remove any canonicalization from.
1011 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001012 * @return Return the non-canonical representation of <var>url</var>, return
1013 * the <var>url</var> as-is if there is nothing to do, or return null if
1014 * the data identified by the canonical representation can not be found in
1015 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001016 */
1017 public Uri uncanonicalize(Uri url) {
1018 return url;
1019 }
1020
1021 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001022 * @hide
1023 * Implementation when a caller has performed an insert on the content
1024 * provider, but that call has been rejected for the operation given
1025 * to {@link #setAppOps(int, int)}. The default implementation simply
1026 * returns a dummy URI that is the base URI with a 0 path element
1027 * appended.
1028 */
1029 public Uri rejectInsert(Uri uri, ContentValues values) {
1030 // If not allowed, we need to return some reasonable URI. Maybe the
1031 // content provider should be responsible for this, but for now we
1032 // will just return the base URI with a dummy '0' tagged on to it.
1033 // You shouldn't be able to read if you can't write, anyway, so it
1034 // shouldn't matter much what is returned.
1035 return uri.buildUpon().appendPath("0").build();
1036 }
1037
1038 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001039 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1041 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001042 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001043 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1044 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001045 * @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 -08001046 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001047 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 * @return The URI for the newly inserted item.
1049 */
1050 public abstract Uri insert(Uri uri, ContentValues values);
1051
1052 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001053 * Override this to handle requests to insert a set of new rows, or the
1054 * default implementation will iterate over the values and call
1055 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1057 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001058 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001059 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1060 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 *
1062 * @param uri The content:// URI of the insertion request.
1063 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001064 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 * @return The number of values that were inserted.
1066 */
1067 public int bulkInsert(Uri uri, ContentValues[] values) {
1068 int numValues = values.length;
1069 for (int i = 0; i < numValues; i++) {
1070 insert(uri, values[i]);
1071 }
1072 return numValues;
1073 }
1074
1075 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001076 * Implement this to handle requests to delete one or more rows.
1077 * The implementation should apply the selection clause when performing
1078 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001079 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001081 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001082 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1083 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 *
1085 * <p>The implementation is responsible for parsing out a row ID at the end
1086 * of the URI, if a specific row is being deleted. That is, the client would
1087 * pass in <code>content://contacts/people/22</code> and the implementation is
1088 * responsible for parsing the record number (22) when creating a SQL statement.
1089 *
1090 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1091 * @param selection An optional restriction to apply to rows when deleting.
1092 * @return The number of rows affected.
1093 * @throws SQLException
1094 */
1095 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
1096
1097 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001098 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001099 * The implementation should update all rows matching the selection
1100 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1102 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001103 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001104 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1105 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 *
1107 * @param uri The URI to query. This can potentially have a record ID if this
1108 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001109 * @param values A set of column_name/value pairs to update in the database.
1110 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 * @param selection An optional filter to match rows to update.
1112 * @return the number of rows affected.
1113 */
1114 public abstract int update(Uri uri, ContentValues values, String selection,
1115 String[] selectionArgs);
1116
1117 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001118 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001119 * The default implementation always throws {@link FileNotFoundException}.
1120 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001121 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1122 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001123 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001124 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1125 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001126 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 *
1128 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1129 * their responsibility to close it when done. That is, the implementation
1130 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001131 * <p>
1132 * If opened with the exclusive "r" or "w" modes, the returned
1133 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1134 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1135 * supports seeking.
1136 * <p>
1137 * If you need to detect when the returned ParcelFileDescriptor has been
1138 * closed, or if the remote process has crashed or encountered some other
1139 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1140 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1141 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1142 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001144 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1145 * to return the appropriate MIME type for the data returned here with
1146 * the same URI. This will allow intent resolution to automatically determine the data MIME
1147 * type and select the appropriate matching targets as part of its operation.</p>
1148 *
1149 * <p class="note">For better interoperability with other applications, it is recommended
1150 * that for any URIs that can be opened, you also support queries on them
1151 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1152 * You may also want to support other common columns if you have additional meta-data
1153 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1154 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1155 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 * @param uri The URI whose file is to be opened.
1157 * @param mode Access mode for the file. May be "r" for read-only access,
1158 * "rw" for read and write access, or "rwt" for read and write access
1159 * that truncates any existing file.
1160 *
1161 * @return Returns a new ParcelFileDescriptor which you can use to access
1162 * the file.
1163 *
1164 * @throws FileNotFoundException Throws FileNotFoundException if there is
1165 * no file associated with the given URI or the mode is invalid.
1166 * @throws SecurityException Throws SecurityException if the caller does
1167 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001168 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001169 * @see #openAssetFile(Uri, String)
1170 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001171 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001172 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001173 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 public ParcelFileDescriptor openFile(Uri uri, String mode)
1175 throws FileNotFoundException {
1176 throw new FileNotFoundException("No files supported by provider at "
1177 + uri);
1178 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001181 * Override this to handle requests to open a file blob.
1182 * The default implementation always throws {@link FileNotFoundException}.
1183 * This method can be called from multiple threads, as described in
1184 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1185 * and Threads</a>.
1186 *
1187 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1188 * to the caller. This way large data (such as images and documents) can be
1189 * returned without copying the content.
1190 *
1191 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1192 * their responsibility to close it when done. That is, the implementation
1193 * of this method should create a new ParcelFileDescriptor for each call.
1194 * <p>
1195 * If opened with the exclusive "r" or "w" modes, the returned
1196 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1197 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1198 * supports seeking.
1199 * <p>
1200 * If you need to detect when the returned ParcelFileDescriptor has been
1201 * closed, or if the remote process has crashed or encountered some other
1202 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1203 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1204 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1205 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1206 *
1207 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1208 * to return the appropriate MIME type for the data returned here with
1209 * the same URI. This will allow intent resolution to automatically determine the data MIME
1210 * type and select the appropriate matching targets as part of its operation.</p>
1211 *
1212 * <p class="note">For better interoperability with other applications, it is recommended
1213 * that for any URIs that can be opened, you also support queries on them
1214 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1215 * You may also want to support other common columns if you have additional meta-data
1216 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1217 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1218 *
1219 * @param uri The URI whose file is to be opened.
1220 * @param mode Access mode for the file. May be "r" for read-only access,
1221 * "w" for write-only access, "rw" for read and write access, or
1222 * "rwt" for read and write access that truncates any existing
1223 * file.
1224 * @param signal A signal to cancel the operation in progress, or
1225 * {@code null} if none. For example, if you are downloading a
1226 * file from the network to service a "rw" mode request, you
1227 * should periodically call
1228 * {@link CancellationSignal#throwIfCanceled()} to check whether
1229 * the client has canceled the request and abort the download.
1230 *
1231 * @return Returns a new ParcelFileDescriptor which you can use to access
1232 * the file.
1233 *
1234 * @throws FileNotFoundException Throws FileNotFoundException if there is
1235 * no file associated with the given URI or the mode is invalid.
1236 * @throws SecurityException Throws SecurityException if the caller does
1237 * not have permission to access the file.
1238 *
1239 * @see #openAssetFile(Uri, String)
1240 * @see #openFileHelper(Uri, String)
1241 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001242 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001243 */
1244 public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
1245 throws FileNotFoundException {
1246 return openFile(uri, mode);
1247 }
1248
1249 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 * This is like {@link #openFile}, but can be implemented by providers
1251 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001252 * inside of their .apk.
1253 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001254 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1255 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001256 *
1257 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001258 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001259 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1261 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1262 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001263 * <p>
1264 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1265 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001266 *
1267 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 * should create the AssetFileDescriptor with
1269 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001270 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001272 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1273 * to return the appropriate MIME type for the data returned here with
1274 * the same URI. This will allow intent resolution to automatically determine the data MIME
1275 * type and select the appropriate matching targets as part of its operation.</p>
1276 *
1277 * <p class="note">For better interoperability with other applications, it is recommended
1278 * that for any URIs that can be opened, you also support queries on them
1279 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1280 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 * @param uri The URI whose file is to be opened.
1282 * @param mode Access mode for the file. May be "r" for read-only access,
1283 * "w" for write-only access (erasing whatever data is currently in
1284 * the file), "wa" for write-only access to append to any existing data,
1285 * "rw" for read and write access on any existing data, and "rwt" for read
1286 * and write access that truncates any existing file.
1287 *
1288 * @return Returns a new AssetFileDescriptor which you can use to access
1289 * the file.
1290 *
1291 * @throws FileNotFoundException Throws FileNotFoundException if there is
1292 * no file associated with the given URI or the mode is invalid.
1293 * @throws SecurityException Throws SecurityException if the caller does
1294 * not have permission to access the file.
1295 *
1296 * @see #openFile(Uri, String)
1297 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001298 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 */
1300 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
1301 throws FileNotFoundException {
1302 ParcelFileDescriptor fd = openFile(uri, mode);
1303 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1304 }
1305
1306 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001307 * This is like {@link #openFile}, but can be implemented by providers
1308 * that need to be able to return sub-sections of files, often assets
1309 * inside of their .apk.
1310 * This method can be called from multiple threads, as described in
1311 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1312 * and Threads</a>.
1313 *
1314 * <p>If you implement this, your clients must be able to deal with such
1315 * file slices, either directly with
1316 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1317 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1318 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1319 * methods.
1320 * <p>
1321 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1322 * streaming of data.
1323 *
1324 * <p class="note">If you are implementing this to return a full file, you
1325 * should create the AssetFileDescriptor with
1326 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1327 * applications that cannot handle sub-sections of files.</p>
1328 *
1329 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1330 * to return the appropriate MIME type for the data returned here with
1331 * the same URI. This will allow intent resolution to automatically determine the data MIME
1332 * type and select the appropriate matching targets as part of its operation.</p>
1333 *
1334 * <p class="note">For better interoperability with other applications, it is recommended
1335 * that for any URIs that can be opened, you also support queries on them
1336 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1337 *
1338 * @param uri The URI whose file is to be opened.
1339 * @param mode Access mode for the file. May be "r" for read-only access,
1340 * "w" for write-only access (erasing whatever data is currently in
1341 * the file), "wa" for write-only access to append to any existing data,
1342 * "rw" for read and write access on any existing data, and "rwt" for read
1343 * and write access that truncates any existing file.
1344 * @param signal A signal to cancel the operation in progress, or
1345 * {@code null} if none. For example, if you are downloading a
1346 * file from the network to service a "rw" mode request, you
1347 * should periodically call
1348 * {@link CancellationSignal#throwIfCanceled()} to check whether
1349 * the client has canceled the request and abort the download.
1350 *
1351 * @return Returns a new AssetFileDescriptor which you can use to access
1352 * the file.
1353 *
1354 * @throws FileNotFoundException Throws FileNotFoundException if there is
1355 * no file associated with the given URI or the mode is invalid.
1356 * @throws SecurityException Throws SecurityException if the caller does
1357 * not have permission to access the file.
1358 *
1359 * @see #openFile(Uri, String)
1360 * @see #openFileHelper(Uri, String)
1361 * @see #getType(android.net.Uri)
1362 */
1363 public AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)
1364 throws FileNotFoundException {
1365 return openAssetFile(uri, mode);
1366 }
1367
1368 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 * Convenience for subclasses that wish to implement {@link #openFile}
1370 * by looking up a column named "_data" at the given URI.
1371 *
1372 * @param uri The URI to be opened.
1373 * @param mode The file mode. May be "r" for read-only access,
1374 * "w" for write-only access (erasing whatever data is currently in
1375 * the file), "wa" for write-only access to append to any existing data,
1376 * "rw" for read and write access on any existing data, and "rwt" for read
1377 * and write access that truncates any existing file.
1378 *
1379 * @return Returns a new ParcelFileDescriptor that can be used by the
1380 * client to access the file.
1381 */
1382 protected final ParcelFileDescriptor openFileHelper(Uri uri,
1383 String mode) throws FileNotFoundException {
1384 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1385 int count = (c != null) ? c.getCount() : 0;
1386 if (count != 1) {
1387 // If there is not exactly one result, throw an appropriate
1388 // exception.
1389 if (c != null) {
1390 c.close();
1391 }
1392 if (count == 0) {
1393 throw new FileNotFoundException("No entry for " + uri);
1394 }
1395 throw new FileNotFoundException("Multiple items at " + uri);
1396 }
1397
1398 c.moveToFirst();
1399 int i = c.getColumnIndex("_data");
1400 String path = (i >= 0 ? c.getString(i) : null);
1401 c.close();
1402 if (path == null) {
1403 throw new FileNotFoundException("Column _data not found.");
1404 }
1405
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001406 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 return ParcelFileDescriptor.open(new File(path), modeBits);
1408 }
1409
1410 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001411 * Called by a client to determine the types of data streams that this
1412 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001413 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001414 * of a particular type, return that MIME type if it matches the given
1415 * mimeTypeFilter. If it can perform type conversions, return an array
1416 * of all supported MIME types that match mimeTypeFilter.
1417 *
1418 * @param uri The data in the content provider being queried.
1419 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001420 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001421 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001422 * given mimeTypeFilter. Otherwise returns an array of all available
1423 * concrete MIME types.
1424 *
1425 * @see #getType(Uri)
1426 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001427 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001428 */
1429 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
1430 return null;
1431 }
1432
1433 /**
1434 * Called by a client to open a read-only stream containing data of a
1435 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1436 * except the file can only be read-only and the content provider may
1437 * perform data conversions to generate data of the desired type.
1438 *
1439 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001440 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001441 * {@link #openAssetFile(Uri, String)}.
1442 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001443 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001444 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001445 * <p>
1446 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1447 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001448 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001449 * <p class="note">For better interoperability with other applications, it is recommended
1450 * that for any URIs that can be opened, you also support queries on them
1451 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1452 * You may also want to support other common columns if you have additional meta-data
1453 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1454 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1455 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001456 * @param uri The data in the content provider being queried.
1457 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001458 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001459 * requirements; in this case the content provider will pick its best
1460 * type matching the pattern.
1461 * @param opts Additional options from the client. The definitions of
1462 * these are specific to the content provider being called.
1463 *
1464 * @return Returns a new AssetFileDescriptor from which the client can
1465 * read data of the desired type.
1466 *
1467 * @throws FileNotFoundException Throws FileNotFoundException if there is
1468 * no file associated with the given URI or the mode is invalid.
1469 * @throws SecurityException Throws SecurityException if the caller does
1470 * not have permission to access the data.
1471 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1472 * content provider does not support the requested MIME type.
1473 *
1474 * @see #getStreamTypes(Uri, String)
1475 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001476 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001477 */
1478 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
1479 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001480 if ("*/*".equals(mimeTypeFilter)) {
1481 // If they can take anything, the untyped open call is good enough.
1482 return openAssetFile(uri, "r");
1483 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001484 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001485 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001486 // Use old untyped open call if this provider has a type for this
1487 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001488 return openAssetFile(uri, "r");
1489 }
1490 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1491 }
1492
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001493
1494 /**
1495 * Called by a client to open a read-only stream containing data of a
1496 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1497 * except the file can only be read-only and the content provider may
1498 * perform data conversions to generate data of the desired type.
1499 *
1500 * <p>The default implementation compares the given mimeType against the
1501 * result of {@link #getType(Uri)} and, if they match, simply calls
1502 * {@link #openAssetFile(Uri, String)}.
1503 *
1504 * <p>See {@link ClipData} for examples of the use and implementation
1505 * of this method.
1506 * <p>
1507 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1508 * streaming of data.
1509 *
1510 * <p class="note">For better interoperability with other applications, it is recommended
1511 * that for any URIs that can be opened, you also support queries on them
1512 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1513 * You may also want to support other common columns if you have additional meta-data
1514 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1515 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1516 *
1517 * @param uri The data in the content provider being queried.
1518 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001519 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001520 * requirements; in this case the content provider will pick its best
1521 * type matching the pattern.
1522 * @param opts Additional options from the client. The definitions of
1523 * these are specific to the content provider being called.
1524 * @param signal A signal to cancel the operation in progress, or
1525 * {@code null} if none. For example, if you are downloading a
1526 * file from the network to service a "rw" mode request, you
1527 * should periodically call
1528 * {@link CancellationSignal#throwIfCanceled()} to check whether
1529 * the client has canceled the request and abort the download.
1530 *
1531 * @return Returns a new AssetFileDescriptor from which the client can
1532 * read data of the desired type.
1533 *
1534 * @throws FileNotFoundException Throws FileNotFoundException if there is
1535 * no file associated with the given URI or the mode is invalid.
1536 * @throws SecurityException Throws SecurityException if the caller does
1537 * not have permission to access the data.
1538 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1539 * content provider does not support the requested MIME type.
1540 *
1541 * @see #getStreamTypes(Uri, String)
1542 * @see #openAssetFile(Uri, String)
1543 * @see ClipDescription#compareMimeTypes(String, String)
1544 */
1545 public AssetFileDescriptor openTypedAssetFile(
1546 Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)
1547 throws FileNotFoundException {
1548 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1549 }
1550
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001551 /**
1552 * Interface to write a stream of data to a pipe. Use with
1553 * {@link ContentProvider#openPipeHelper}.
1554 */
1555 public interface PipeDataWriter<T> {
1556 /**
1557 * Called from a background thread to stream data out to a pipe.
1558 * Note that the pipe is blocking, so this thread can block on
1559 * writes for an arbitrary amount of time if the client is slow
1560 * at reading.
1561 *
1562 * @param output The pipe where data should be written. This will be
1563 * closed for you upon returning from this function.
1564 * @param uri The URI whose data is to be written.
1565 * @param mimeType The desired type of data to be written.
1566 * @param opts Options supplied by caller.
1567 * @param args Your own custom arguments.
1568 */
1569 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
1570 Bundle opts, T args);
1571 }
1572
1573 /**
1574 * A helper function for implementing {@link #openTypedAssetFile}, for
1575 * creating a data pipe and background thread allowing you to stream
1576 * generated data back to the client. This function returns a new
1577 * ParcelFileDescriptor that should be returned to the caller (the caller
1578 * is responsible for closing it).
1579 *
1580 * @param uri The URI whose data is to be written.
1581 * @param mimeType The desired type of data to be written.
1582 * @param opts Options supplied by caller.
1583 * @param args Your own custom arguments.
1584 * @param func Interface implementing the function that will actually
1585 * stream the data.
1586 * @return Returns a new ParcelFileDescriptor holding the read side of
1587 * the pipe. This should be returned to the caller for reading; the caller
1588 * is responsible for closing it when done.
1589 */
1590 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
1591 final Bundle opts, final T args, final PipeDataWriter<T> func)
1592 throws FileNotFoundException {
1593 try {
1594 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1595
1596 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1597 @Override
1598 protected Object doInBackground(Object... params) {
1599 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1600 try {
1601 fds[1].close();
1602 } catch (IOException e) {
1603 Log.w(TAG, "Failure closing pipe", e);
1604 }
1605 return null;
1606 }
1607 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001608 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001609
1610 return fds[0];
1611 } catch (IOException e) {
1612 throw new FileNotFoundException("failure making pipe");
1613 }
1614 }
1615
1616 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 * Returns true if this instance is a temporary content provider.
1618 * @return true if this instance is a temporary content provider
1619 */
1620 protected boolean isTemporary() {
1621 return false;
1622 }
1623
1624 /**
1625 * Returns the Binder object for this provider.
1626 *
1627 * @return the Binder object for this provider
1628 * @hide
1629 */
1630 public IContentProvider getIContentProvider() {
1631 return mTransport;
1632 }
1633
1634 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001635 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1636 * when directly instantiating the provider for testing.
1637 * @hide
1638 */
1639 public void attachInfoForTesting(Context context, ProviderInfo info) {
1640 attachInfo(context, info, true);
1641 }
1642
1643 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 * After being instantiated, this is called to tell the content provider
1645 * about itself.
1646 *
1647 * @param context The context this provider is running in
1648 * @param info Registered information about this content provider
1649 */
1650 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001651 attachInfo(context, info, false);
1652 }
1653
1654 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001655 /*
1656 * We may be using AsyncTask from binder threads. Make it init here
1657 * so its static handler is on the main thread.
1658 */
1659 AsyncTask.init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001661 mNoPerms = testing;
1662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 /*
1664 * Only allow it to be set once, so after the content service gives
1665 * this to us clients can't change it.
1666 */
1667 if (mContext == null) {
1668 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001669 if (context != null) {
1670 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1671 Context.APP_OPS_SERVICE);
1672 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001673 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 if (info != null) {
1675 setReadPermission(info.readPermission);
1676 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001677 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001678 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001679 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001680 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 }
1682 ContentProvider.this.onCreate();
1683 }
1684 }
Fred Quintanace31b232009-05-04 16:01:15 -07001685
1686 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001687 * Override this to handle requests to perform a batch of operations, or the
1688 * default implementation will iterate over the operations and call
1689 * {@link ContentProviderOperation#apply} on each of them.
1690 * If all calls to {@link ContentProviderOperation#apply} succeed
1691 * then a {@link ContentProviderResult} array with as many
1692 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001693 * fail, it is up to the implementation how many of the others take effect.
1694 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001695 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1696 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001697 *
Fred Quintanace31b232009-05-04 16:01:15 -07001698 * @param operations the operations to apply
1699 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001700 * @throws OperationApplicationException thrown if any operation fails.
1701 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001702 */
Fred Quintana03d94902009-05-22 14:23:31 -07001703 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001704 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001705 final int numOperations = operations.size();
1706 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1707 for (int i = 0; i < numOperations; i++) {
1708 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001709 }
1710 return results;
1711 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001712
1713 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001714 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001715 * interfaces that are cheaper and/or unnatural for a table-like
1716 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001717 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001718 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1719 * on this entry into the content provider besides the basic ability for the application
1720 * to get access to the provider at all. For example, it has no idea whether the call
1721 * being executed may read or write data in the provider, so can't enforce those
1722 * individual permissions. Any implementation of this method <strong>must</strong>
1723 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1724 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001725 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1726 * @param arg provider-defined String argument. May be {@code null}.
1727 * @param extras provider-defined Bundle argument. May be {@code null}.
1728 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001729 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001730 */
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001731 public Bundle call(String method, String arg, Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001732 return null;
1733 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001734
1735 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001736 * Implement this to shut down the ContentProvider instance. You can then
1737 * invoke this method in unit tests.
1738 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001739 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001740 * Android normally handles ContentProvider startup and shutdown
1741 * automatically. You do not need to start up or shut down a
1742 * ContentProvider. When you invoke a test method on a ContentProvider,
1743 * however, a ContentProvider instance is started and keeps running after
1744 * the test finishes, even if a succeeding test instantiates another
1745 * ContentProvider. A conflict develops because the two instances are
1746 * usually running against the same underlying data source (for example, an
1747 * sqlite database).
1748 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001749 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001750 * Implementing shutDown() avoids this conflict by providing a way to
1751 * terminate the ContentProvider. This method can also prevent memory leaks
1752 * from multiple instantiations of the ContentProvider, and it can ensure
1753 * unit test isolation by allowing you to completely clean up the test
1754 * fixture before moving on to the next test.
1755 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001756 */
1757 public void shutdown() {
1758 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1759 "connections are gracefully shutdown");
1760 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001761
1762 /**
1763 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001764 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001765 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001766 * @param fd The raw file descriptor that the dump is being sent to.
1767 * @param writer The PrintWriter to which you should dump your state. This will be
1768 * closed for you after you return.
1769 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001770 */
1771 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1772 writer.println("nothing to dump");
1773 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001774
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001775 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001776 private void validateIncomingUri(Uri uri) throws SecurityException {
1777 String auth = uri.getAuthority();
1778 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001779 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
1780 throw new SecurityException("trying to query a ContentProvider in user "
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001781 + mContext.getUserId() + " with a uri belonging to user " + userId);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001782 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001783 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
1784 String message = "The authority of the uri " + uri + " does not match the one of the "
1785 + "contentProvider: ";
1786 if (mAuthority != null) {
1787 message += mAuthority;
1788 } else {
1789 message += mAuthorities;
1790 }
1791 throw new SecurityException(message);
1792 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001793 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001794
1795 /** @hide */
1796 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1797 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001798 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001799 if (end == -1) return defaultUserId;
1800 String userIdString = auth.substring(0, end);
1801 try {
1802 return Integer.parseInt(userIdString);
1803 } catch (NumberFormatException e) {
1804 Log.w(TAG, "Error parsing userId.", e);
1805 return UserHandle.USER_NULL;
1806 }
1807 }
1808
1809 /** @hide */
1810 public static int getUserIdFromAuthority(String auth) {
1811 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1812 }
1813
1814 /** @hide */
1815 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1816 if (uri == null) return defaultUserId;
1817 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1818 }
1819
1820 /** @hide */
1821 public static int getUserIdFromUri(Uri uri) {
1822 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1823 }
1824
1825 /**
1826 * Removes userId part from authority string. Expects format:
1827 * userId@some.authority
1828 * If there is no userId in the authority, it symply returns the argument
1829 * @hide
1830 */
1831 public static String getAuthorityWithoutUserId(String auth) {
1832 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001833 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001834 return auth.substring(end+1);
1835 }
1836
1837 /** @hide */
1838 public static Uri getUriWithoutUserId(Uri uri) {
1839 if (uri == null) return null;
1840 Uri.Builder builder = uri.buildUpon();
1841 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1842 return builder.build();
1843 }
1844
1845 /** @hide */
1846 public static boolean uriHasUserId(Uri uri) {
1847 if (uri == null) return false;
1848 return !TextUtils.isEmpty(uri.getUserInfo());
1849 }
1850
1851 /** @hide */
1852 public static Uri maybeAddUserId(Uri uri, int userId) {
1853 if (uri == null) return null;
1854 if (userId != UserHandle.USER_CURRENT
1855 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1856 if (!uriHasUserId(uri)) {
1857 //We don't add the user Id if there's already one
1858 Uri.Builder builder = uri.buildUpon();
1859 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1860 return builder.build();
1861 }
1862 }
1863 return uri;
1864 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001865}