blob: 0cff4c0e9a9b963022085cb281f60b8e5db1bd11 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.content;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Nicolas Prevot504d78e2014-06-26 10:07:33 +010020import static android.Manifest.permission.INTERACT_ACROSS_USERS;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070021
Dianne Hackborn35654b62013-01-14 17:38:02 -080022import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070023import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.pm.ProviderInfo;
25import android.content.res.AssetFileDescriptor;
26import android.content.res.Configuration;
27import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.database.SQLException;
29import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070030import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080032import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070033import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080034import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070035import android.os.ICancellationSignal;
36import android.os.OperationCanceledException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070038import android.os.Process;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070039import android.os.UserHandle;
Vasu Nori0c9e14a2010-08-04 13:31:48 -070040import android.util.Log;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010041import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042
43import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080044import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070046import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080047import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070048import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049
50/**
51 * Content providers are one of the primary building blocks of Android applications, providing
52 * content to applications. They encapsulate data and provide it to applications through the single
53 * {@link ContentResolver} interface. A content provider is only required if you need to share
54 * data between multiple applications. For example, the contacts data is used by multiple
55 * applications and must be stored in a content provider. If you don't need to share data amongst
56 * multiple applications you can use a database directly via
57 * {@link android.database.sqlite.SQLiteDatabase}.
58 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059 * <p>When a request is made via
60 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
61 * request to the content provider registered with the authority. The content provider can interpret
62 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
63 * URIs.</p>
64 *
65 * <p>The primary methods that need to be implemented are:
66 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070067 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 * <li>{@link #query} which returns data to the caller</li>
69 * <li>{@link #insert} which inserts new data into the content provider</li>
70 * <li>{@link #update} which updates existing data in the content provider</li>
71 * <li>{@link #delete} which deletes data from the content provider</li>
72 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
73 * </ul></p>
74 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070075 * <p class="caution">Data access methods (such as {@link #insert} and
76 * {@link #update}) may be called from many threads at once, and must be thread-safe.
77 * Other methods (such as {@link #onCreate}) are only called from the application
78 * main thread, and must avoid performing lengthy operations. See the method
79 * descriptions for their expected thread behavior.</p>
80 *
81 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
82 * ContentProvider instance, so subclasses don't have to worry about the details of
83 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070084 *
85 * <div class="special reference">
86 * <h3>Developer Guides</h3>
87 * <p>For more information about using content providers, read the
88 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
89 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -070091public abstract class ContentProvider implements ComponentCallbacks2 {
Vasu Nori0c9e14a2010-08-04 13:31:48 -070092 private static final String TAG = "ContentProvider";
93
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +090094 /*
95 * Note: if you add methods to ContentProvider, you must add similar methods to
96 * MockContentProvider.
97 */
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700100 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100101
102 // Since most Providers have only one authority, we keep both a String and a String[] to improve
103 // performance.
104 private String mAuthority;
105 private String[] mAuthorities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 private String mReadPermission;
107 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700108 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700109 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800110 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700111 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700113 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<String>();
114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 private Transport mTransport = new Transport();
116
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700117 /**
118 * Construct a ContentProvider instance. Content providers must be
119 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
120 * in the manifest</a>, accessed with {@link ContentResolver}, and created
121 * automatically by the system, so applications usually do not create
122 * ContentProvider instances directly.
123 *
124 * <p>At construction time, the object is uninitialized, and most fields and
125 * methods are unavailable. Subclasses should initialize themselves in
126 * {@link #onCreate}, not the constructor.
127 *
128 * <p>Content providers are created on the application main thread at
129 * application launch time. The constructor must not perform lengthy
130 * operations, or application startup will be delayed.
131 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900132 public ContentProvider() {
133 }
134
135 /**
136 * Constructor just for mocking.
137 *
138 * @param context A Context object which should be some mock instance (like the
139 * instance of {@link android.test.mock.MockContext}).
140 * @param readPermission The read permision you want this instance should have in the
141 * test, which is available via {@link #getReadPermission()}.
142 * @param writePermission The write permission you want this instance should have
143 * in the test, which is available via {@link #getWritePermission()}.
144 * @param pathPermissions The PathPermissions you want this instance should have
145 * in the test, which is available via {@link #getPathPermissions()}.
146 * @hide
147 */
148 public ContentProvider(
149 Context context,
150 String readPermission,
151 String writePermission,
152 PathPermission[] pathPermissions) {
153 mContext = context;
154 mReadPermission = readPermission;
155 mWritePermission = writePermission;
156 mPathPermissions = pathPermissions;
157 }
158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 /**
160 * Given an IContentProvider, try to coerce it back to the real
161 * ContentProvider object if it is running in the local process. This can
162 * be used if you know you are running in the same process as a provider,
163 * and want to get direct access to its implementation details. Most
164 * clients should not nor have a reason to use it.
165 *
166 * @param abstractInterface The ContentProvider interface that is to be
167 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800168 * @return If the IContentProvider is non-{@code null} and local, returns its actual
169 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 * @hide
171 */
172 public static ContentProvider coerceToLocalContentProvider(
173 IContentProvider abstractInterface) {
174 if (abstractInterface instanceof Transport) {
175 return ((Transport)abstractInterface).getContentProvider();
176 }
177 return null;
178 }
179
180 /**
181 * Binder object that deals with remoting.
182 *
183 * @hide
184 */
185 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800186 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800187 int mReadOp = AppOpsManager.OP_NONE;
188 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 ContentProvider getContentProvider() {
191 return ContentProvider.this;
192 }
193
Jeff Brownd2183652011-10-09 12:39:53 -0700194 @Override
195 public String getProviderName() {
196 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 }
198
Jeff Brown75ea64f2012-01-25 19:37:13 -0800199 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800200 public Cursor query(String callingPkg, Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800201 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800202 ICancellationSignal cancellationSignal) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100203 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100204 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800205 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800206 return rejectQuery(uri, projection, selection, selectionArgs, sortOrder,
207 CancellationSignal.fromTransport(cancellationSignal));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800208 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700209 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700210 try {
211 return ContentProvider.this.query(
212 uri, projection, selection, selectionArgs, sortOrder,
213 CancellationSignal.fromTransport(cancellationSignal));
214 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700215 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 }
218
Jeff Brown75ea64f2012-01-25 19:37:13 -0800219 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100221 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100222 uri = getUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 return ContentProvider.this.getType(uri);
224 }
225
Jeff Brown75ea64f2012-01-25 19:37:13 -0800226 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800227 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100228 validateIncomingUri(uri);
229 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100230 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800231 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800232 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800233 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700234 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700235 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100236 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700237 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700238 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 }
241
Jeff Brown75ea64f2012-01-25 19:37:13 -0800242 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800243 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100244 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100245 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800246 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800247 return 0;
248 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700249 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700250 try {
251 return ContentProvider.this.bulkInsert(uri, initialValues);
252 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700253 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 }
256
Jeff Brown75ea64f2012-01-25 19:37:13 -0800257 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800258 public ContentProviderResult[] applyBatch(String callingPkg,
259 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700260 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100261 int numOperations = operations.size();
262 final int[] userIds = new int[numOperations];
263 for (int i = 0; i < numOperations; i++) {
264 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100265 Uri uri = operation.getUri();
266 validateIncomingUri(uri);
267 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100268 if (userIds[i] != UserHandle.USER_CURRENT) {
269 // Removing the user id from the uri.
270 operation = new ContentProviderOperation(operation, true);
271 operations.set(i, operation);
272 }
Fred Quintana89437372009-05-15 15:10:40 -0700273 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800274 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800275 != AppOpsManager.MODE_ALLOWED) {
276 throw new OperationApplicationException("App op not allowed", 0);
277 }
Fred Quintana89437372009-05-15 15:10:40 -0700278 }
Fred Quintana89437372009-05-15 15:10:40 -0700279 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800280 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800281 != AppOpsManager.MODE_ALLOWED) {
282 throw new OperationApplicationException("App op not allowed", 0);
283 }
Fred Quintana89437372009-05-15 15:10:40 -0700284 }
285 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700286 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700287 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100288 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800289 if (results != null) {
290 for (int i = 0; i < results.length ; i++) {
291 if (userIds[i] != UserHandle.USER_CURRENT) {
292 // Adding the userId to the uri.
293 results[i] = new ContentProviderResult(results[i], userIds[i]);
294 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100295 }
296 }
297 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700298 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700299 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700300 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700301 }
302
Jeff Brown75ea64f2012-01-25 19:37:13 -0800303 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800304 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100305 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100306 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800307 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800308 return 0;
309 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700310 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700311 try {
312 return ContentProvider.this.delete(uri, selection, selectionArgs);
313 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700314 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 }
317
Jeff Brown75ea64f2012-01-25 19:37:13 -0800318 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800319 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100321 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100322 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800323 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800324 return 0;
325 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700326 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700327 try {
328 return ContentProvider.this.update(uri, values, selection, selectionArgs);
329 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700330 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 }
333
Jeff Brown75ea64f2012-01-25 19:37:13 -0800334 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700335 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800336 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
337 IBinder callerToken) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100338 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100339 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800340 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700341 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700342 try {
343 return ContentProvider.this.openFile(
344 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
345 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700346 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 }
349
Jeff Brown75ea64f2012-01-25 19:37:13 -0800350 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700351 public AssetFileDescriptor openAssetFile(
352 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100354 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100355 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800356 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700357 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700358 try {
359 return ContentProvider.this.openAssetFile(
360 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
361 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700362 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364 }
365
Jeff Brown75ea64f2012-01-25 19:37:13 -0800366 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800367 public Bundle call(String callingPkg, String method, String arg, Bundle extras) {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700368 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700369 try {
370 return ContentProvider.this.call(method, arg, extras);
371 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700372 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700373 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800374 }
375
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700376 @Override
377 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100378 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100379 uri = getUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700380 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
381 }
382
383 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800384 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700385 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100386 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100387 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800388 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700389 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700390 try {
391 return ContentProvider.this.openTypedAssetFile(
392 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
393 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700394 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700395 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700396 }
397
Jeff Brown75ea64f2012-01-25 19:37:13 -0800398 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700399 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800400 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800401 }
402
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700403 @Override
404 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100405 validateIncomingUri(uri);
406 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100407 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800408 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700409 return null;
410 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700411 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700412 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100413 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700414 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700415 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700416 }
417 }
418
419 @Override
420 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100421 validateIncomingUri(uri);
422 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100423 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800424 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700425 return null;
426 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700427 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700428 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100429 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700430 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700431 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700432 }
433 }
434
Dianne Hackbornff170242014-11-19 10:59:01 -0800435 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
436 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800437 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800438 if (enforceWritePermission(callingPkg, uri, callerToken)
439 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800440 throw new FileNotFoundException("App op not allowed");
441 }
442 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800443 if (enforceReadPermission(callingPkg, uri, callerToken)
444 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800445 throw new FileNotFoundException("App op not allowed");
446 }
447 }
448 }
449
Dianne Hackbornff170242014-11-19 10:59:01 -0800450 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
451 throws SecurityException {
452 enforceReadPermissionInner(uri, callerToken);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800453 if (mReadOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800454 return mAppOpsManager.noteOp(mReadOp, Binder.getCallingUid(), callingPkg);
455 }
456 return AppOpsManager.MODE_ALLOWED;
457 }
458
Dianne Hackbornff170242014-11-19 10:59:01 -0800459 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
460 throws SecurityException {
461 enforceWritePermissionInner(uri, callerToken);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800462 if (mWriteOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800463 return mAppOpsManager.noteOp(mWriteOp, Binder.getCallingUid(), callingPkg);
464 }
465 return AppOpsManager.MODE_ALLOWED;
466 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700467 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800468
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100469 boolean checkUser(int pid, int uid, Context context) {
470 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700471 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100472 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
473 == PERMISSION_GRANTED;
474 }
475
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700476 /** {@hide} */
Dianne Hackbornff170242014-11-19 10:59:01 -0800477 protected void enforceReadPermissionInner(Uri uri, IBinder callerToken)
478 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700479 final Context context = getContext();
480 final int pid = Binder.getCallingPid();
481 final int uid = Binder.getCallingUid();
482 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700483
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700484 if (UserHandle.isSameApp(uid, mMyUid)) {
485 return;
486 }
487
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100488 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700489 final String componentPerm = getReadPermission();
490 if (componentPerm != null) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800491 if (context.checkPermission(componentPerm, pid, uid, callerToken)
492 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700493 return;
494 } else {
495 missingPerm = componentPerm;
496 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700497 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700498
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700499 // track if unprotected read is allowed; any denied
500 // <path-permission> below removes this ability
501 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700502
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700503 final PathPermission[] pps = getPathPermissions();
504 if (pps != null) {
505 final String path = uri.getPath();
506 for (PathPermission pp : pps) {
507 final String pathPerm = pp.getReadPermission();
508 if (pathPerm != null && pp.match(path)) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800509 if (context.checkPermission(pathPerm, pid, uid, callerToken)
510 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700511 return;
512 } else {
513 // any denied <path-permission> means we lose
514 // default <provider> access.
515 allowDefaultRead = false;
516 missingPerm = pathPerm;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700517 }
518 }
519 }
520 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700521
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700522 // if we passed <path-permission> checks above, and no default
523 // <provider> permission, then allow access.
524 if (allowDefaultRead) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700526
527 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800528 final int callingUserId = UserHandle.getUserId(uid);
529 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
530 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800531 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
532 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700533 return;
534 }
535
536 final String failReason = mExported
537 ? " requires " + missingPerm + ", or grantUriPermission()"
538 : " requires the provider be exported, or grantUriPermission()";
539 throw new SecurityException("Permission Denial: reading "
540 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
541 + ", uid=" + uid + failReason);
542 }
543
544 /** {@hide} */
Dianne Hackbornff170242014-11-19 10:59:01 -0800545 protected void enforceWritePermissionInner(Uri uri, IBinder callerToken)
546 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700547 final Context context = getContext();
548 final int pid = Binder.getCallingPid();
549 final int uid = Binder.getCallingUid();
550 String missingPerm = null;
551
552 if (UserHandle.isSameApp(uid, mMyUid)) {
553 return;
554 }
555
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100556 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700557 final String componentPerm = getWritePermission();
558 if (componentPerm != null) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800559 if (context.checkPermission(componentPerm, pid, uid, callerToken)
560 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700561 return;
562 } else {
563 missingPerm = componentPerm;
564 }
565 }
566
567 // track if unprotected write is allowed; any denied
568 // <path-permission> below removes this ability
569 boolean allowDefaultWrite = (componentPerm == null);
570
571 final PathPermission[] pps = getPathPermissions();
572 if (pps != null) {
573 final String path = uri.getPath();
574 for (PathPermission pp : pps) {
575 final String pathPerm = pp.getWritePermission();
576 if (pathPerm != null && pp.match(path)) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800577 if (context.checkPermission(pathPerm, pid, uid, callerToken)
578 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700579 return;
580 } else {
581 // any denied <path-permission> means we lose
582 // default <provider> access.
583 allowDefaultWrite = false;
584 missingPerm = pathPerm;
585 }
586 }
587 }
588 }
589
590 // if we passed <path-permission> checks above, and no default
591 // <provider> permission, then allow access.
592 if (allowDefaultWrite) return;
593 }
594
595 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800596 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
597 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700598 return;
599 }
600
601 final String failReason = mExported
602 ? " requires " + missingPerm + ", or grantUriPermission()"
603 : " requires the provider be exported, or grantUriPermission()";
604 throw new SecurityException("Permission Denial: writing "
605 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
606 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 }
608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700610 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800611 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 * constructor.
613 */
614 public final Context getContext() {
615 return mContext;
616 }
617
618 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700619 * Set the calling package, returning the current value (or {@code null})
620 * which can be used later to restore the previous state.
621 */
622 private String setCallingPackage(String callingPackage) {
623 final String original = mCallingPackage.get();
624 mCallingPackage.set(callingPackage);
625 return original;
626 }
627
628 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700629 * Return the package name of the caller that initiated the request being
630 * processed on the current thread. The returned package will have been
631 * verified to belong to the calling UID. Returns {@code null} if not
632 * currently processing a request.
633 * <p>
634 * This will always return {@code null} when processing
635 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
636 *
637 * @see Binder#getCallingUid()
638 * @see Context#grantUriPermission(String, Uri, int)
639 * @throws SecurityException if the calling package doesn't belong to the
640 * calling UID.
641 */
642 public final String getCallingPackage() {
643 final String pkg = mCallingPackage.get();
644 if (pkg != null) {
645 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
646 }
647 return pkg;
648 }
649
650 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100651 * Change the authorities of the ContentProvider.
652 * This is normally set for you from its manifest information when the provider is first
653 * created.
654 * @hide
655 * @param authorities the semi-colon separated authorities of the ContentProvider.
656 */
657 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100658 if (authorities != null) {
659 if (authorities.indexOf(';') == -1) {
660 mAuthority = authorities;
661 mAuthorities = null;
662 } else {
663 mAuthority = null;
664 mAuthorities = authorities.split(";");
665 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100666 }
667 }
668
669 /** @hide */
670 protected final boolean matchesOurAuthorities(String authority) {
671 if (mAuthority != null) {
672 return mAuthority.equals(authority);
673 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100674 if (mAuthorities != null) {
675 int length = mAuthorities.length;
676 for (int i = 0; i < length; i++) {
677 if (mAuthorities[i].equals(authority)) return true;
678 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100679 }
680 return false;
681 }
682
683
684 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 * Change the permission required to read data from the content
686 * provider. This is normally set for you from its manifest information
687 * when the provider is first created.
688 *
689 * @param permission Name of the permission required for read-only access.
690 */
691 protected final void setReadPermission(String permission) {
692 mReadPermission = permission;
693 }
694
695 /**
696 * Return the name of the permission required for read-only access to
697 * this content provider. This method can be called from multiple
698 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800699 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
700 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 */
702 public final String getReadPermission() {
703 return mReadPermission;
704 }
705
706 /**
707 * Change the permission required to read and write data in the content
708 * provider. This is normally set for you from its manifest information
709 * when the provider is first created.
710 *
711 * @param permission Name of the permission required for read/write access.
712 */
713 protected final void setWritePermission(String permission) {
714 mWritePermission = permission;
715 }
716
717 /**
718 * Return the name of the permission required for read/write access to
719 * this content provider. This method can be called from multiple
720 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800721 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
722 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 */
724 public final String getWritePermission() {
725 return mWritePermission;
726 }
727
728 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700729 * Change the path-based permission required to read and/or write data in
730 * the content provider. This is normally set for you from its manifest
731 * information when the provider is first created.
732 *
733 * @param permissions Array of path permission descriptions.
734 */
735 protected final void setPathPermissions(PathPermission[] permissions) {
736 mPathPermissions = permissions;
737 }
738
739 /**
740 * Return the path-based permissions required for read and/or write access to
741 * this content provider. This method can be called from multiple
742 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800743 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
744 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700745 */
746 public final PathPermission[] getPathPermissions() {
747 return mPathPermissions;
748 }
749
Dianne Hackborn35654b62013-01-14 17:38:02 -0800750 /** @hide */
751 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800752 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800753 mTransport.mReadOp = readOp;
754 mTransport.mWriteOp = writeOp;
755 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800756 }
757
Dianne Hackborn961321f2013-02-05 17:22:41 -0800758 /** @hide */
759 public AppOpsManager getAppOpsManager() {
760 return mTransport.mAppOpsManager;
761 }
762
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700763 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700764 * Implement this to initialize your content provider on startup.
765 * This method is called for all registered content providers on the
766 * application main thread at application launch time. It must not perform
767 * lengthy operations, or application startup will be delayed.
768 *
769 * <p>You should defer nontrivial initialization (such as opening,
770 * upgrading, and scanning databases) until the content provider is used
771 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
772 * keeps application startup fast, avoids unnecessary work if the provider
773 * turns out not to be needed, and stops database errors (such as a full
774 * disk) from halting application launch.
775 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700776 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700777 * is a helpful utility class that makes it easy to manage databases,
778 * and will automatically defer opening until first use. If you do use
779 * SQLiteOpenHelper, make sure to avoid calling
780 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
781 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
782 * from this method. (Instead, override
783 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
784 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 *
786 * @return true if the provider was successfully loaded, false otherwise
787 */
788 public abstract boolean onCreate();
789
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700790 /**
791 * {@inheritDoc}
792 * This method is always called on the application main thread, and must
793 * not perform lengthy operations.
794 *
795 * <p>The default content provider implementation does nothing.
796 * Override this method to take appropriate action.
797 * (Content providers do not usually care about things like screen
798 * orientation, but may want to know about locale changes.)
799 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 public void onConfigurationChanged(Configuration newConfig) {
801 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700802
803 /**
804 * {@inheritDoc}
805 * This method is always called on the application main thread, and must
806 * not perform lengthy operations.
807 *
808 * <p>The default content provider implementation does nothing.
809 * Subclasses may override this method to take appropriate action.
810 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 public void onLowMemory() {
812 }
813
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700814 public void onTrimMemory(int level) {
815 }
816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800818 * @hide
819 * Implementation when a caller has performed a query on the content
820 * provider, but that call has been rejected for the operation given
821 * to {@link #setAppOps(int, int)}. The default implementation
822 * rewrites the <var>selection</var> argument to include a condition
823 * that is never true (so will always result in an empty cursor)
824 * and calls through to {@link #query(android.net.Uri, String[], String, String[],
825 * String, android.os.CancellationSignal)} with that.
826 */
827 public Cursor rejectQuery(Uri uri, String[] projection,
828 String selection, String[] selectionArgs, String sortOrder,
829 CancellationSignal cancellationSignal) {
830 // The read is not allowed... to fake it out, we replace the given
831 // selection statement with a dummy one that will always be false.
832 // This way we will get a cursor back that has the correct structure
833 // but contains no rows.
Dianne Hackborn9fa39bd2013-03-22 18:42:14 -0700834 if (selection == null || selection.isEmpty()) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800835 selection = "'A' = 'B'";
836 } else {
837 selection = "'A' = 'B' AND (" + selection + ")";
838 }
839 return query(uri, projection, selection, selectionArgs, sortOrder, cancellationSignal);
840 }
841
842 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700843 * Implement this to handle query requests from clients.
844 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800845 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
846 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 * <p>
848 * Example client call:<p>
849 * <pre>// Request a specific record.
850 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000851 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 projection, // Which columns to return.
853 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000854 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 People.NAME + " ASC"); // Sort order.</pre>
856 * Example implementation:<p>
857 * <pre>// SQLiteQueryBuilder is a helper class that creates the
858 // proper SQL syntax for us.
859 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
860
861 // Set the table we're querying.
862 qBuilder.setTables(DATABASE_TABLE_NAME);
863
864 // If the query ends in a specific record number, we're
865 // being asked for a specific record, so set the
866 // WHERE clause in our query.
867 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
868 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
869 }
870
871 // Make the query.
872 Cursor c = qBuilder.query(mDb,
873 projection,
874 selection,
875 selectionArgs,
876 groupBy,
877 having,
878 sortOrder);
879 c.setNotificationUri(getContext().getContentResolver(), uri);
880 return c;</pre>
881 *
882 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000883 * if the client is requesting a specific record, the URI will end in a record number
884 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
885 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800887 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800889 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000890 * @param selectionArgs You may include ?s in selection, which will be replaced by
891 * the values from selectionArgs, in order that they appear in the selection.
892 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800894 * If {@code null} then the provider is free to define the sort order.
895 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 */
897 public abstract Cursor query(Uri uri, String[] projection,
898 String selection, String[] selectionArgs, String sortOrder);
899
Fred Quintana5bba6322009-10-05 14:21:12 -0700900 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800901 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800902 * This method can be called from multiple threads, as described in
903 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
904 * and Threads</a>.
905 * <p>
906 * Example client call:<p>
907 * <pre>// Request a specific record.
908 * Cursor managedCursor = managedQuery(
909 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
910 projection, // Which columns to return.
911 null, // WHERE clause.
912 null, // WHERE clause value substitution
913 People.NAME + " ASC"); // Sort order.</pre>
914 * Example implementation:<p>
915 * <pre>// SQLiteQueryBuilder is a helper class that creates the
916 // proper SQL syntax for us.
917 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
918
919 // Set the table we're querying.
920 qBuilder.setTables(DATABASE_TABLE_NAME);
921
922 // If the query ends in a specific record number, we're
923 // being asked for a specific record, so set the
924 // WHERE clause in our query.
925 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
926 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
927 }
928
929 // Make the query.
930 Cursor c = qBuilder.query(mDb,
931 projection,
932 selection,
933 selectionArgs,
934 groupBy,
935 having,
936 sortOrder);
937 c.setNotificationUri(getContext().getContentResolver(), uri);
938 return c;</pre>
939 * <p>
940 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800941 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
942 * signal to ensure correct operation on older versions of the Android Framework in
943 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800944 *
945 * @param uri The URI to query. This will be the full URI sent by the client;
946 * if the client is requesting a specific record, the URI will end in a record number
947 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
948 * that _id value.
949 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800950 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800951 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800952 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800953 * @param selectionArgs You may include ?s in selection, which will be replaced by
954 * the values from selectionArgs, in order that they appear in the selection.
955 * The values will be bound as Strings.
956 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800957 * If {@code null} then the provider is free to define the sort order.
958 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800959 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
960 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800961 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800962 */
963 public Cursor query(Uri uri, String[] projection,
964 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800965 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800966 return query(uri, projection, selection, selectionArgs, sortOrder);
967 }
968
969 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700970 * Implement this to handle requests for the MIME type of the data at the
971 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 * <code>vnd.android.cursor.item</code> for a single record,
973 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700974 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800975 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
976 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700978 * <p>Note that there are no permissions needed for an application to
979 * access this information; if your content provider requires read and/or
980 * write permissions, or is not exported, all applications can still call
981 * this method regardless of their access permissions. This allows them
982 * to retrieve the MIME type for a URI when dispatching intents.
983 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800985 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 */
987 public abstract String getType(Uri uri);
988
989 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700990 * Implement this to support canonicalization of URIs that refer to your
991 * content provider. A canonical URI is one that can be transported across
992 * devices, backup/restore, and other contexts, and still be able to refer
993 * to the same data item. Typically this is implemented by adding query
994 * params to the URI allowing the content provider to verify that an incoming
995 * canonical URI references the same data as it was originally intended for and,
996 * if it doesn't, to find that data (if it exists) in the current environment.
997 *
998 * <p>For example, if the content provider holds people and a normal URI in it
999 * is created with a row index into that people database, the cananical representation
1000 * may have an additional query param at the end which specifies the name of the
1001 * person it is intended for. Later calls into the provider with that URI will look
1002 * up the row of that URI's base index and, if it doesn't match or its entry's
1003 * name doesn't match the name in the query param, perform a query on its database
1004 * to find the correct row to operate on.</p>
1005 *
1006 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1007 * URIs (including this one) must perform this verification and recovery of any
1008 * canonical URIs they receive. In addition, you must also implement
1009 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1010 *
1011 * <p>The default implementation of this method returns null, indicating that
1012 * canonical URIs are not supported.</p>
1013 *
1014 * @param url The Uri to canonicalize.
1015 *
1016 * @return Return the canonical representation of <var>url</var>, or null if
1017 * canonicalization of that Uri is not supported.
1018 */
1019 public Uri canonicalize(Uri url) {
1020 return null;
1021 }
1022
1023 /**
1024 * Remove canonicalization from canonical URIs previously returned by
1025 * {@link #canonicalize}. For example, if your implementation is to add
1026 * a query param to canonicalize a URI, this method can simply trip any
1027 * query params on the URI. The default implementation always returns the
1028 * same <var>url</var> that was passed in.
1029 *
1030 * @param url The Uri to remove any canonicalization from.
1031 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001032 * @return Return the non-canonical representation of <var>url</var>, return
1033 * the <var>url</var> as-is if there is nothing to do, or return null if
1034 * the data identified by the canonical representation can not be found in
1035 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001036 */
1037 public Uri uncanonicalize(Uri url) {
1038 return url;
1039 }
1040
1041 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001042 * @hide
1043 * Implementation when a caller has performed an insert on the content
1044 * provider, but that call has been rejected for the operation given
1045 * to {@link #setAppOps(int, int)}. The default implementation simply
1046 * returns a dummy URI that is the base URI with a 0 path element
1047 * appended.
1048 */
1049 public Uri rejectInsert(Uri uri, ContentValues values) {
1050 // If not allowed, we need to return some reasonable URI. Maybe the
1051 // content provider should be responsible for this, but for now we
1052 // will just return the base URI with a dummy '0' tagged on to it.
1053 // You shouldn't be able to read if you can't write, anyway, so it
1054 // shouldn't matter much what is returned.
1055 return uri.buildUpon().appendPath("0").build();
1056 }
1057
1058 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001059 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1061 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001062 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001063 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1064 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001065 * @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 -08001066 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001067 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 * @return The URI for the newly inserted item.
1069 */
1070 public abstract Uri insert(Uri uri, ContentValues values);
1071
1072 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001073 * Override this to handle requests to insert a set of new rows, or the
1074 * default implementation will iterate over the values and call
1075 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1077 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001078 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001079 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1080 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 *
1082 * @param uri The content:// URI of the insertion request.
1083 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001084 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 * @return The number of values that were inserted.
1086 */
1087 public int bulkInsert(Uri uri, ContentValues[] values) {
1088 int numValues = values.length;
1089 for (int i = 0; i < numValues; i++) {
1090 insert(uri, values[i]);
1091 }
1092 return numValues;
1093 }
1094
1095 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001096 * Implement this to handle requests to delete one or more rows.
1097 * The implementation should apply the selection clause when performing
1098 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001099 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001101 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001102 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1103 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 *
1105 * <p>The implementation is responsible for parsing out a row ID at the end
1106 * of the URI, if a specific row is being deleted. That is, the client would
1107 * pass in <code>content://contacts/people/22</code> and the implementation is
1108 * responsible for parsing the record number (22) when creating a SQL statement.
1109 *
1110 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1111 * @param selection An optional restriction to apply to rows when deleting.
1112 * @return The number of rows affected.
1113 * @throws SQLException
1114 */
1115 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
1116
1117 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001118 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001119 * The implementation should update all rows matching the selection
1120 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1122 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001123 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001124 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1125 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 *
1127 * @param uri The URI to query. This can potentially have a record ID if this
1128 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001129 * @param values A set of column_name/value pairs to update in the database.
1130 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 * @param selection An optional filter to match rows to update.
1132 * @return the number of rows affected.
1133 */
1134 public abstract int update(Uri uri, ContentValues values, String selection,
1135 String[] selectionArgs);
1136
1137 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001138 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001139 * The default implementation always throws {@link FileNotFoundException}.
1140 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001141 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1142 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001143 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001144 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1145 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001146 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 *
1148 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1149 * their responsibility to close it when done. That is, the implementation
1150 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001151 * <p>
1152 * If opened with the exclusive "r" or "w" modes, the returned
1153 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1154 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1155 * supports seeking.
1156 * <p>
1157 * If you need to detect when the returned ParcelFileDescriptor has been
1158 * closed, or if the remote process has crashed or encountered some other
1159 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1160 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1161 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1162 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001164 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1165 * to return the appropriate MIME type for the data returned here with
1166 * the same URI. This will allow intent resolution to automatically determine the data MIME
1167 * type and select the appropriate matching targets as part of its operation.</p>
1168 *
1169 * <p class="note">For better interoperability with other applications, it is recommended
1170 * that for any URIs that can be opened, you also support queries on them
1171 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1172 * You may also want to support other common columns if you have additional meta-data
1173 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1174 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1175 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 * @param uri The URI whose file is to be opened.
1177 * @param mode Access mode for the file. May be "r" for read-only access,
1178 * "rw" for read and write access, or "rwt" for read and write access
1179 * that truncates any existing file.
1180 *
1181 * @return Returns a new ParcelFileDescriptor which you can use to access
1182 * the file.
1183 *
1184 * @throws FileNotFoundException Throws FileNotFoundException if there is
1185 * no file associated with the given URI or the mode is invalid.
1186 * @throws SecurityException Throws SecurityException if the caller does
1187 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001188 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 * @see #openAssetFile(Uri, String)
1190 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001191 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001192 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001193 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 public ParcelFileDescriptor openFile(Uri uri, String mode)
1195 throws FileNotFoundException {
1196 throw new FileNotFoundException("No files supported by provider at "
1197 + uri);
1198 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001201 * Override this to handle requests to open a file blob.
1202 * The default implementation always throws {@link FileNotFoundException}.
1203 * This method can be called from multiple threads, as described in
1204 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1205 * and Threads</a>.
1206 *
1207 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1208 * to the caller. This way large data (such as images and documents) can be
1209 * returned without copying the content.
1210 *
1211 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1212 * their responsibility to close it when done. That is, the implementation
1213 * of this method should create a new ParcelFileDescriptor for each call.
1214 * <p>
1215 * If opened with the exclusive "r" or "w" modes, the returned
1216 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1217 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1218 * supports seeking.
1219 * <p>
1220 * If you need to detect when the returned ParcelFileDescriptor has been
1221 * closed, or if the remote process has crashed or encountered some other
1222 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1223 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1224 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1225 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1226 *
1227 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1228 * to return the appropriate MIME type for the data returned here with
1229 * the same URI. This will allow intent resolution to automatically determine the data MIME
1230 * type and select the appropriate matching targets as part of its operation.</p>
1231 *
1232 * <p class="note">For better interoperability with other applications, it is recommended
1233 * that for any URIs that can be opened, you also support queries on them
1234 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1235 * You may also want to support other common columns if you have additional meta-data
1236 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1237 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1238 *
1239 * @param uri The URI whose file is to be opened.
1240 * @param mode Access mode for the file. May be "r" for read-only access,
1241 * "w" for write-only access, "rw" for read and write access, or
1242 * "rwt" for read and write access that truncates any existing
1243 * file.
1244 * @param signal A signal to cancel the operation in progress, or
1245 * {@code null} if none. For example, if you are downloading a
1246 * file from the network to service a "rw" mode request, you
1247 * should periodically call
1248 * {@link CancellationSignal#throwIfCanceled()} to check whether
1249 * the client has canceled the request and abort the download.
1250 *
1251 * @return Returns a new ParcelFileDescriptor which you can use to access
1252 * the file.
1253 *
1254 * @throws FileNotFoundException Throws FileNotFoundException if there is
1255 * no file associated with the given URI or the mode is invalid.
1256 * @throws SecurityException Throws SecurityException if the caller does
1257 * not have permission to access the file.
1258 *
1259 * @see #openAssetFile(Uri, String)
1260 * @see #openFileHelper(Uri, String)
1261 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001262 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001263 */
1264 public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
1265 throws FileNotFoundException {
1266 return openFile(uri, mode);
1267 }
1268
1269 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 * This is like {@link #openFile}, but can be implemented by providers
1271 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001272 * inside of their .apk.
1273 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001274 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1275 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001276 *
1277 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001278 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001279 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1281 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1282 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001283 * <p>
1284 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1285 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001286 *
1287 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 * should create the AssetFileDescriptor with
1289 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001290 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001292 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1293 * to return the appropriate MIME type for the data returned here with
1294 * the same URI. This will allow intent resolution to automatically determine the data MIME
1295 * type and select the appropriate matching targets as part of its operation.</p>
1296 *
1297 * <p class="note">For better interoperability with other applications, it is recommended
1298 * that for any URIs that can be opened, you also support queries on them
1299 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1300 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 * @param uri The URI whose file is to be opened.
1302 * @param mode Access mode for the file. May be "r" for read-only access,
1303 * "w" for write-only access (erasing whatever data is currently in
1304 * the file), "wa" for write-only access to append to any existing data,
1305 * "rw" for read and write access on any existing data, and "rwt" for read
1306 * and write access that truncates any existing file.
1307 *
1308 * @return Returns a new AssetFileDescriptor which you can use to access
1309 * the file.
1310 *
1311 * @throws FileNotFoundException Throws FileNotFoundException if there is
1312 * no file associated with the given URI or the mode is invalid.
1313 * @throws SecurityException Throws SecurityException if the caller does
1314 * not have permission to access the file.
1315 *
1316 * @see #openFile(Uri, String)
1317 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001318 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 */
1320 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
1321 throws FileNotFoundException {
1322 ParcelFileDescriptor fd = openFile(uri, mode);
1323 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1324 }
1325
1326 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001327 * This is like {@link #openFile}, but can be implemented by providers
1328 * that need to be able to return sub-sections of files, often assets
1329 * inside of their .apk.
1330 * This method can be called from multiple threads, as described in
1331 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1332 * and Threads</a>.
1333 *
1334 * <p>If you implement this, your clients must be able to deal with such
1335 * file slices, either directly with
1336 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1337 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1338 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1339 * methods.
1340 * <p>
1341 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1342 * streaming of data.
1343 *
1344 * <p class="note">If you are implementing this to return a full file, you
1345 * should create the AssetFileDescriptor with
1346 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1347 * applications that cannot handle sub-sections of files.</p>
1348 *
1349 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1350 * to return the appropriate MIME type for the data returned here with
1351 * the same URI. This will allow intent resolution to automatically determine the data MIME
1352 * type and select the appropriate matching targets as part of its operation.</p>
1353 *
1354 * <p class="note">For better interoperability with other applications, it is recommended
1355 * that for any URIs that can be opened, you also support queries on them
1356 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1357 *
1358 * @param uri The URI whose file is to be opened.
1359 * @param mode Access mode for the file. May be "r" for read-only access,
1360 * "w" for write-only access (erasing whatever data is currently in
1361 * the file), "wa" for write-only access to append to any existing data,
1362 * "rw" for read and write access on any existing data, and "rwt" for read
1363 * and write access that truncates any existing file.
1364 * @param signal A signal to cancel the operation in progress, or
1365 * {@code null} if none. For example, if you are downloading a
1366 * file from the network to service a "rw" mode request, you
1367 * should periodically call
1368 * {@link CancellationSignal#throwIfCanceled()} to check whether
1369 * the client has canceled the request and abort the download.
1370 *
1371 * @return Returns a new AssetFileDescriptor which you can use to access
1372 * the file.
1373 *
1374 * @throws FileNotFoundException Throws FileNotFoundException if there is
1375 * no file associated with the given URI or the mode is invalid.
1376 * @throws SecurityException Throws SecurityException if the caller does
1377 * not have permission to access the file.
1378 *
1379 * @see #openFile(Uri, String)
1380 * @see #openFileHelper(Uri, String)
1381 * @see #getType(android.net.Uri)
1382 */
1383 public AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)
1384 throws FileNotFoundException {
1385 return openAssetFile(uri, mode);
1386 }
1387
1388 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 * Convenience for subclasses that wish to implement {@link #openFile}
1390 * by looking up a column named "_data" at the given URI.
1391 *
1392 * @param uri The URI to be opened.
1393 * @param mode The file mode. May be "r" for read-only access,
1394 * "w" for write-only access (erasing whatever data is currently in
1395 * the file), "wa" for write-only access to append to any existing data,
1396 * "rw" for read and write access on any existing data, and "rwt" for read
1397 * and write access that truncates any existing file.
1398 *
1399 * @return Returns a new ParcelFileDescriptor that can be used by the
1400 * client to access the file.
1401 */
1402 protected final ParcelFileDescriptor openFileHelper(Uri uri,
1403 String mode) throws FileNotFoundException {
1404 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1405 int count = (c != null) ? c.getCount() : 0;
1406 if (count != 1) {
1407 // If there is not exactly one result, throw an appropriate
1408 // exception.
1409 if (c != null) {
1410 c.close();
1411 }
1412 if (count == 0) {
1413 throw new FileNotFoundException("No entry for " + uri);
1414 }
1415 throw new FileNotFoundException("Multiple items at " + uri);
1416 }
1417
1418 c.moveToFirst();
1419 int i = c.getColumnIndex("_data");
1420 String path = (i >= 0 ? c.getString(i) : null);
1421 c.close();
1422 if (path == null) {
1423 throw new FileNotFoundException("Column _data not found.");
1424 }
1425
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001426 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 return ParcelFileDescriptor.open(new File(path), modeBits);
1428 }
1429
1430 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001431 * Called by a client to determine the types of data streams that this
1432 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001433 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001434 * of a particular type, return that MIME type if it matches the given
1435 * mimeTypeFilter. If it can perform type conversions, return an array
1436 * of all supported MIME types that match mimeTypeFilter.
1437 *
1438 * @param uri The data in the content provider being queried.
1439 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001440 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001441 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001442 * given mimeTypeFilter. Otherwise returns an array of all available
1443 * concrete MIME types.
1444 *
1445 * @see #getType(Uri)
1446 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001447 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001448 */
1449 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
1450 return null;
1451 }
1452
1453 /**
1454 * Called by a client to open a read-only stream containing data of a
1455 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1456 * except the file can only be read-only and the content provider may
1457 * perform data conversions to generate data of the desired type.
1458 *
1459 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001460 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001461 * {@link #openAssetFile(Uri, String)}.
1462 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001463 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001464 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001465 * <p>
1466 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1467 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001468 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001469 * <p class="note">For better interoperability with other applications, it is recommended
1470 * that for any URIs that can be opened, you also support queries on them
1471 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1472 * You may also want to support other common columns if you have additional meta-data
1473 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1474 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1475 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001476 * @param uri The data in the content provider being queried.
1477 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001478 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001479 * requirements; in this case the content provider will pick its best
1480 * type matching the pattern.
1481 * @param opts Additional options from the client. The definitions of
1482 * these are specific to the content provider being called.
1483 *
1484 * @return Returns a new AssetFileDescriptor from which the client can
1485 * read data of the desired type.
1486 *
1487 * @throws FileNotFoundException Throws FileNotFoundException if there is
1488 * no file associated with the given URI or the mode is invalid.
1489 * @throws SecurityException Throws SecurityException if the caller does
1490 * not have permission to access the data.
1491 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1492 * content provider does not support the requested MIME type.
1493 *
1494 * @see #getStreamTypes(Uri, String)
1495 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001496 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001497 */
1498 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
1499 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001500 if ("*/*".equals(mimeTypeFilter)) {
1501 // If they can take anything, the untyped open call is good enough.
1502 return openAssetFile(uri, "r");
1503 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001504 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001505 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001506 // Use old untyped open call if this provider has a type for this
1507 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001508 return openAssetFile(uri, "r");
1509 }
1510 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1511 }
1512
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001513
1514 /**
1515 * Called by a client to open a read-only stream containing data of a
1516 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1517 * except the file can only be read-only and the content provider may
1518 * perform data conversions to generate data of the desired type.
1519 *
1520 * <p>The default implementation compares the given mimeType against the
1521 * result of {@link #getType(Uri)} and, if they match, simply calls
1522 * {@link #openAssetFile(Uri, String)}.
1523 *
1524 * <p>See {@link ClipData} for examples of the use and implementation
1525 * of this method.
1526 * <p>
1527 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1528 * streaming of data.
1529 *
1530 * <p class="note">For better interoperability with other applications, it is recommended
1531 * that for any URIs that can be opened, you also support queries on them
1532 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1533 * You may also want to support other common columns if you have additional meta-data
1534 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1535 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1536 *
1537 * @param uri The data in the content provider being queried.
1538 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001539 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001540 * requirements; in this case the content provider will pick its best
1541 * type matching the pattern.
1542 * @param opts Additional options from the client. The definitions of
1543 * these are specific to the content provider being called.
1544 * @param signal A signal to cancel the operation in progress, or
1545 * {@code null} if none. For example, if you are downloading a
1546 * file from the network to service a "rw" mode request, you
1547 * should periodically call
1548 * {@link CancellationSignal#throwIfCanceled()} to check whether
1549 * the client has canceled the request and abort the download.
1550 *
1551 * @return Returns a new AssetFileDescriptor from which the client can
1552 * read data of the desired type.
1553 *
1554 * @throws FileNotFoundException Throws FileNotFoundException if there is
1555 * no file associated with the given URI or the mode is invalid.
1556 * @throws SecurityException Throws SecurityException if the caller does
1557 * not have permission to access the data.
1558 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1559 * content provider does not support the requested MIME type.
1560 *
1561 * @see #getStreamTypes(Uri, String)
1562 * @see #openAssetFile(Uri, String)
1563 * @see ClipDescription#compareMimeTypes(String, String)
1564 */
1565 public AssetFileDescriptor openTypedAssetFile(
1566 Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)
1567 throws FileNotFoundException {
1568 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1569 }
1570
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001571 /**
1572 * Interface to write a stream of data to a pipe. Use with
1573 * {@link ContentProvider#openPipeHelper}.
1574 */
1575 public interface PipeDataWriter<T> {
1576 /**
1577 * Called from a background thread to stream data out to a pipe.
1578 * Note that the pipe is blocking, so this thread can block on
1579 * writes for an arbitrary amount of time if the client is slow
1580 * at reading.
1581 *
1582 * @param output The pipe where data should be written. This will be
1583 * closed for you upon returning from this function.
1584 * @param uri The URI whose data is to be written.
1585 * @param mimeType The desired type of data to be written.
1586 * @param opts Options supplied by caller.
1587 * @param args Your own custom arguments.
1588 */
1589 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
1590 Bundle opts, T args);
1591 }
1592
1593 /**
1594 * A helper function for implementing {@link #openTypedAssetFile}, for
1595 * creating a data pipe and background thread allowing you to stream
1596 * generated data back to the client. This function returns a new
1597 * ParcelFileDescriptor that should be returned to the caller (the caller
1598 * is responsible for closing it).
1599 *
1600 * @param uri The URI whose data is to be written.
1601 * @param mimeType The desired type of data to be written.
1602 * @param opts Options supplied by caller.
1603 * @param args Your own custom arguments.
1604 * @param func Interface implementing the function that will actually
1605 * stream the data.
1606 * @return Returns a new ParcelFileDescriptor holding the read side of
1607 * the pipe. This should be returned to the caller for reading; the caller
1608 * is responsible for closing it when done.
1609 */
1610 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
1611 final Bundle opts, final T args, final PipeDataWriter<T> func)
1612 throws FileNotFoundException {
1613 try {
1614 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1615
1616 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1617 @Override
1618 protected Object doInBackground(Object... params) {
1619 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1620 try {
1621 fds[1].close();
1622 } catch (IOException e) {
1623 Log.w(TAG, "Failure closing pipe", e);
1624 }
1625 return null;
1626 }
1627 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001628 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001629
1630 return fds[0];
1631 } catch (IOException e) {
1632 throw new FileNotFoundException("failure making pipe");
1633 }
1634 }
1635
1636 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 * Returns true if this instance is a temporary content provider.
1638 * @return true if this instance is a temporary content provider
1639 */
1640 protected boolean isTemporary() {
1641 return false;
1642 }
1643
1644 /**
1645 * Returns the Binder object for this provider.
1646 *
1647 * @return the Binder object for this provider
1648 * @hide
1649 */
1650 public IContentProvider getIContentProvider() {
1651 return mTransport;
1652 }
1653
1654 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001655 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1656 * when directly instantiating the provider for testing.
1657 * @hide
1658 */
1659 public void attachInfoForTesting(Context context, ProviderInfo info) {
1660 attachInfo(context, info, true);
1661 }
1662
1663 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 * After being instantiated, this is called to tell the content provider
1665 * about itself.
1666 *
1667 * @param context The context this provider is running in
1668 * @param info Registered information about this content provider
1669 */
1670 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001671 attachInfo(context, info, false);
1672 }
1673
1674 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001675 mNoPerms = testing;
1676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 /*
1678 * Only allow it to be set once, so after the content service gives
1679 * this to us clients can't change it.
1680 */
1681 if (mContext == null) {
1682 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001683 if (context != null) {
1684 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1685 Context.APP_OPS_SERVICE);
1686 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001687 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 if (info != null) {
1689 setReadPermission(info.readPermission);
1690 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001691 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001692 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001693 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001694 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 }
1696 ContentProvider.this.onCreate();
1697 }
1698 }
Fred Quintanace31b232009-05-04 16:01:15 -07001699
1700 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001701 * Override this to handle requests to perform a batch of operations, or the
1702 * default implementation will iterate over the operations and call
1703 * {@link ContentProviderOperation#apply} on each of them.
1704 * If all calls to {@link ContentProviderOperation#apply} succeed
1705 * then a {@link ContentProviderResult} array with as many
1706 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001707 * fail, it is up to the implementation how many of the others take effect.
1708 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001709 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1710 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001711 *
Fred Quintanace31b232009-05-04 16:01:15 -07001712 * @param operations the operations to apply
1713 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001714 * @throws OperationApplicationException thrown if any operation fails.
1715 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001716 */
Fred Quintana03d94902009-05-22 14:23:31 -07001717 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001718 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001719 final int numOperations = operations.size();
1720 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1721 for (int i = 0; i < numOperations; i++) {
1722 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001723 }
1724 return results;
1725 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001726
1727 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001728 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001729 * interfaces that are cheaper and/or unnatural for a table-like
1730 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001731 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001732 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1733 * on this entry into the content provider besides the basic ability for the application
1734 * to get access to the provider at all. For example, it has no idea whether the call
1735 * being executed may read or write data in the provider, so can't enforce those
1736 * individual permissions. Any implementation of this method <strong>must</strong>
1737 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1738 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001739 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1740 * @param arg provider-defined String argument. May be {@code null}.
1741 * @param extras provider-defined Bundle argument. May be {@code null}.
1742 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001743 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001744 */
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001745 public Bundle call(String method, String arg, Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001746 return null;
1747 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001748
1749 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001750 * Implement this to shut down the ContentProvider instance. You can then
1751 * invoke this method in unit tests.
1752 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001753 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001754 * Android normally handles ContentProvider startup and shutdown
1755 * automatically. You do not need to start up or shut down a
1756 * ContentProvider. When you invoke a test method on a ContentProvider,
1757 * however, a ContentProvider instance is started and keeps running after
1758 * the test finishes, even if a succeeding test instantiates another
1759 * ContentProvider. A conflict develops because the two instances are
1760 * usually running against the same underlying data source (for example, an
1761 * sqlite database).
1762 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001763 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001764 * Implementing shutDown() avoids this conflict by providing a way to
1765 * terminate the ContentProvider. This method can also prevent memory leaks
1766 * from multiple instantiations of the ContentProvider, and it can ensure
1767 * unit test isolation by allowing you to completely clean up the test
1768 * fixture before moving on to the next test.
1769 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001770 */
1771 public void shutdown() {
1772 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1773 "connections are gracefully shutdown");
1774 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001775
1776 /**
1777 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001778 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001779 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001780 * @param fd The raw file descriptor that the dump is being sent to.
1781 * @param writer The PrintWriter to which you should dump your state. This will be
1782 * closed for you after you return.
1783 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001784 */
1785 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1786 writer.println("nothing to dump");
1787 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001788
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001789 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001790 private void validateIncomingUri(Uri uri) throws SecurityException {
1791 String auth = uri.getAuthority();
1792 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001793 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
1794 throw new SecurityException("trying to query a ContentProvider in user "
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001795 + mContext.getUserId() + " with a uri belonging to user " + userId);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001796 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001797 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
1798 String message = "The authority of the uri " + uri + " does not match the one of the "
1799 + "contentProvider: ";
1800 if (mAuthority != null) {
1801 message += mAuthority;
1802 } else {
1803 message += mAuthorities;
1804 }
1805 throw new SecurityException(message);
1806 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001807 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001808
1809 /** @hide */
1810 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1811 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001812 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001813 if (end == -1) return defaultUserId;
1814 String userIdString = auth.substring(0, end);
1815 try {
1816 return Integer.parseInt(userIdString);
1817 } catch (NumberFormatException e) {
1818 Log.w(TAG, "Error parsing userId.", e);
1819 return UserHandle.USER_NULL;
1820 }
1821 }
1822
1823 /** @hide */
1824 public static int getUserIdFromAuthority(String auth) {
1825 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1826 }
1827
1828 /** @hide */
1829 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1830 if (uri == null) return defaultUserId;
1831 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1832 }
1833
1834 /** @hide */
1835 public static int getUserIdFromUri(Uri uri) {
1836 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1837 }
1838
1839 /**
1840 * Removes userId part from authority string. Expects format:
1841 * userId@some.authority
1842 * If there is no userId in the authority, it symply returns the argument
1843 * @hide
1844 */
1845 public static String getAuthorityWithoutUserId(String auth) {
1846 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001847 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001848 return auth.substring(end+1);
1849 }
1850
1851 /** @hide */
1852 public static Uri getUriWithoutUserId(Uri uri) {
1853 if (uri == null) return null;
1854 Uri.Builder builder = uri.buildUpon();
1855 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1856 return builder.build();
1857 }
1858
1859 /** @hide */
1860 public static boolean uriHasUserId(Uri uri) {
1861 if (uri == null) return false;
1862 return !TextUtils.isEmpty(uri.getUserInfo());
1863 }
1864
1865 /** @hide */
1866 public static Uri maybeAddUserId(Uri uri, int userId) {
1867 if (uri == null) return null;
1868 if (userId != UserHandle.USER_CURRENT
1869 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1870 if (!uriHasUserId(uri)) {
1871 //We don't add the user Id if there's already one
1872 Uri.Builder builder = uri.buildUpon();
1873 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1874 return builder.build();
1875 }
1876 }
1877 return uri;
1878 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001879}