blob: be9782fb1f075aea8d9a70f7595df5b018592849 [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;
20
Dianne Hackborn35654b62013-01-14 17:38:02 -080021import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070022import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import android.content.pm.ProviderInfo;
24import android.content.res.AssetFileDescriptor;
25import android.content.res.Configuration;
26import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.database.SQLException;
28import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070029import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080031import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070032import android.os.CancellationSignal;
33import android.os.ICancellationSignal;
34import android.os.OperationCanceledException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070036import android.os.Process;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070037import android.os.UserHandle;
Vasu Nori0c9e14a2010-08-04 13:31:48 -070038import android.util.Log;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010039import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040
41import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080042import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070044import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080045import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070046import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047
48/**
49 * Content providers are one of the primary building blocks of Android applications, providing
50 * content to applications. They encapsulate data and provide it to applications through the single
51 * {@link ContentResolver} interface. A content provider is only required if you need to share
52 * data between multiple applications. For example, the contacts data is used by multiple
53 * applications and must be stored in a content provider. If you don't need to share data amongst
54 * multiple applications you can use a database directly via
55 * {@link android.database.sqlite.SQLiteDatabase}.
56 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057 * <p>When a request is made via
58 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
59 * request to the content provider registered with the authority. The content provider can interpret
60 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
61 * URIs.</p>
62 *
63 * <p>The primary methods that need to be implemented are:
64 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070065 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 * <li>{@link #query} which returns data to the caller</li>
67 * <li>{@link #insert} which inserts new data into the content provider</li>
68 * <li>{@link #update} which updates existing data in the content provider</li>
69 * <li>{@link #delete} which deletes data from the content provider</li>
70 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
71 * </ul></p>
72 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070073 * <p class="caution">Data access methods (such as {@link #insert} and
74 * {@link #update}) may be called from many threads at once, and must be thread-safe.
75 * Other methods (such as {@link #onCreate}) are only called from the application
76 * main thread, and must avoid performing lengthy operations. See the method
77 * descriptions for their expected thread behavior.</p>
78 *
79 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
80 * ContentProvider instance, so subclasses don't have to worry about the details of
81 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070082 *
83 * <div class="special reference">
84 * <h3>Developer Guides</h3>
85 * <p>For more information about using content providers, read the
86 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
87 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -070089public abstract class ContentProvider implements ComponentCallbacks2 {
Vasu Nori0c9e14a2010-08-04 13:31:48 -070090 private static final String TAG = "ContentProvider";
91
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +090092 /*
93 * Note: if you add methods to ContentProvider, you must add similar methods to
94 * MockContentProvider.
95 */
96
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070098 private int mMyUid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 private String mReadPermission;
100 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700101 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700102 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800103 private boolean mNoPerms;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700105 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<String>();
106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 private Transport mTransport = new Transport();
108
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700109 /**
110 * Construct a ContentProvider instance. Content providers must be
111 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
112 * in the manifest</a>, accessed with {@link ContentResolver}, and created
113 * automatically by the system, so applications usually do not create
114 * ContentProvider instances directly.
115 *
116 * <p>At construction time, the object is uninitialized, and most fields and
117 * methods are unavailable. Subclasses should initialize themselves in
118 * {@link #onCreate}, not the constructor.
119 *
120 * <p>Content providers are created on the application main thread at
121 * application launch time. The constructor must not perform lengthy
122 * operations, or application startup will be delayed.
123 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900124 public ContentProvider() {
125 }
126
127 /**
128 * Constructor just for mocking.
129 *
130 * @param context A Context object which should be some mock instance (like the
131 * instance of {@link android.test.mock.MockContext}).
132 * @param readPermission The read permision you want this instance should have in the
133 * test, which is available via {@link #getReadPermission()}.
134 * @param writePermission The write permission you want this instance should have
135 * in the test, which is available via {@link #getWritePermission()}.
136 * @param pathPermissions The PathPermissions you want this instance should have
137 * in the test, which is available via {@link #getPathPermissions()}.
138 * @hide
139 */
140 public ContentProvider(
141 Context context,
142 String readPermission,
143 String writePermission,
144 PathPermission[] pathPermissions) {
145 mContext = context;
146 mReadPermission = readPermission;
147 mWritePermission = writePermission;
148 mPathPermissions = pathPermissions;
149 }
150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151 /**
152 * Given an IContentProvider, try to coerce it back to the real
153 * ContentProvider object if it is running in the local process. This can
154 * be used if you know you are running in the same process as a provider,
155 * and want to get direct access to its implementation details. Most
156 * clients should not nor have a reason to use it.
157 *
158 * @param abstractInterface The ContentProvider interface that is to be
159 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800160 * @return If the IContentProvider is non-{@code null} and local, returns its actual
161 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 * @hide
163 */
164 public static ContentProvider coerceToLocalContentProvider(
165 IContentProvider abstractInterface) {
166 if (abstractInterface instanceof Transport) {
167 return ((Transport)abstractInterface).getContentProvider();
168 }
169 return null;
170 }
171
172 /**
173 * Binder object that deals with remoting.
174 *
175 * @hide
176 */
177 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800178 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800179 int mReadOp = AppOpsManager.OP_NONE;
180 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 ContentProvider getContentProvider() {
183 return ContentProvider.this;
184 }
185
Jeff Brownd2183652011-10-09 12:39:53 -0700186 @Override
187 public String getProviderName() {
188 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 }
190
Jeff Brown75ea64f2012-01-25 19:37:13 -0800191 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800192 public Cursor query(String callingPkg, Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800193 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800194 ICancellationSignal cancellationSignal) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800195 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800196 return rejectQuery(uri, projection, selection, selectionArgs, sortOrder,
197 CancellationSignal.fromTransport(cancellationSignal));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800198 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100199 uri = getUriWithoutUserId(uri);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700200 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700201 try {
202 return ContentProvider.this.query(
203 uri, projection, selection, selectionArgs, sortOrder,
204 CancellationSignal.fromTransport(cancellationSignal));
205 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700206 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 }
209
Jeff Brown75ea64f2012-01-25 19:37:13 -0800210 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 public String getType(Uri uri) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100212 uri = getUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 return ContentProvider.this.getType(uri);
214 }
215
Jeff Brown75ea64f2012-01-25 19:37:13 -0800216 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800217 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800218 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800219 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800220 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100221 int userId = getUserIdFromUri(uri);
222 uri = getUriWithoutUserId(uri);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700223 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700224 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100225 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700226 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700227 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 }
230
Jeff Brown75ea64f2012-01-25 19:37:13 -0800231 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800232 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
233 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
234 return 0;
235 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100236 uri = getUriWithoutUserId(uri);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700237 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700238 try {
239 return ContentProvider.this.bulkInsert(uri, initialValues);
240 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700241 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 }
244
Jeff Brown75ea64f2012-01-25 19:37:13 -0800245 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800246 public ContentProviderResult[] applyBatch(String callingPkg,
247 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700248 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100249 int numOperations = operations.size();
250 final int[] userIds = new int[numOperations];
251 for (int i = 0; i < numOperations; i++) {
252 ContentProviderOperation operation = operations.get(i);
253 userIds[i] = getUserIdFromUri(operation.getUri());
Fred Quintana89437372009-05-15 15:10:40 -0700254 if (operation.isReadOperation()) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800255 if (enforceReadPermission(callingPkg, operation.getUri())
256 != AppOpsManager.MODE_ALLOWED) {
257 throw new OperationApplicationException("App op not allowed", 0);
258 }
Fred Quintana89437372009-05-15 15:10:40 -0700259 }
Fred Quintana89437372009-05-15 15:10:40 -0700260 if (operation.isWriteOperation()) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800261 if (enforceWritePermission(callingPkg, operation.getUri())
262 != AppOpsManager.MODE_ALLOWED) {
263 throw new OperationApplicationException("App op not allowed", 0);
264 }
Fred Quintana89437372009-05-15 15:10:40 -0700265 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100266 if (userIds[i] != UserHandle.USER_CURRENT) {
267 // Removing the user id from the uri.
268 operation = new ContentProviderOperation(operation, true);
269 }
270 operations.set(i, operation);
Fred Quintana89437372009-05-15 15:10:40 -0700271 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700272 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700273 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100274 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
275 for (int i = 0; i < results.length ; i++) {
276 if (userIds[i] != UserHandle.USER_CURRENT) {
277 // Adding the userId to the uri.
278 results[i] = new ContentProviderResult(results[i], userIds[i]);
279 }
280 }
281 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700282 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700283 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700284 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700285 }
286
Jeff Brown75ea64f2012-01-25 19:37:13 -0800287 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800288 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
289 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
290 return 0;
291 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100292 uri = getUriWithoutUserId(uri);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700293 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700294 try {
295 return ContentProvider.this.delete(uri, selection, selectionArgs);
296 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700297 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 }
300
Jeff Brown75ea64f2012-01-25 19:37:13 -0800301 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800302 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 String[] selectionArgs) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800304 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
305 return 0;
306 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100307 uri = getUriWithoutUserId(uri);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700308 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700309 try {
310 return ContentProvider.this.update(uri, values, selection, selectionArgs);
311 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700312 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 }
315
Jeff Brown75ea64f2012-01-25 19:37:13 -0800316 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700317 public ParcelFileDescriptor openFile(
318 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 throws FileNotFoundException {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800320 enforceFilePermission(callingPkg, uri, mode);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100321 uri = getUriWithoutUserId(uri);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700322 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700323 try {
324 return ContentProvider.this.openFile(
325 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
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 AssetFileDescriptor openAssetFile(
333 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 throws FileNotFoundException {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800335 enforceFilePermission(callingPkg, uri, mode);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100336 uri = getUriWithoutUserId(uri);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700337 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700338 try {
339 return ContentProvider.this.openAssetFile(
340 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
341 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700342 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 }
345
Jeff Brown75ea64f2012-01-25 19:37:13 -0800346 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800347 public Bundle call(String callingPkg, String method, String arg, Bundle extras) {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700348 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700349 try {
350 return ContentProvider.this.call(method, arg, extras);
351 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700352 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700353 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800354 }
355
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700356 @Override
357 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100358 uri = getUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700359 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
360 }
361
362 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800363 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700364 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800365 enforceFilePermission(callingPkg, uri, "r");
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100366 uri = getUriWithoutUserId(uri);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700367 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700368 try {
369 return ContentProvider.this.openTypedAssetFile(
370 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
371 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700372 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700373 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700374 }
375
Jeff Brown75ea64f2012-01-25 19:37:13 -0800376 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700377 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800378 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800379 }
380
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700381 @Override
382 public Uri canonicalize(String callingPkg, Uri uri) {
383 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
384 return null;
385 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100386 int userId = getUserIdFromUri(uri);
387 uri = getUriWithoutUserId(uri);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700388 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700389 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100390 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700391 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700392 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700393 }
394 }
395
396 @Override
397 public Uri uncanonicalize(String callingPkg, Uri uri) {
398 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
399 return null;
400 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100401 int userId = getUserIdFromUri(uri);
402 uri = getUriWithoutUserId(uri);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700403 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700404 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100405 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700406 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700407 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700408 }
409 }
410
Dianne Hackborn35654b62013-01-14 17:38:02 -0800411 private void enforceFilePermission(String callingPkg, Uri uri, String mode)
412 throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800413 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800414 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
415 throw new FileNotFoundException("App op not allowed");
416 }
417 } else {
418 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) {
419 throw new FileNotFoundException("App op not allowed");
420 }
421 }
422 }
423
424 private int enforceReadPermission(String callingPkg, Uri uri) throws SecurityException {
425 enforceReadPermissionInner(uri);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800426 if (mReadOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800427 return mAppOpsManager.noteOp(mReadOp, Binder.getCallingUid(), callingPkg);
428 }
429 return AppOpsManager.MODE_ALLOWED;
430 }
431
Dianne Hackborn35654b62013-01-14 17:38:02 -0800432 private int enforceWritePermission(String callingPkg, Uri uri) throws SecurityException {
433 enforceWritePermissionInner(uri);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800434 if (mWriteOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800435 return mAppOpsManager.noteOp(mWriteOp, Binder.getCallingUid(), callingPkg);
436 }
437 return AppOpsManager.MODE_ALLOWED;
438 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700439 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800440
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700441 /** {@hide} */
442 protected void enforceReadPermissionInner(Uri uri) throws SecurityException {
443 final Context context = getContext();
444 final int pid = Binder.getCallingPid();
445 final int uid = Binder.getCallingUid();
446 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700447
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700448 if (UserHandle.isSameApp(uid, mMyUid)) {
449 return;
450 }
451
452 if (mExported) {
453 final String componentPerm = getReadPermission();
454 if (componentPerm != null) {
455 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
456 return;
457 } else {
458 missingPerm = componentPerm;
459 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700460 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700461
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700462 // track if unprotected read is allowed; any denied
463 // <path-permission> below removes this ability
464 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700465
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700466 final PathPermission[] pps = getPathPermissions();
467 if (pps != null) {
468 final String path = uri.getPath();
469 for (PathPermission pp : pps) {
470 final String pathPerm = pp.getReadPermission();
471 if (pathPerm != null && pp.match(path)) {
472 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
473 return;
474 } else {
475 // any denied <path-permission> means we lose
476 // default <provider> access.
477 allowDefaultRead = false;
478 missingPerm = pathPerm;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700479 }
480 }
481 }
482 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700483
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700484 // if we passed <path-permission> checks above, and no default
485 // <provider> permission, then allow access.
486 if (allowDefaultRead) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800487 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700488
489 // last chance, check against any uri grants
490 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION)
491 == PERMISSION_GRANTED) {
492 return;
493 }
494
495 final String failReason = mExported
496 ? " requires " + missingPerm + ", or grantUriPermission()"
497 : " requires the provider be exported, or grantUriPermission()";
498 throw new SecurityException("Permission Denial: reading "
499 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
500 + ", uid=" + uid + failReason);
501 }
502
503 /** {@hide} */
504 protected void enforceWritePermissionInner(Uri uri) throws SecurityException {
505 final Context context = getContext();
506 final int pid = Binder.getCallingPid();
507 final int uid = Binder.getCallingUid();
508 String missingPerm = null;
509
510 if (UserHandle.isSameApp(uid, mMyUid)) {
511 return;
512 }
513
514 if (mExported) {
515 final String componentPerm = getWritePermission();
516 if (componentPerm != null) {
517 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) {
518 return;
519 } else {
520 missingPerm = componentPerm;
521 }
522 }
523
524 // track if unprotected write is allowed; any denied
525 // <path-permission> below removes this ability
526 boolean allowDefaultWrite = (componentPerm == null);
527
528 final PathPermission[] pps = getPathPermissions();
529 if (pps != null) {
530 final String path = uri.getPath();
531 for (PathPermission pp : pps) {
532 final String pathPerm = pp.getWritePermission();
533 if (pathPerm != null && pp.match(path)) {
534 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) {
535 return;
536 } else {
537 // any denied <path-permission> means we lose
538 // default <provider> access.
539 allowDefaultWrite = false;
540 missingPerm = pathPerm;
541 }
542 }
543 }
544 }
545
546 // if we passed <path-permission> checks above, and no default
547 // <provider> permission, then allow access.
548 if (allowDefaultWrite) return;
549 }
550
551 // last chance, check against any uri grants
552 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
553 == PERMISSION_GRANTED) {
554 return;
555 }
556
557 final String failReason = mExported
558 ? " requires " + missingPerm + ", or grantUriPermission()"
559 : " requires the provider be exported, or grantUriPermission()";
560 throw new SecurityException("Permission Denial: writing "
561 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
562 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 }
564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700566 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800567 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 * constructor.
569 */
570 public final Context getContext() {
571 return mContext;
572 }
573
574 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700575 * Set the calling package, returning the current value (or {@code null})
576 * which can be used later to restore the previous state.
577 */
578 private String setCallingPackage(String callingPackage) {
579 final String original = mCallingPackage.get();
580 mCallingPackage.set(callingPackage);
581 return original;
582 }
583
584 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700585 * Return the package name of the caller that initiated the request being
586 * processed on the current thread. The returned package will have been
587 * verified to belong to the calling UID. Returns {@code null} if not
588 * currently processing a request.
589 * <p>
590 * This will always return {@code null} when processing
591 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
592 *
593 * @see Binder#getCallingUid()
594 * @see Context#grantUriPermission(String, Uri, int)
595 * @throws SecurityException if the calling package doesn't belong to the
596 * calling UID.
597 */
598 public final String getCallingPackage() {
599 final String pkg = mCallingPackage.get();
600 if (pkg != null) {
601 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
602 }
603 return pkg;
604 }
605
606 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 * Change the permission required to read data from the content
608 * provider. This is normally set for you from its manifest information
609 * when the provider is first created.
610 *
611 * @param permission Name of the permission required for read-only access.
612 */
613 protected final void setReadPermission(String permission) {
614 mReadPermission = permission;
615 }
616
617 /**
618 * Return the name of the permission required for read-only access to
619 * this content provider. This method can be called from multiple
620 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800621 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
622 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 */
624 public final String getReadPermission() {
625 return mReadPermission;
626 }
627
628 /**
629 * Change the permission required to read and write data in the content
630 * provider. This is normally set for you from its manifest information
631 * when the provider is first created.
632 *
633 * @param permission Name of the permission required for read/write access.
634 */
635 protected final void setWritePermission(String permission) {
636 mWritePermission = permission;
637 }
638
639 /**
640 * Return the name of the permission required for read/write access to
641 * this content provider. This method can be called from multiple
642 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800643 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
644 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 */
646 public final String getWritePermission() {
647 return mWritePermission;
648 }
649
650 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700651 * Change the path-based permission required to read and/or write data in
652 * the content provider. This is normally set for you from its manifest
653 * information when the provider is first created.
654 *
655 * @param permissions Array of path permission descriptions.
656 */
657 protected final void setPathPermissions(PathPermission[] permissions) {
658 mPathPermissions = permissions;
659 }
660
661 /**
662 * Return the path-based permissions required for read and/or write access to
663 * this content provider. This method can be called from multiple
664 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800665 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
666 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700667 */
668 public final PathPermission[] getPathPermissions() {
669 return mPathPermissions;
670 }
671
Dianne Hackborn35654b62013-01-14 17:38:02 -0800672 /** @hide */
673 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800674 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800675 mTransport.mReadOp = readOp;
676 mTransport.mWriteOp = writeOp;
677 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800678 }
679
Dianne Hackborn961321f2013-02-05 17:22:41 -0800680 /** @hide */
681 public AppOpsManager getAppOpsManager() {
682 return mTransport.mAppOpsManager;
683 }
684
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700685 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700686 * Implement this to initialize your content provider on startup.
687 * This method is called for all registered content providers on the
688 * application main thread at application launch time. It must not perform
689 * lengthy operations, or application startup will be delayed.
690 *
691 * <p>You should defer nontrivial initialization (such as opening,
692 * upgrading, and scanning databases) until the content provider is used
693 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
694 * keeps application startup fast, avoids unnecessary work if the provider
695 * turns out not to be needed, and stops database errors (such as a full
696 * disk) from halting application launch.
697 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700698 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700699 * is a helpful utility class that makes it easy to manage databases,
700 * and will automatically defer opening until first use. If you do use
701 * SQLiteOpenHelper, make sure to avoid calling
702 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
703 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
704 * from this method. (Instead, override
705 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
706 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 *
708 * @return true if the provider was successfully loaded, false otherwise
709 */
710 public abstract boolean onCreate();
711
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700712 /**
713 * {@inheritDoc}
714 * This method is always called on the application main thread, and must
715 * not perform lengthy operations.
716 *
717 * <p>The default content provider implementation does nothing.
718 * Override this method to take appropriate action.
719 * (Content providers do not usually care about things like screen
720 * orientation, but may want to know about locale changes.)
721 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 public void onConfigurationChanged(Configuration newConfig) {
723 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700724
725 /**
726 * {@inheritDoc}
727 * This method is always called on the application main thread, and must
728 * not perform lengthy operations.
729 *
730 * <p>The default content provider implementation does nothing.
731 * Subclasses may override this method to take appropriate action.
732 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 public void onLowMemory() {
734 }
735
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700736 public void onTrimMemory(int level) {
737 }
738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800740 * @hide
741 * Implementation when a caller has performed a query on the content
742 * provider, but that call has been rejected for the operation given
743 * to {@link #setAppOps(int, int)}. The default implementation
744 * rewrites the <var>selection</var> argument to include a condition
745 * that is never true (so will always result in an empty cursor)
746 * and calls through to {@link #query(android.net.Uri, String[], String, String[],
747 * String, android.os.CancellationSignal)} with that.
748 */
749 public Cursor rejectQuery(Uri uri, String[] projection,
750 String selection, String[] selectionArgs, String sortOrder,
751 CancellationSignal cancellationSignal) {
752 // The read is not allowed... to fake it out, we replace the given
753 // selection statement with a dummy one that will always be false.
754 // This way we will get a cursor back that has the correct structure
755 // but contains no rows.
Dianne Hackborn9fa39bd2013-03-22 18:42:14 -0700756 if (selection == null || selection.isEmpty()) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800757 selection = "'A' = 'B'";
758 } else {
759 selection = "'A' = 'B' AND (" + selection + ")";
760 }
761 return query(uri, projection, selection, selectionArgs, sortOrder, cancellationSignal);
762 }
763
764 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700765 * Implement this to handle query requests from clients.
766 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800767 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
768 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 * <p>
770 * Example client call:<p>
771 * <pre>// Request a specific record.
772 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000773 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 projection, // Which columns to return.
775 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000776 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 People.NAME + " ASC"); // Sort order.</pre>
778 * Example implementation:<p>
779 * <pre>// SQLiteQueryBuilder is a helper class that creates the
780 // proper SQL syntax for us.
781 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
782
783 // Set the table we're querying.
784 qBuilder.setTables(DATABASE_TABLE_NAME);
785
786 // If the query ends in a specific record number, we're
787 // being asked for a specific record, so set the
788 // WHERE clause in our query.
789 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
790 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
791 }
792
793 // Make the query.
794 Cursor c = qBuilder.query(mDb,
795 projection,
796 selection,
797 selectionArgs,
798 groupBy,
799 having,
800 sortOrder);
801 c.setNotificationUri(getContext().getContentResolver(), uri);
802 return c;</pre>
803 *
804 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000805 * if the client is requesting a specific record, the URI will end in a record number
806 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
807 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800809 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800811 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000812 * @param selectionArgs You may include ?s in selection, which will be replaced by
813 * the values from selectionArgs, in order that they appear in the selection.
814 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800816 * If {@code null} then the provider is free to define the sort order.
817 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 */
819 public abstract Cursor query(Uri uri, String[] projection,
820 String selection, String[] selectionArgs, String sortOrder);
821
Fred Quintana5bba6322009-10-05 14:21:12 -0700822 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800823 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800824 * This method can be called from multiple threads, as described in
825 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
826 * and Threads</a>.
827 * <p>
828 * Example client call:<p>
829 * <pre>// Request a specific record.
830 * Cursor managedCursor = managedQuery(
831 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
832 projection, // Which columns to return.
833 null, // WHERE clause.
834 null, // WHERE clause value substitution
835 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 * <p>
862 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800863 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
864 * signal to ensure correct operation on older versions of the Android Framework in
865 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800866 *
867 * @param uri The URI to query. This will be the full URI sent by the client;
868 * if the client is requesting a specific record, the URI will end in a record number
869 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
870 * that _id value.
871 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800872 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800873 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800874 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800875 * @param selectionArgs You may include ?s in selection, which will be replaced by
876 * the values from selectionArgs, in order that they appear in the selection.
877 * The values will be bound as Strings.
878 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800879 * If {@code null} then the provider is free to define the sort order.
880 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800881 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
882 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800883 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800884 */
885 public Cursor query(Uri uri, String[] projection,
886 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800887 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800888 return query(uri, projection, selection, selectionArgs, sortOrder);
889 }
890
891 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700892 * Implement this to handle requests for the MIME type of the data at the
893 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 * <code>vnd.android.cursor.item</code> for a single record,
895 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700896 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800897 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
898 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700900 * <p>Note that there are no permissions needed for an application to
901 * access this information; if your content provider requires read and/or
902 * write permissions, or is not exported, all applications can still call
903 * this method regardless of their access permissions. This allows them
904 * to retrieve the MIME type for a URI when dispatching intents.
905 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800907 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 */
909 public abstract String getType(Uri uri);
910
911 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700912 * Implement this to support canonicalization of URIs that refer to your
913 * content provider. A canonical URI is one that can be transported across
914 * devices, backup/restore, and other contexts, and still be able to refer
915 * to the same data item. Typically this is implemented by adding query
916 * params to the URI allowing the content provider to verify that an incoming
917 * canonical URI references the same data as it was originally intended for and,
918 * if it doesn't, to find that data (if it exists) in the current environment.
919 *
920 * <p>For example, if the content provider holds people and a normal URI in it
921 * is created with a row index into that people database, the cananical representation
922 * may have an additional query param at the end which specifies the name of the
923 * person it is intended for. Later calls into the provider with that URI will look
924 * up the row of that URI's base index and, if it doesn't match or its entry's
925 * name doesn't match the name in the query param, perform a query on its database
926 * to find the correct row to operate on.</p>
927 *
928 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
929 * URIs (including this one) must perform this verification and recovery of any
930 * canonical URIs they receive. In addition, you must also implement
931 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
932 *
933 * <p>The default implementation of this method returns null, indicating that
934 * canonical URIs are not supported.</p>
935 *
936 * @param url The Uri to canonicalize.
937 *
938 * @return Return the canonical representation of <var>url</var>, or null if
939 * canonicalization of that Uri is not supported.
940 */
941 public Uri canonicalize(Uri url) {
942 return null;
943 }
944
945 /**
946 * Remove canonicalization from canonical URIs previously returned by
947 * {@link #canonicalize}. For example, if your implementation is to add
948 * a query param to canonicalize a URI, this method can simply trip any
949 * query params on the URI. The default implementation always returns the
950 * same <var>url</var> that was passed in.
951 *
952 * @param url The Uri to remove any canonicalization from.
953 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -0700954 * @return Return the non-canonical representation of <var>url</var>, return
955 * the <var>url</var> as-is if there is nothing to do, or return null if
956 * the data identified by the canonical representation can not be found in
957 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700958 */
959 public Uri uncanonicalize(Uri url) {
960 return url;
961 }
962
963 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800964 * @hide
965 * Implementation when a caller has performed an insert on the content
966 * provider, but that call has been rejected for the operation given
967 * to {@link #setAppOps(int, int)}. The default implementation simply
968 * returns a dummy URI that is the base URI with a 0 path element
969 * appended.
970 */
971 public Uri rejectInsert(Uri uri, ContentValues values) {
972 // If not allowed, we need to return some reasonable URI. Maybe the
973 // content provider should be responsible for this, but for now we
974 // will just return the base URI with a dummy '0' tagged on to it.
975 // You shouldn't be able to read if you can't write, anyway, so it
976 // shouldn't matter much what is returned.
977 return uri.buildUpon().appendPath("0").build();
978 }
979
980 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700981 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
983 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700984 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800985 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
986 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800987 * @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 -0800988 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800989 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 * @return The URI for the newly inserted item.
991 */
992 public abstract Uri insert(Uri uri, ContentValues values);
993
994 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700995 * Override this to handle requests to insert a set of new rows, or the
996 * default implementation will iterate over the values and call
997 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
999 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001000 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001001 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1002 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 *
1004 * @param uri The content:// URI of the insertion request.
1005 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001006 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 * @return The number of values that were inserted.
1008 */
1009 public int bulkInsert(Uri uri, ContentValues[] values) {
1010 int numValues = values.length;
1011 for (int i = 0; i < numValues; i++) {
1012 insert(uri, values[i]);
1013 }
1014 return numValues;
1015 }
1016
1017 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001018 * Implement this to handle requests to delete one or more rows.
1019 * The implementation should apply the selection clause when performing
1020 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001021 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001023 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001024 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1025 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 *
1027 * <p>The implementation is responsible for parsing out a row ID at the end
1028 * of the URI, if a specific row is being deleted. That is, the client would
1029 * pass in <code>content://contacts/people/22</code> and the implementation is
1030 * responsible for parsing the record number (22) when creating a SQL statement.
1031 *
1032 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1033 * @param selection An optional restriction to apply to rows when deleting.
1034 * @return The number of rows affected.
1035 * @throws SQLException
1036 */
1037 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
1038
1039 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001040 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001041 * The implementation should update all rows matching the selection
1042 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1044 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001045 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001046 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1047 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 *
1049 * @param uri The URI to query. This can potentially have a record ID if this
1050 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001051 * @param values A set of column_name/value pairs to update in the database.
1052 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 * @param selection An optional filter to match rows to update.
1054 * @return the number of rows affected.
1055 */
1056 public abstract int update(Uri uri, ContentValues values, String selection,
1057 String[] selectionArgs);
1058
1059 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001060 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001061 * The default implementation always throws {@link FileNotFoundException}.
1062 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001063 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1064 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001065 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001066 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1067 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001068 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 *
1070 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1071 * their responsibility to close it when done. That is, the implementation
1072 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001073 * <p>
1074 * If opened with the exclusive "r" or "w" modes, the returned
1075 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1076 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1077 * supports seeking.
1078 * <p>
1079 * If you need to detect when the returned ParcelFileDescriptor has been
1080 * closed, or if the remote process has crashed or encountered some other
1081 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1082 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1083 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1084 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001086 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1087 * to return the appropriate MIME type for the data returned here with
1088 * the same URI. This will allow intent resolution to automatically determine the data MIME
1089 * type and select the appropriate matching targets as part of its operation.</p>
1090 *
1091 * <p class="note">For better interoperability with other applications, it is recommended
1092 * that for any URIs that can be opened, you also support queries on them
1093 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1094 * You may also want to support other common columns if you have additional meta-data
1095 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1096 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1097 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 * @param uri The URI whose file is to be opened.
1099 * @param mode Access mode for the file. May be "r" for read-only access,
1100 * "rw" for read and write access, or "rwt" for read and write access
1101 * that truncates any existing file.
1102 *
1103 * @return Returns a new ParcelFileDescriptor which you can use to access
1104 * the file.
1105 *
1106 * @throws FileNotFoundException Throws FileNotFoundException if there is
1107 * no file associated with the given URI or the mode is invalid.
1108 * @throws SecurityException Throws SecurityException if the caller does
1109 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001110 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 * @see #openAssetFile(Uri, String)
1112 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001113 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001114 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001115 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 public ParcelFileDescriptor openFile(Uri uri, String mode)
1117 throws FileNotFoundException {
1118 throw new FileNotFoundException("No files supported by provider at "
1119 + uri);
1120 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001123 * Override this to handle requests to open a file blob.
1124 * The default implementation always throws {@link FileNotFoundException}.
1125 * This method can be called from multiple threads, as described in
1126 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1127 * and Threads</a>.
1128 *
1129 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1130 * to the caller. This way large data (such as images and documents) can be
1131 * returned without copying the content.
1132 *
1133 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1134 * their responsibility to close it when done. That is, the implementation
1135 * of this method should create a new ParcelFileDescriptor for each call.
1136 * <p>
1137 * If opened with the exclusive "r" or "w" modes, the returned
1138 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1139 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1140 * supports seeking.
1141 * <p>
1142 * If you need to detect when the returned ParcelFileDescriptor has been
1143 * closed, or if the remote process has crashed or encountered some other
1144 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1145 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1146 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1147 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1148 *
1149 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1150 * to return the appropriate MIME type for the data returned here with
1151 * the same URI. This will allow intent resolution to automatically determine the data MIME
1152 * type and select the appropriate matching targets as part of its operation.</p>
1153 *
1154 * <p class="note">For better interoperability with other applications, it is recommended
1155 * that for any URIs that can be opened, you also support queries on them
1156 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1157 * You may also want to support other common columns if you have additional meta-data
1158 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1159 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1160 *
1161 * @param uri The URI whose file is to be opened.
1162 * @param mode Access mode for the file. May be "r" for read-only access,
1163 * "w" for write-only access, "rw" for read and write access, or
1164 * "rwt" for read and write access that truncates any existing
1165 * file.
1166 * @param signal A signal to cancel the operation in progress, or
1167 * {@code null} if none. For example, if you are downloading a
1168 * file from the network to service a "rw" mode request, you
1169 * should periodically call
1170 * {@link CancellationSignal#throwIfCanceled()} to check whether
1171 * the client has canceled the request and abort the download.
1172 *
1173 * @return Returns a new ParcelFileDescriptor which you can use to access
1174 * the file.
1175 *
1176 * @throws FileNotFoundException Throws FileNotFoundException if there is
1177 * no file associated with the given URI or the mode is invalid.
1178 * @throws SecurityException Throws SecurityException if the caller does
1179 * not have permission to access the file.
1180 *
1181 * @see #openAssetFile(Uri, String)
1182 * @see #openFileHelper(Uri, String)
1183 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001184 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001185 */
1186 public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
1187 throws FileNotFoundException {
1188 return openFile(uri, mode);
1189 }
1190
1191 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 * This is like {@link #openFile}, but can be implemented by providers
1193 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001194 * inside of their .apk.
1195 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001196 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1197 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001198 *
1199 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001200 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001201 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1203 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1204 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001205 * <p>
1206 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1207 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001208 *
1209 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 * should create the AssetFileDescriptor with
1211 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001212 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001214 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1215 * to return the appropriate MIME type for the data returned here with
1216 * the same URI. This will allow intent resolution to automatically determine the data MIME
1217 * type and select the appropriate matching targets as part of its operation.</p>
1218 *
1219 * <p class="note">For better interoperability with other applications, it is recommended
1220 * that for any URIs that can be opened, you also support queries on them
1221 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1222 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 * @param uri The URI whose file is to be opened.
1224 * @param mode Access mode for the file. May be "r" for read-only access,
1225 * "w" for write-only access (erasing whatever data is currently in
1226 * the file), "wa" for write-only access to append to any existing data,
1227 * "rw" for read and write access on any existing data, and "rwt" for read
1228 * and write access that truncates any existing file.
1229 *
1230 * @return Returns a new AssetFileDescriptor which you can use to access
1231 * the file.
1232 *
1233 * @throws FileNotFoundException Throws FileNotFoundException if there is
1234 * no file associated with the given URI or the mode is invalid.
1235 * @throws SecurityException Throws SecurityException if the caller does
1236 * not have permission to access the file.
1237 *
1238 * @see #openFile(Uri, String)
1239 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001240 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 */
1242 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
1243 throws FileNotFoundException {
1244 ParcelFileDescriptor fd = openFile(uri, mode);
1245 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1246 }
1247
1248 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001249 * This is like {@link #openFile}, but can be implemented by providers
1250 * that need to be able to return sub-sections of files, often assets
1251 * inside of their .apk.
1252 * This method can be called from multiple threads, as described in
1253 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1254 * and Threads</a>.
1255 *
1256 * <p>If you implement this, your clients must be able to deal with such
1257 * file slices, either directly with
1258 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1259 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1260 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1261 * methods.
1262 * <p>
1263 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1264 * streaming of data.
1265 *
1266 * <p class="note">If you are implementing this to return a full file, you
1267 * should create the AssetFileDescriptor with
1268 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1269 * applications that cannot handle sub-sections of files.</p>
1270 *
1271 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1272 * to return the appropriate MIME type for the data returned here with
1273 * the same URI. This will allow intent resolution to automatically determine the data MIME
1274 * type and select the appropriate matching targets as part of its operation.</p>
1275 *
1276 * <p class="note">For better interoperability with other applications, it is recommended
1277 * that for any URIs that can be opened, you also support queries on them
1278 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1279 *
1280 * @param uri The URI whose file is to be opened.
1281 * @param mode Access mode for the file. May be "r" for read-only access,
1282 * "w" for write-only access (erasing whatever data is currently in
1283 * the file), "wa" for write-only access to append to any existing data,
1284 * "rw" for read and write access on any existing data, and "rwt" for read
1285 * and write access that truncates any existing file.
1286 * @param signal A signal to cancel the operation in progress, or
1287 * {@code null} if none. For example, if you are downloading a
1288 * file from the network to service a "rw" mode request, you
1289 * should periodically call
1290 * {@link CancellationSignal#throwIfCanceled()} to check whether
1291 * the client has canceled the request and abort the download.
1292 *
1293 * @return Returns a new AssetFileDescriptor which you can use to access
1294 * the file.
1295 *
1296 * @throws FileNotFoundException Throws FileNotFoundException if there is
1297 * no file associated with the given URI or the mode is invalid.
1298 * @throws SecurityException Throws SecurityException if the caller does
1299 * not have permission to access the file.
1300 *
1301 * @see #openFile(Uri, String)
1302 * @see #openFileHelper(Uri, String)
1303 * @see #getType(android.net.Uri)
1304 */
1305 public AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)
1306 throws FileNotFoundException {
1307 return openAssetFile(uri, mode);
1308 }
1309
1310 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 * Convenience for subclasses that wish to implement {@link #openFile}
1312 * by looking up a column named "_data" at the given URI.
1313 *
1314 * @param uri The URI to be opened.
1315 * @param mode The file mode. May be "r" for read-only access,
1316 * "w" for write-only access (erasing whatever data is currently in
1317 * the file), "wa" for write-only access to append to any existing data,
1318 * "rw" for read and write access on any existing data, and "rwt" for read
1319 * and write access that truncates any existing file.
1320 *
1321 * @return Returns a new ParcelFileDescriptor that can be used by the
1322 * client to access the file.
1323 */
1324 protected final ParcelFileDescriptor openFileHelper(Uri uri,
1325 String mode) throws FileNotFoundException {
1326 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1327 int count = (c != null) ? c.getCount() : 0;
1328 if (count != 1) {
1329 // If there is not exactly one result, throw an appropriate
1330 // exception.
1331 if (c != null) {
1332 c.close();
1333 }
1334 if (count == 0) {
1335 throw new FileNotFoundException("No entry for " + uri);
1336 }
1337 throw new FileNotFoundException("Multiple items at " + uri);
1338 }
1339
1340 c.moveToFirst();
1341 int i = c.getColumnIndex("_data");
1342 String path = (i >= 0 ? c.getString(i) : null);
1343 c.close();
1344 if (path == null) {
1345 throw new FileNotFoundException("Column _data not found.");
1346 }
1347
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001348 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 return ParcelFileDescriptor.open(new File(path), modeBits);
1350 }
1351
1352 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001353 * Called by a client to determine the types of data streams that this
1354 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001355 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001356 * of a particular type, return that MIME type if it matches the given
1357 * mimeTypeFilter. If it can perform type conversions, return an array
1358 * of all supported MIME types that match mimeTypeFilter.
1359 *
1360 * @param uri The data in the content provider being queried.
1361 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001362 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001363 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001364 * given mimeTypeFilter. Otherwise returns an array of all available
1365 * concrete MIME types.
1366 *
1367 * @see #getType(Uri)
1368 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001369 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001370 */
1371 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
1372 return null;
1373 }
1374
1375 /**
1376 * Called by a client to open a read-only stream containing data of a
1377 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1378 * except the file can only be read-only and the content provider may
1379 * perform data conversions to generate data of the desired type.
1380 *
1381 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001382 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001383 * {@link #openAssetFile(Uri, String)}.
1384 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001385 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001386 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001387 * <p>
1388 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1389 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001390 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001391 * <p class="note">For better interoperability with other applications, it is recommended
1392 * that for any URIs that can be opened, you also support queries on them
1393 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1394 * You may also want to support other common columns if you have additional meta-data
1395 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1396 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1397 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001398 * @param uri The data in the content provider being queried.
1399 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001400 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001401 * requirements; in this case the content provider will pick its best
1402 * type matching the pattern.
1403 * @param opts Additional options from the client. The definitions of
1404 * these are specific to the content provider being called.
1405 *
1406 * @return Returns a new AssetFileDescriptor from which the client can
1407 * read data of the desired type.
1408 *
1409 * @throws FileNotFoundException Throws FileNotFoundException if there is
1410 * no file associated with the given URI or the mode is invalid.
1411 * @throws SecurityException Throws SecurityException if the caller does
1412 * not have permission to access the data.
1413 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1414 * content provider does not support the requested MIME type.
1415 *
1416 * @see #getStreamTypes(Uri, String)
1417 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001418 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001419 */
1420 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
1421 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001422 if ("*/*".equals(mimeTypeFilter)) {
1423 // If they can take anything, the untyped open call is good enough.
1424 return openAssetFile(uri, "r");
1425 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001426 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001427 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001428 // Use old untyped open call if this provider has a type for this
1429 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001430 return openAssetFile(uri, "r");
1431 }
1432 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1433 }
1434
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001435
1436 /**
1437 * Called by a client to open a read-only stream containing data of a
1438 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1439 * except the file can only be read-only and the content provider may
1440 * perform data conversions to generate data of the desired type.
1441 *
1442 * <p>The default implementation compares the given mimeType against the
1443 * result of {@link #getType(Uri)} and, if they match, simply calls
1444 * {@link #openAssetFile(Uri, String)}.
1445 *
1446 * <p>See {@link ClipData} for examples of the use and implementation
1447 * of this method.
1448 * <p>
1449 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1450 * streaming of data.
1451 *
1452 * <p class="note">For better interoperability with other applications, it is recommended
1453 * that for any URIs that can be opened, you also support queries on them
1454 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1455 * You may also want to support other common columns if you have additional meta-data
1456 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1457 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1458 *
1459 * @param uri The data in the content provider being queried.
1460 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001461 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001462 * requirements; in this case the content provider will pick its best
1463 * type matching the pattern.
1464 * @param opts Additional options from the client. The definitions of
1465 * these are specific to the content provider being called.
1466 * @param signal A signal to cancel the operation in progress, or
1467 * {@code null} if none. For example, if you are downloading a
1468 * file from the network to service a "rw" mode request, you
1469 * should periodically call
1470 * {@link CancellationSignal#throwIfCanceled()} to check whether
1471 * the client has canceled the request and abort the download.
1472 *
1473 * @return Returns a new AssetFileDescriptor from which the client can
1474 * read data of the desired type.
1475 *
1476 * @throws FileNotFoundException Throws FileNotFoundException if there is
1477 * no file associated with the given URI or the mode is invalid.
1478 * @throws SecurityException Throws SecurityException if the caller does
1479 * not have permission to access the data.
1480 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1481 * content provider does not support the requested MIME type.
1482 *
1483 * @see #getStreamTypes(Uri, String)
1484 * @see #openAssetFile(Uri, String)
1485 * @see ClipDescription#compareMimeTypes(String, String)
1486 */
1487 public AssetFileDescriptor openTypedAssetFile(
1488 Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)
1489 throws FileNotFoundException {
1490 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1491 }
1492
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001493 /**
1494 * Interface to write a stream of data to a pipe. Use with
1495 * {@link ContentProvider#openPipeHelper}.
1496 */
1497 public interface PipeDataWriter<T> {
1498 /**
1499 * Called from a background thread to stream data out to a pipe.
1500 * Note that the pipe is blocking, so this thread can block on
1501 * writes for an arbitrary amount of time if the client is slow
1502 * at reading.
1503 *
1504 * @param output The pipe where data should be written. This will be
1505 * closed for you upon returning from this function.
1506 * @param uri The URI whose data is to be written.
1507 * @param mimeType The desired type of data to be written.
1508 * @param opts Options supplied by caller.
1509 * @param args Your own custom arguments.
1510 */
1511 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
1512 Bundle opts, T args);
1513 }
1514
1515 /**
1516 * A helper function for implementing {@link #openTypedAssetFile}, for
1517 * creating a data pipe and background thread allowing you to stream
1518 * generated data back to the client. This function returns a new
1519 * ParcelFileDescriptor that should be returned to the caller (the caller
1520 * is responsible for closing it).
1521 *
1522 * @param uri The URI whose data is to be written.
1523 * @param mimeType The desired type of data to be written.
1524 * @param opts Options supplied by caller.
1525 * @param args Your own custom arguments.
1526 * @param func Interface implementing the function that will actually
1527 * stream the data.
1528 * @return Returns a new ParcelFileDescriptor holding the read side of
1529 * the pipe. This should be returned to the caller for reading; the caller
1530 * is responsible for closing it when done.
1531 */
1532 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
1533 final Bundle opts, final T args, final PipeDataWriter<T> func)
1534 throws FileNotFoundException {
1535 try {
1536 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1537
1538 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1539 @Override
1540 protected Object doInBackground(Object... params) {
1541 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1542 try {
1543 fds[1].close();
1544 } catch (IOException e) {
1545 Log.w(TAG, "Failure closing pipe", e);
1546 }
1547 return null;
1548 }
1549 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001550 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001551
1552 return fds[0];
1553 } catch (IOException e) {
1554 throw new FileNotFoundException("failure making pipe");
1555 }
1556 }
1557
1558 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 * Returns true if this instance is a temporary content provider.
1560 * @return true if this instance is a temporary content provider
1561 */
1562 protected boolean isTemporary() {
1563 return false;
1564 }
1565
1566 /**
1567 * Returns the Binder object for this provider.
1568 *
1569 * @return the Binder object for this provider
1570 * @hide
1571 */
1572 public IContentProvider getIContentProvider() {
1573 return mTransport;
1574 }
1575
1576 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001577 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1578 * when directly instantiating the provider for testing.
1579 * @hide
1580 */
1581 public void attachInfoForTesting(Context context, ProviderInfo info) {
1582 attachInfo(context, info, true);
1583 }
1584
1585 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 * After being instantiated, this is called to tell the content provider
1587 * about itself.
1588 *
1589 * @param context The context this provider is running in
1590 * @param info Registered information about this content provider
1591 */
1592 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001593 attachInfo(context, info, false);
1594 }
1595
1596 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001597 /*
1598 * We may be using AsyncTask from binder threads. Make it init here
1599 * so its static handler is on the main thread.
1600 */
1601 AsyncTask.init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001603 mNoPerms = testing;
1604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 /*
1606 * Only allow it to be set once, so after the content service gives
1607 * this to us clients can't change it.
1608 */
1609 if (mContext == null) {
1610 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001611 if (context != null) {
1612 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1613 Context.APP_OPS_SERVICE);
1614 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001615 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 if (info != null) {
1617 setReadPermission(info.readPermission);
1618 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001619 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001620 mExported = info.exported;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001621 }
1622 ContentProvider.this.onCreate();
1623 }
1624 }
Fred Quintanace31b232009-05-04 16:01:15 -07001625
1626 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001627 * Override this to handle requests to perform a batch of operations, or the
1628 * default implementation will iterate over the operations and call
1629 * {@link ContentProviderOperation#apply} on each of them.
1630 * If all calls to {@link ContentProviderOperation#apply} succeed
1631 * then a {@link ContentProviderResult} array with as many
1632 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001633 * fail, it is up to the implementation how many of the others take effect.
1634 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001635 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1636 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001637 *
Fred Quintanace31b232009-05-04 16:01:15 -07001638 * @param operations the operations to apply
1639 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001640 * @throws OperationApplicationException thrown if any operation fails.
1641 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001642 */
Fred Quintana03d94902009-05-22 14:23:31 -07001643 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001644 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001645 final int numOperations = operations.size();
1646 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1647 for (int i = 0; i < numOperations; i++) {
1648 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001649 }
1650 return results;
1651 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001652
1653 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001654 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001655 * interfaces that are cheaper and/or unnatural for a table-like
1656 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001657 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001658 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1659 * on this entry into the content provider besides the basic ability for the application
1660 * to get access to the provider at all. For example, it has no idea whether the call
1661 * being executed may read or write data in the provider, so can't enforce those
1662 * individual permissions. Any implementation of this method <strong>must</strong>
1663 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1664 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001665 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1666 * @param arg provider-defined String argument. May be {@code null}.
1667 * @param extras provider-defined Bundle argument. May be {@code null}.
1668 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001669 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001670 */
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001671 public Bundle call(String method, String arg, Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001672 return null;
1673 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001674
1675 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001676 * Implement this to shut down the ContentProvider instance. You can then
1677 * invoke this method in unit tests.
1678 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001679 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001680 * Android normally handles ContentProvider startup and shutdown
1681 * automatically. You do not need to start up or shut down a
1682 * ContentProvider. When you invoke a test method on a ContentProvider,
1683 * however, a ContentProvider instance is started and keeps running after
1684 * the test finishes, even if a succeeding test instantiates another
1685 * ContentProvider. A conflict develops because the two instances are
1686 * usually running against the same underlying data source (for example, an
1687 * sqlite database).
1688 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001689 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001690 * Implementing shutDown() avoids this conflict by providing a way to
1691 * terminate the ContentProvider. This method can also prevent memory leaks
1692 * from multiple instantiations of the ContentProvider, and it can ensure
1693 * unit test isolation by allowing you to completely clean up the test
1694 * fixture before moving on to the next test.
1695 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001696 */
1697 public void shutdown() {
1698 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1699 "connections are gracefully shutdown");
1700 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001701
1702 /**
1703 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001704 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001705 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001706 * @param fd The raw file descriptor that the dump is being sent to.
1707 * @param writer The PrintWriter to which you should dump your state. This will be
1708 * closed for you after you return.
1709 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001710 */
1711 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1712 writer.println("nothing to dump");
1713 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001714
1715 /** @hide */
1716 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1717 if (auth == null) return defaultUserId;
1718 int end = auth.indexOf('@');
1719 if (end == -1) return defaultUserId;
1720 String userIdString = auth.substring(0, end);
1721 try {
1722 return Integer.parseInt(userIdString);
1723 } catch (NumberFormatException e) {
1724 Log.w(TAG, "Error parsing userId.", e);
1725 return UserHandle.USER_NULL;
1726 }
1727 }
1728
1729 /** @hide */
1730 public static int getUserIdFromAuthority(String auth) {
1731 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1732 }
1733
1734 /** @hide */
1735 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1736 if (uri == null) return defaultUserId;
1737 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1738 }
1739
1740 /** @hide */
1741 public static int getUserIdFromUri(Uri uri) {
1742 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1743 }
1744
1745 /**
1746 * Removes userId part from authority string. Expects format:
1747 * userId@some.authority
1748 * If there is no userId in the authority, it symply returns the argument
1749 * @hide
1750 */
1751 public static String getAuthorityWithoutUserId(String auth) {
1752 if (auth == null) return null;
1753 int end = auth.indexOf('@');
1754 return auth.substring(end+1);
1755 }
1756
1757 /** @hide */
1758 public static Uri getUriWithoutUserId(Uri uri) {
1759 if (uri == null) return null;
1760 Uri.Builder builder = uri.buildUpon();
1761 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1762 return builder.build();
1763 }
1764
1765 /** @hide */
1766 public static boolean uriHasUserId(Uri uri) {
1767 if (uri == null) return false;
1768 return !TextUtils.isEmpty(uri.getUserInfo());
1769 }
1770
1771 /** @hide */
1772 public static Uri maybeAddUserId(Uri uri, int userId) {
1773 if (uri == null) return null;
1774 if (userId != UserHandle.USER_CURRENT
1775 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1776 if (!uriHasUserId(uri)) {
1777 //We don't add the user Id if there's already one
1778 Uri.Builder builder = uri.buildUpon();
1779 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1780 return builder.build();
1781 }
1782 }
1783 return uri;
1784 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001785}