blob: fd65d56abb1a7344addf426a60381441e3f9bf97 [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
Scott Kennedy9f78f652015-03-01 15:29:25 -080022import android.annotation.Nullable;
Dianne Hackborn35654b62013-01-14 17:38:02 -080023import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070024import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import android.content.pm.ProviderInfo;
26import android.content.res.AssetFileDescriptor;
27import android.content.res.Configuration;
28import android.database.Cursor;
Svet Ganov7271f3e2015-04-23 10:16:53 -070029import android.database.MatrixCursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.database.SQLException;
31import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070032import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080034import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070035import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080036import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070037import android.os.ICancellationSignal;
38import android.os.OperationCanceledException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070040import android.os.Process;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070041import android.os.UserHandle;
Vasu Nori0c9e14a2010-08-04 13:31:48 -070042import android.util.Log;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010043import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044
45import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080046import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070048import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080049import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070050import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051
52/**
53 * Content providers are one of the primary building blocks of Android applications, providing
54 * content to applications. They encapsulate data and provide it to applications through the single
55 * {@link ContentResolver} interface. A content provider is only required if you need to share
56 * data between multiple applications. For example, the contacts data is used by multiple
57 * applications and must be stored in a content provider. If you don't need to share data amongst
58 * multiple applications you can use a database directly via
59 * {@link android.database.sqlite.SQLiteDatabase}.
60 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061 * <p>When a request is made via
62 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
63 * request to the content provider registered with the authority. The content provider can interpret
64 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
65 * URIs.</p>
66 *
67 * <p>The primary methods that need to be implemented are:
68 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070069 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 * <li>{@link #query} which returns data to the caller</li>
71 * <li>{@link #insert} which inserts new data into the content provider</li>
72 * <li>{@link #update} which updates existing data in the content provider</li>
73 * <li>{@link #delete} which deletes data from the content provider</li>
74 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
75 * </ul></p>
76 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070077 * <p class="caution">Data access methods (such as {@link #insert} and
78 * {@link #update}) may be called from many threads at once, and must be thread-safe.
79 * Other methods (such as {@link #onCreate}) are only called from the application
80 * main thread, and must avoid performing lengthy operations. See the method
81 * descriptions for their expected thread behavior.</p>
82 *
83 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
84 * ContentProvider instance, so subclasses don't have to worry about the details of
85 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070086 *
87 * <div class="special reference">
88 * <h3>Developer Guides</h3>
89 * <p>For more information about using content providers, read the
90 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
91 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -070093public abstract class ContentProvider implements ComponentCallbacks2 {
Vasu Nori0c9e14a2010-08-04 13:31:48 -070094 private static final String TAG = "ContentProvider";
95
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +090096 /*
97 * Note: if you add methods to ContentProvider, you must add similar methods to
98 * MockContentProvider.
99 */
100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700102 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100103
104 // Since most Providers have only one authority, we keep both a String and a String[] to improve
105 // performance.
106 private String mAuthority;
107 private String[] mAuthorities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 private String mReadPermission;
109 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700110 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700111 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800112 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700113 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700115 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<String>();
116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 private Transport mTransport = new Transport();
118
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700119 /**
120 * Construct a ContentProvider instance. Content providers must be
121 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
122 * in the manifest</a>, accessed with {@link ContentResolver}, and created
123 * automatically by the system, so applications usually do not create
124 * ContentProvider instances directly.
125 *
126 * <p>At construction time, the object is uninitialized, and most fields and
127 * methods are unavailable. Subclasses should initialize themselves in
128 * {@link #onCreate}, not the constructor.
129 *
130 * <p>Content providers are created on the application main thread at
131 * application launch time. The constructor must not perform lengthy
132 * operations, or application startup will be delayed.
133 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900134 public ContentProvider() {
135 }
136
137 /**
138 * Constructor just for mocking.
139 *
140 * @param context A Context object which should be some mock instance (like the
141 * instance of {@link android.test.mock.MockContext}).
142 * @param readPermission The read permision you want this instance should have in the
143 * test, which is available via {@link #getReadPermission()}.
144 * @param writePermission The write permission you want this instance should have
145 * in the test, which is available via {@link #getWritePermission()}.
146 * @param pathPermissions The PathPermissions you want this instance should have
147 * in the test, which is available via {@link #getPathPermissions()}.
148 * @hide
149 */
150 public ContentProvider(
151 Context context,
152 String readPermission,
153 String writePermission,
154 PathPermission[] pathPermissions) {
155 mContext = context;
156 mReadPermission = readPermission;
157 mWritePermission = writePermission;
158 mPathPermissions = pathPermissions;
159 }
160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 /**
162 * Given an IContentProvider, try to coerce it back to the real
163 * ContentProvider object if it is running in the local process. This can
164 * be used if you know you are running in the same process as a provider,
165 * and want to get direct access to its implementation details. Most
166 * clients should not nor have a reason to use it.
167 *
168 * @param abstractInterface The ContentProvider interface that is to be
169 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800170 * @return If the IContentProvider is non-{@code null} and local, returns its actual
171 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 * @hide
173 */
174 public static ContentProvider coerceToLocalContentProvider(
175 IContentProvider abstractInterface) {
176 if (abstractInterface instanceof Transport) {
177 return ((Transport)abstractInterface).getContentProvider();
178 }
179 return null;
180 }
181
182 /**
183 * Binder object that deals with remoting.
184 *
185 * @hide
186 */
187 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800188 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800189 int mReadOp = AppOpsManager.OP_NONE;
190 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 ContentProvider getContentProvider() {
193 return ContentProvider.this;
194 }
195
Jeff Brownd2183652011-10-09 12:39:53 -0700196 @Override
197 public String getProviderName() {
198 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 }
200
Jeff Brown75ea64f2012-01-25 19:37:13 -0800201 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800202 public Cursor query(String callingPkg, Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800203 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800204 ICancellationSignal cancellationSignal) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100205 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100206 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800207 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Svet Ganov7271f3e2015-04-23 10:16:53 -0700208 // The caller has no access to the data, so return an empty cursor with
209 // the columns in the requested order. The caller may ask for an invalid
210 // column and we would not catch that but this is not a problem in practice.
211 // We do not call ContentProvider#query with a modified where clause since
212 // the implementation is not guaranteed to be backed by a SQL database, hence
213 // it may not handle properly the tautology where clause we would have created.
214 return new MatrixCursor(projection, 0);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800215 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700216 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700217 try {
218 return ContentProvider.this.query(
219 uri, projection, selection, selectionArgs, sortOrder,
220 CancellationSignal.fromTransport(cancellationSignal));
221 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700222 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 }
225
Jeff Brown75ea64f2012-01-25 19:37:13 -0800226 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100228 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100229 uri = getUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 return ContentProvider.this.getType(uri);
231 }
232
Jeff Brown75ea64f2012-01-25 19:37:13 -0800233 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800234 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100235 validateIncomingUri(uri);
236 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100237 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800238 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800239 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800240 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700241 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700242 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100243 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700244 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700245 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 }
248
Jeff Brown75ea64f2012-01-25 19:37:13 -0800249 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800250 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100251 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100252 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800253 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800254 return 0;
255 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700256 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700257 try {
258 return ContentProvider.this.bulkInsert(uri, initialValues);
259 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700260 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 }
263
Jeff Brown75ea64f2012-01-25 19:37:13 -0800264 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800265 public ContentProviderResult[] applyBatch(String callingPkg,
266 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700267 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100268 int numOperations = operations.size();
269 final int[] userIds = new int[numOperations];
270 for (int i = 0; i < numOperations; i++) {
271 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100272 Uri uri = operation.getUri();
273 validateIncomingUri(uri);
274 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100275 if (userIds[i] != UserHandle.USER_CURRENT) {
276 // Removing the user id from the uri.
277 operation = new ContentProviderOperation(operation, true);
278 operations.set(i, operation);
279 }
Fred Quintana89437372009-05-15 15:10:40 -0700280 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800281 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800282 != AppOpsManager.MODE_ALLOWED) {
283 throw new OperationApplicationException("App op not allowed", 0);
284 }
Fred Quintana89437372009-05-15 15:10:40 -0700285 }
Fred Quintana89437372009-05-15 15:10:40 -0700286 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800287 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800288 != AppOpsManager.MODE_ALLOWED) {
289 throw new OperationApplicationException("App op not allowed", 0);
290 }
Fred Quintana89437372009-05-15 15:10:40 -0700291 }
292 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700293 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700294 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100295 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
Jay Shraunerac2506c2014-12-15 12:28:25 -0800296 if (results != null) {
297 for (int i = 0; i < results.length ; i++) {
298 if (userIds[i] != UserHandle.USER_CURRENT) {
299 // Adding the userId to the uri.
300 results[i] = new ContentProviderResult(results[i], userIds[i]);
301 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100302 }
303 }
304 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700305 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700306 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700307 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700308 }
309
Jeff Brown75ea64f2012-01-25 19:37:13 -0800310 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800311 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100312 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100313 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800314 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800315 return 0;
316 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700317 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700318 try {
319 return ContentProvider.this.delete(uri, selection, selectionArgs);
320 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700321 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 }
324
Jeff Brown75ea64f2012-01-25 19:37:13 -0800325 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800326 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100328 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100329 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800330 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800331 return 0;
332 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700333 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700334 try {
335 return ContentProvider.this.update(uri, values, selection, selectionArgs);
336 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700337 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 }
340
Jeff Brown75ea64f2012-01-25 19:37:13 -0800341 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700342 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800343 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
344 IBinder callerToken) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100345 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100346 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800347 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700348 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700349 try {
350 return ContentProvider.this.openFile(
351 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
352 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700353 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 }
356
Jeff Brown75ea64f2012-01-25 19:37:13 -0800357 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700358 public AssetFileDescriptor openAssetFile(
359 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100361 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100362 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800363 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700364 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700365 try {
366 return ContentProvider.this.openAssetFile(
367 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
368 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700369 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800371 }
372
Jeff Brown75ea64f2012-01-25 19:37:13 -0800373 @Override
Scott Kennedy9f78f652015-03-01 15:29:25 -0800374 public Bundle call(
375 String callingPkg, String method, @Nullable String arg, @Nullable Bundle extras) {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700376 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700377 try {
378 return ContentProvider.this.call(method, arg, extras);
379 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700380 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700381 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800382 }
383
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700384 @Override
385 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100386 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100387 uri = getUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700388 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
389 }
390
391 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800392 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700393 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100394 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100395 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800396 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700397 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700398 try {
399 return ContentProvider.this.openTypedAssetFile(
400 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
401 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700402 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700403 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700404 }
405
Jeff Brown75ea64f2012-01-25 19:37:13 -0800406 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700407 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800408 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800409 }
410
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700411 @Override
412 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100413 validateIncomingUri(uri);
414 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100415 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800416 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700417 return null;
418 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700419 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700420 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100421 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700422 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700423 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700424 }
425 }
426
427 @Override
428 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100429 validateIncomingUri(uri);
430 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100431 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800432 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700433 return null;
434 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700435 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700436 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100437 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700438 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700439 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700440 }
441 }
442
Dianne Hackbornff170242014-11-19 10:59:01 -0800443 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
444 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800445 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800446 if (enforceWritePermission(callingPkg, uri, callerToken)
447 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800448 throw new FileNotFoundException("App op not allowed");
449 }
450 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800451 if (enforceReadPermission(callingPkg, uri, callerToken)
452 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800453 throw new FileNotFoundException("App op not allowed");
454 }
455 }
456 }
457
Dianne Hackbornff170242014-11-19 10:59:01 -0800458 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
459 throws SecurityException {
460 enforceReadPermissionInner(uri, callerToken);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800461 if (mReadOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800462 return mAppOpsManager.noteOp(mReadOp, Binder.getCallingUid(), callingPkg);
463 }
464 return AppOpsManager.MODE_ALLOWED;
465 }
466
Dianne Hackbornff170242014-11-19 10:59:01 -0800467 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
468 throws SecurityException {
469 enforceWritePermissionInner(uri, callerToken);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800470 if (mWriteOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800471 return mAppOpsManager.noteOp(mWriteOp, Binder.getCallingUid(), callingPkg);
472 }
473 return AppOpsManager.MODE_ALLOWED;
474 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700475 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800476
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100477 boolean checkUser(int pid, int uid, Context context) {
478 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700479 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100480 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
481 == PERMISSION_GRANTED;
482 }
483
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700484 /** {@hide} */
Dianne Hackbornff170242014-11-19 10:59:01 -0800485 protected void enforceReadPermissionInner(Uri uri, IBinder callerToken)
486 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700487 final Context context = getContext();
488 final int pid = Binder.getCallingPid();
489 final int uid = Binder.getCallingUid();
490 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700491
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700492 if (UserHandle.isSameApp(uid, mMyUid)) {
493 return;
494 }
495
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100496 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700497 final String componentPerm = getReadPermission();
498 if (componentPerm != null) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800499 if (context.checkPermission(componentPerm, pid, uid, callerToken)
500 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700501 return;
502 } else {
503 missingPerm = componentPerm;
504 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700505 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700506
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700507 // track if unprotected read is allowed; any denied
508 // <path-permission> below removes this ability
509 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700510
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700511 final PathPermission[] pps = getPathPermissions();
512 if (pps != null) {
513 final String path = uri.getPath();
514 for (PathPermission pp : pps) {
515 final String pathPerm = pp.getReadPermission();
516 if (pathPerm != null && pp.match(path)) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800517 if (context.checkPermission(pathPerm, pid, uid, callerToken)
518 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700519 return;
520 } else {
521 // any denied <path-permission> means we lose
522 // default <provider> access.
523 allowDefaultRead = false;
524 missingPerm = pathPerm;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700525 }
526 }
527 }
528 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700529
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700530 // if we passed <path-permission> checks above, and no default
531 // <provider> permission, then allow access.
532 if (allowDefaultRead) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700534
535 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800536 final int callingUserId = UserHandle.getUserId(uid);
537 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
538 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800539 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
540 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700541 return;
542 }
543
544 final String failReason = mExported
545 ? " requires " + missingPerm + ", or grantUriPermission()"
546 : " requires the provider be exported, or grantUriPermission()";
547 throw new SecurityException("Permission Denial: reading "
548 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
549 + ", uid=" + uid + failReason);
550 }
551
552 /** {@hide} */
Dianne Hackbornff170242014-11-19 10:59:01 -0800553 protected void enforceWritePermissionInner(Uri uri, IBinder callerToken)
554 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700555 final Context context = getContext();
556 final int pid = Binder.getCallingPid();
557 final int uid = Binder.getCallingUid();
558 String missingPerm = null;
559
560 if (UserHandle.isSameApp(uid, mMyUid)) {
561 return;
562 }
563
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100564 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700565 final String componentPerm = getWritePermission();
566 if (componentPerm != null) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800567 if (context.checkPermission(componentPerm, pid, uid, callerToken)
568 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700569 return;
570 } else {
571 missingPerm = componentPerm;
572 }
573 }
574
575 // track if unprotected write is allowed; any denied
576 // <path-permission> below removes this ability
577 boolean allowDefaultWrite = (componentPerm == null);
578
579 final PathPermission[] pps = getPathPermissions();
580 if (pps != null) {
581 final String path = uri.getPath();
582 for (PathPermission pp : pps) {
583 final String pathPerm = pp.getWritePermission();
584 if (pathPerm != null && pp.match(path)) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800585 if (context.checkPermission(pathPerm, pid, uid, callerToken)
586 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700587 return;
588 } else {
589 // any denied <path-permission> means we lose
590 // default <provider> access.
591 allowDefaultWrite = false;
592 missingPerm = pathPerm;
593 }
594 }
595 }
596 }
597
598 // if we passed <path-permission> checks above, and no default
599 // <provider> permission, then allow access.
600 if (allowDefaultWrite) return;
601 }
602
603 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800604 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
605 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700606 return;
607 }
608
609 final String failReason = mExported
610 ? " requires " + missingPerm + ", or grantUriPermission()"
611 : " requires the provider be exported, or grantUriPermission()";
612 throw new SecurityException("Permission Denial: writing "
613 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
614 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 }
616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700618 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800619 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 * constructor.
621 */
622 public final Context getContext() {
623 return mContext;
624 }
625
626 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700627 * Set the calling package, returning the current value (or {@code null})
628 * which can be used later to restore the previous state.
629 */
630 private String setCallingPackage(String callingPackage) {
631 final String original = mCallingPackage.get();
632 mCallingPackage.set(callingPackage);
633 return original;
634 }
635
636 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700637 * Return the package name of the caller that initiated the request being
638 * processed on the current thread. The returned package will have been
639 * verified to belong to the calling UID. Returns {@code null} if not
640 * currently processing a request.
641 * <p>
642 * This will always return {@code null} when processing
643 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
644 *
645 * @see Binder#getCallingUid()
646 * @see Context#grantUriPermission(String, Uri, int)
647 * @throws SecurityException if the calling package doesn't belong to the
648 * calling UID.
649 */
650 public final String getCallingPackage() {
651 final String pkg = mCallingPackage.get();
652 if (pkg != null) {
653 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
654 }
655 return pkg;
656 }
657
658 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100659 * Change the authorities of the ContentProvider.
660 * This is normally set for you from its manifest information when the provider is first
661 * created.
662 * @hide
663 * @param authorities the semi-colon separated authorities of the ContentProvider.
664 */
665 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100666 if (authorities != null) {
667 if (authorities.indexOf(';') == -1) {
668 mAuthority = authorities;
669 mAuthorities = null;
670 } else {
671 mAuthority = null;
672 mAuthorities = authorities.split(";");
673 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100674 }
675 }
676
677 /** @hide */
678 protected final boolean matchesOurAuthorities(String authority) {
679 if (mAuthority != null) {
680 return mAuthority.equals(authority);
681 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100682 if (mAuthorities != null) {
683 int length = mAuthorities.length;
684 for (int i = 0; i < length; i++) {
685 if (mAuthorities[i].equals(authority)) return true;
686 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100687 }
688 return false;
689 }
690
691
692 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 * Change the permission required to read data from the content
694 * provider. This is normally set for you from its manifest information
695 * when the provider is first created.
696 *
697 * @param permission Name of the permission required for read-only access.
698 */
699 protected final void setReadPermission(String permission) {
700 mReadPermission = permission;
701 }
702
703 /**
704 * Return the name of the permission required for read-only access to
705 * this content provider. This method can be called from multiple
706 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800707 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
708 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 */
710 public final String getReadPermission() {
711 return mReadPermission;
712 }
713
714 /**
715 * Change the permission required to read and write data in the content
716 * provider. This is normally set for you from its manifest information
717 * when the provider is first created.
718 *
719 * @param permission Name of the permission required for read/write access.
720 */
721 protected final void setWritePermission(String permission) {
722 mWritePermission = permission;
723 }
724
725 /**
726 * Return the name of the permission required for read/write access to
727 * this content provider. This method can be called from multiple
728 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800729 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
730 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 */
732 public final String getWritePermission() {
733 return mWritePermission;
734 }
735
736 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700737 * Change the path-based permission required to read and/or write data in
738 * the content provider. This is normally set for you from its manifest
739 * information when the provider is first created.
740 *
741 * @param permissions Array of path permission descriptions.
742 */
743 protected final void setPathPermissions(PathPermission[] permissions) {
744 mPathPermissions = permissions;
745 }
746
747 /**
748 * Return the path-based permissions required for read and/or write access to
749 * this content provider. This method can be called from multiple
750 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800751 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
752 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700753 */
754 public final PathPermission[] getPathPermissions() {
755 return mPathPermissions;
756 }
757
Dianne Hackborn35654b62013-01-14 17:38:02 -0800758 /** @hide */
759 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800760 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800761 mTransport.mReadOp = readOp;
762 mTransport.mWriteOp = writeOp;
763 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800764 }
765
Dianne Hackborn961321f2013-02-05 17:22:41 -0800766 /** @hide */
767 public AppOpsManager getAppOpsManager() {
768 return mTransport.mAppOpsManager;
769 }
770
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700771 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700772 * Implement this to initialize your content provider on startup.
773 * This method is called for all registered content providers on the
774 * application main thread at application launch time. It must not perform
775 * lengthy operations, or application startup will be delayed.
776 *
777 * <p>You should defer nontrivial initialization (such as opening,
778 * upgrading, and scanning databases) until the content provider is used
779 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
780 * keeps application startup fast, avoids unnecessary work if the provider
781 * turns out not to be needed, and stops database errors (such as a full
782 * disk) from halting application launch.
783 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700784 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700785 * is a helpful utility class that makes it easy to manage databases,
786 * and will automatically defer opening until first use. If you do use
787 * SQLiteOpenHelper, make sure to avoid calling
788 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
789 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
790 * from this method. (Instead, override
791 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
792 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 *
794 * @return true if the provider was successfully loaded, false otherwise
795 */
796 public abstract boolean onCreate();
797
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700798 /**
799 * {@inheritDoc}
800 * This method is always called on the application main thread, and must
801 * not perform lengthy operations.
802 *
803 * <p>The default content provider implementation does nothing.
804 * Override this method to take appropriate action.
805 * (Content providers do not usually care about things like screen
806 * orientation, but may want to know about locale changes.)
807 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 public void onConfigurationChanged(Configuration newConfig) {
809 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700810
811 /**
812 * {@inheritDoc}
813 * This method is always called on the application main thread, and must
814 * not perform lengthy operations.
815 *
816 * <p>The default content provider implementation does nothing.
817 * Subclasses may override this method to take appropriate action.
818 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 public void onLowMemory() {
820 }
821
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700822 public void onTrimMemory(int level) {
823 }
824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700826 * Implement this to handle query requests from clients.
827 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800828 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
829 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 * <p>
831 * Example client call:<p>
832 * <pre>// Request a specific record.
833 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000834 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 projection, // Which columns to return.
836 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000837 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 People.NAME + " ASC"); // Sort order.</pre>
839 * Example implementation:<p>
840 * <pre>// SQLiteQueryBuilder is a helper class that creates the
841 // proper SQL syntax for us.
842 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
843
844 // Set the table we're querying.
845 qBuilder.setTables(DATABASE_TABLE_NAME);
846
847 // If the query ends in a specific record number, we're
848 // being asked for a specific record, so set the
849 // WHERE clause in our query.
850 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
851 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
852 }
853
854 // Make the query.
855 Cursor c = qBuilder.query(mDb,
856 projection,
857 selection,
858 selectionArgs,
859 groupBy,
860 having,
861 sortOrder);
862 c.setNotificationUri(getContext().getContentResolver(), uri);
863 return c;</pre>
864 *
865 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000866 * if the client is requesting a specific record, the URI will end in a record number
867 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
868 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800870 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800872 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000873 * @param selectionArgs You may include ?s in selection, which will be replaced by
874 * the values from selectionArgs, in order that they appear in the selection.
875 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800877 * If {@code null} then the provider is free to define the sort order.
878 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 */
880 public abstract Cursor query(Uri uri, String[] projection,
881 String selection, String[] selectionArgs, String sortOrder);
882
Fred Quintana5bba6322009-10-05 14:21:12 -0700883 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800884 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800885 * This method can be called from multiple threads, as described in
886 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
887 * and Threads</a>.
888 * <p>
889 * Example client call:<p>
890 * <pre>// Request a specific record.
891 * Cursor managedCursor = managedQuery(
892 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
893 projection, // Which columns to return.
894 null, // WHERE clause.
895 null, // WHERE clause value substitution
896 People.NAME + " ASC"); // Sort order.</pre>
897 * Example implementation:<p>
898 * <pre>// SQLiteQueryBuilder is a helper class that creates the
899 // proper SQL syntax for us.
900 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
901
902 // Set the table we're querying.
903 qBuilder.setTables(DATABASE_TABLE_NAME);
904
905 // If the query ends in a specific record number, we're
906 // being asked for a specific record, so set the
907 // WHERE clause in our query.
908 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
909 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
910 }
911
912 // Make the query.
913 Cursor c = qBuilder.query(mDb,
914 projection,
915 selection,
916 selectionArgs,
917 groupBy,
918 having,
919 sortOrder);
920 c.setNotificationUri(getContext().getContentResolver(), uri);
921 return c;</pre>
922 * <p>
923 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800924 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
925 * signal to ensure correct operation on older versions of the Android Framework in
926 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800927 *
928 * @param uri The URI to query. This will be the full URI sent by the client;
929 * if the client is requesting a specific record, the URI will end in a record number
930 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
931 * that _id value.
932 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800933 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800934 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800935 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800936 * @param selectionArgs You may include ?s in selection, which will be replaced by
937 * the values from selectionArgs, in order that they appear in the selection.
938 * The values will be bound as Strings.
939 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800940 * If {@code null} then the provider is free to define the sort order.
941 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800942 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
943 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800944 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800945 */
946 public Cursor query(Uri uri, String[] projection,
947 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800948 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800949 return query(uri, projection, selection, selectionArgs, sortOrder);
950 }
951
952 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700953 * Implement this to handle requests for the MIME type of the data at the
954 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 * <code>vnd.android.cursor.item</code> for a single record,
956 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700957 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800958 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
959 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700961 * <p>Note that there are no permissions needed for an application to
962 * access this information; if your content provider requires read and/or
963 * write permissions, or is not exported, all applications can still call
964 * this method regardless of their access permissions. This allows them
965 * to retrieve the MIME type for a URI when dispatching intents.
966 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800968 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 */
970 public abstract String getType(Uri uri);
971
972 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700973 * Implement this to support canonicalization of URIs that refer to your
974 * content provider. A canonical URI is one that can be transported across
975 * devices, backup/restore, and other contexts, and still be able to refer
976 * to the same data item. Typically this is implemented by adding query
977 * params to the URI allowing the content provider to verify that an incoming
978 * canonical URI references the same data as it was originally intended for and,
979 * if it doesn't, to find that data (if it exists) in the current environment.
980 *
981 * <p>For example, if the content provider holds people and a normal URI in it
982 * is created with a row index into that people database, the cananical representation
983 * may have an additional query param at the end which specifies the name of the
984 * person it is intended for. Later calls into the provider with that URI will look
985 * up the row of that URI's base index and, if it doesn't match or its entry's
986 * name doesn't match the name in the query param, perform a query on its database
987 * to find the correct row to operate on.</p>
988 *
989 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
990 * URIs (including this one) must perform this verification and recovery of any
991 * canonical URIs they receive. In addition, you must also implement
992 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
993 *
994 * <p>The default implementation of this method returns null, indicating that
995 * canonical URIs are not supported.</p>
996 *
997 * @param url The Uri to canonicalize.
998 *
999 * @return Return the canonical representation of <var>url</var>, or null if
1000 * canonicalization of that Uri is not supported.
1001 */
1002 public Uri canonicalize(Uri url) {
1003 return null;
1004 }
1005
1006 /**
1007 * Remove canonicalization from canonical URIs previously returned by
1008 * {@link #canonicalize}. For example, if your implementation is to add
1009 * a query param to canonicalize a URI, this method can simply trip any
1010 * query params on the URI. The default implementation always returns the
1011 * same <var>url</var> that was passed in.
1012 *
1013 * @param url The Uri to remove any canonicalization from.
1014 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001015 * @return Return the non-canonical representation of <var>url</var>, return
1016 * the <var>url</var> as-is if there is nothing to do, or return null if
1017 * the data identified by the canonical representation can not be found in
1018 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001019 */
1020 public Uri uncanonicalize(Uri url) {
1021 return url;
1022 }
1023
1024 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001025 * @hide
1026 * Implementation when a caller has performed an insert on the content
1027 * provider, but that call has been rejected for the operation given
1028 * to {@link #setAppOps(int, int)}. The default implementation simply
1029 * returns a dummy URI that is the base URI with a 0 path element
1030 * appended.
1031 */
1032 public Uri rejectInsert(Uri uri, ContentValues values) {
1033 // If not allowed, we need to return some reasonable URI. Maybe the
1034 // content provider should be responsible for this, but for now we
1035 // will just return the base URI with a dummy '0' tagged on to it.
1036 // You shouldn't be able to read if you can't write, anyway, so it
1037 // shouldn't matter much what is returned.
1038 return uri.buildUpon().appendPath("0").build();
1039 }
1040
1041 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001042 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1044 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001045 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001046 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1047 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001048 * @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 -08001049 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001050 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 * @return The URI for the newly inserted item.
1052 */
1053 public abstract Uri insert(Uri uri, ContentValues values);
1054
1055 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001056 * Override this to handle requests to insert a set of new rows, or the
1057 * default implementation will iterate over the values and call
1058 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1060 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001061 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001062 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1063 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 *
1065 * @param uri The content:// URI of the insertion request.
1066 * @param values An array of sets 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 number of values that were inserted.
1069 */
1070 public int bulkInsert(Uri uri, ContentValues[] values) {
1071 int numValues = values.length;
1072 for (int i = 0; i < numValues; i++) {
1073 insert(uri, values[i]);
1074 }
1075 return numValues;
1076 }
1077
1078 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001079 * Implement this to handle requests to delete one or more rows.
1080 * The implementation should apply the selection clause when performing
1081 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001082 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001084 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001085 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1086 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 *
1088 * <p>The implementation is responsible for parsing out a row ID at the end
1089 * of the URI, if a specific row is being deleted. That is, the client would
1090 * pass in <code>content://contacts/people/22</code> and the implementation is
1091 * responsible for parsing the record number (22) when creating a SQL statement.
1092 *
1093 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1094 * @param selection An optional restriction to apply to rows when deleting.
1095 * @return The number of rows affected.
1096 * @throws SQLException
1097 */
1098 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
1099
1100 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001101 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001102 * The implementation should update all rows matching the selection
1103 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1105 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001106 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001107 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1108 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 *
1110 * @param uri The URI to query. This can potentially have a record ID if this
1111 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001112 * @param values A set of column_name/value pairs to update in the database.
1113 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 * @param selection An optional filter to match rows to update.
1115 * @return the number of rows affected.
1116 */
1117 public abstract int update(Uri uri, ContentValues values, String selection,
1118 String[] selectionArgs);
1119
1120 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001121 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001122 * The default implementation always throws {@link FileNotFoundException}.
1123 * 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>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001126 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001127 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1128 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001129 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 *
1131 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1132 * their responsibility to close it when done. That is, the implementation
1133 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001134 * <p>
1135 * If opened with the exclusive "r" or "w" modes, the returned
1136 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1137 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1138 * supports seeking.
1139 * <p>
1140 * If you need to detect when the returned ParcelFileDescriptor has been
1141 * closed, or if the remote process has crashed or encountered some other
1142 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1143 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1144 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1145 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001147 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1148 * to return the appropriate MIME type for the data returned here with
1149 * the same URI. This will allow intent resolution to automatically determine the data MIME
1150 * type and select the appropriate matching targets as part of its operation.</p>
1151 *
1152 * <p class="note">For better interoperability with other applications, it is recommended
1153 * that for any URIs that can be opened, you also support queries on them
1154 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1155 * You may also want to support other common columns if you have additional meta-data
1156 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1157 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1158 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 * @param uri The URI whose file is to be opened.
1160 * @param mode Access mode for the file. May be "r" for read-only access,
1161 * "rw" for read and write access, or "rwt" for read and write access
1162 * that truncates any existing file.
1163 *
1164 * @return Returns a new ParcelFileDescriptor which you can use to access
1165 * the file.
1166 *
1167 * @throws FileNotFoundException Throws FileNotFoundException if there is
1168 * no file associated with the given URI or the mode is invalid.
1169 * @throws SecurityException Throws SecurityException if the caller does
1170 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001171 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 * @see #openAssetFile(Uri, String)
1173 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001174 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001175 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001176 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 public ParcelFileDescriptor openFile(Uri uri, String mode)
1178 throws FileNotFoundException {
1179 throw new FileNotFoundException("No files supported by provider at "
1180 + uri);
1181 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001184 * Override this to handle requests to open a file blob.
1185 * The default implementation always throws {@link FileNotFoundException}.
1186 * This method can be called from multiple threads, as described in
1187 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1188 * and Threads</a>.
1189 *
1190 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1191 * to the caller. This way large data (such as images and documents) can be
1192 * returned without copying the content.
1193 *
1194 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1195 * their responsibility to close it when done. That is, the implementation
1196 * of this method should create a new ParcelFileDescriptor for each call.
1197 * <p>
1198 * If opened with the exclusive "r" or "w" modes, the returned
1199 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1200 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1201 * supports seeking.
1202 * <p>
1203 * If you need to detect when the returned ParcelFileDescriptor has been
1204 * closed, or if the remote process has crashed or encountered some other
1205 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1206 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1207 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1208 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1209 *
1210 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1211 * to return the appropriate MIME type for the data returned here with
1212 * the same URI. This will allow intent resolution to automatically determine the data MIME
1213 * type and select the appropriate matching targets as part of its operation.</p>
1214 *
1215 * <p class="note">For better interoperability with other applications, it is recommended
1216 * that for any URIs that can be opened, you also support queries on them
1217 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1218 * You may also want to support other common columns if you have additional meta-data
1219 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1220 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1221 *
1222 * @param uri The URI whose file is to be opened.
1223 * @param mode Access mode for the file. May be "r" for read-only access,
1224 * "w" for write-only access, "rw" for read and write access, or
1225 * "rwt" for read and write access that truncates any existing
1226 * file.
1227 * @param signal A signal to cancel the operation in progress, or
1228 * {@code null} if none. For example, if you are downloading a
1229 * file from the network to service a "rw" mode request, you
1230 * should periodically call
1231 * {@link CancellationSignal#throwIfCanceled()} to check whether
1232 * the client has canceled the request and abort the download.
1233 *
1234 * @return Returns a new ParcelFileDescriptor which you can use to access
1235 * the file.
1236 *
1237 * @throws FileNotFoundException Throws FileNotFoundException if there is
1238 * no file associated with the given URI or the mode is invalid.
1239 * @throws SecurityException Throws SecurityException if the caller does
1240 * not have permission to access the file.
1241 *
1242 * @see #openAssetFile(Uri, String)
1243 * @see #openFileHelper(Uri, String)
1244 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001245 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001246 */
1247 public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
1248 throws FileNotFoundException {
1249 return openFile(uri, mode);
1250 }
1251
1252 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 * This is like {@link #openFile}, but can be implemented by providers
1254 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001255 * inside of their .apk.
1256 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001257 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1258 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001259 *
1260 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001261 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001262 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1264 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1265 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001266 * <p>
1267 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1268 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001269 *
1270 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 * should create the AssetFileDescriptor with
1272 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001273 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001275 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1276 * to return the appropriate MIME type for the data returned here with
1277 * the same URI. This will allow intent resolution to automatically determine the data MIME
1278 * type and select the appropriate matching targets as part of its operation.</p>
1279 *
1280 * <p class="note">For better interoperability with other applications, it is recommended
1281 * that for any URIs that can be opened, you also support queries on them
1282 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1283 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 * @param uri The URI whose file is to be opened.
1285 * @param mode Access mode for the file. May be "r" for read-only access,
1286 * "w" for write-only access (erasing whatever data is currently in
1287 * the file), "wa" for write-only access to append to any existing data,
1288 * "rw" for read and write access on any existing data, and "rwt" for read
1289 * and write access that truncates any existing file.
1290 *
1291 * @return Returns a new AssetFileDescriptor which you can use to access
1292 * the file.
1293 *
1294 * @throws FileNotFoundException Throws FileNotFoundException if there is
1295 * no file associated with the given URI or the mode is invalid.
1296 * @throws SecurityException Throws SecurityException if the caller does
1297 * not have permission to access the file.
1298 *
1299 * @see #openFile(Uri, String)
1300 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001301 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 */
1303 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
1304 throws FileNotFoundException {
1305 ParcelFileDescriptor fd = openFile(uri, mode);
1306 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1307 }
1308
1309 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001310 * This is like {@link #openFile}, but can be implemented by providers
1311 * that need to be able to return sub-sections of files, often assets
1312 * inside of their .apk.
1313 * This method can be called from multiple threads, as described in
1314 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1315 * and Threads</a>.
1316 *
1317 * <p>If you implement this, your clients must be able to deal with such
1318 * file slices, either directly with
1319 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1320 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1321 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1322 * methods.
1323 * <p>
1324 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1325 * streaming of data.
1326 *
1327 * <p class="note">If you are implementing this to return a full file, you
1328 * should create the AssetFileDescriptor with
1329 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1330 * applications that cannot handle sub-sections of files.</p>
1331 *
1332 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1333 * to return the appropriate MIME type for the data returned here with
1334 * the same URI. This will allow intent resolution to automatically determine the data MIME
1335 * type and select the appropriate matching targets as part of its operation.</p>
1336 *
1337 * <p class="note">For better interoperability with other applications, it is recommended
1338 * that for any URIs that can be opened, you also support queries on them
1339 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1340 *
1341 * @param uri The URI whose file is to be opened.
1342 * @param mode Access mode for the file. May be "r" for read-only access,
1343 * "w" for write-only access (erasing whatever data is currently in
1344 * the file), "wa" for write-only access to append to any existing data,
1345 * "rw" for read and write access on any existing data, and "rwt" for read
1346 * and write access that truncates any existing file.
1347 * @param signal A signal to cancel the operation in progress, or
1348 * {@code null} if none. For example, if you are downloading a
1349 * file from the network to service a "rw" mode request, you
1350 * should periodically call
1351 * {@link CancellationSignal#throwIfCanceled()} to check whether
1352 * the client has canceled the request and abort the download.
1353 *
1354 * @return Returns a new AssetFileDescriptor which you can use to access
1355 * the file.
1356 *
1357 * @throws FileNotFoundException Throws FileNotFoundException if there is
1358 * no file associated with the given URI or the mode is invalid.
1359 * @throws SecurityException Throws SecurityException if the caller does
1360 * not have permission to access the file.
1361 *
1362 * @see #openFile(Uri, String)
1363 * @see #openFileHelper(Uri, String)
1364 * @see #getType(android.net.Uri)
1365 */
1366 public AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)
1367 throws FileNotFoundException {
1368 return openAssetFile(uri, mode);
1369 }
1370
1371 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 * Convenience for subclasses that wish to implement {@link #openFile}
1373 * by looking up a column named "_data" at the given URI.
1374 *
1375 * @param uri The URI to be opened.
1376 * @param mode The file mode. May be "r" for read-only access,
1377 * "w" for write-only access (erasing whatever data is currently in
1378 * the file), "wa" for write-only access to append to any existing data,
1379 * "rw" for read and write access on any existing data, and "rwt" for read
1380 * and write access that truncates any existing file.
1381 *
1382 * @return Returns a new ParcelFileDescriptor that can be used by the
1383 * client to access the file.
1384 */
1385 protected final ParcelFileDescriptor openFileHelper(Uri uri,
1386 String mode) throws FileNotFoundException {
1387 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1388 int count = (c != null) ? c.getCount() : 0;
1389 if (count != 1) {
1390 // If there is not exactly one result, throw an appropriate
1391 // exception.
1392 if (c != null) {
1393 c.close();
1394 }
1395 if (count == 0) {
1396 throw new FileNotFoundException("No entry for " + uri);
1397 }
1398 throw new FileNotFoundException("Multiple items at " + uri);
1399 }
1400
1401 c.moveToFirst();
1402 int i = c.getColumnIndex("_data");
1403 String path = (i >= 0 ? c.getString(i) : null);
1404 c.close();
1405 if (path == null) {
1406 throw new FileNotFoundException("Column _data not found.");
1407 }
1408
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001409 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 return ParcelFileDescriptor.open(new File(path), modeBits);
1411 }
1412
1413 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001414 * Called by a client to determine the types of data streams that this
1415 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001416 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001417 * of a particular type, return that MIME type if it matches the given
1418 * mimeTypeFilter. If it can perform type conversions, return an array
1419 * of all supported MIME types that match mimeTypeFilter.
1420 *
1421 * @param uri The data in the content provider being queried.
1422 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001423 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001424 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001425 * given mimeTypeFilter. Otherwise returns an array of all available
1426 * concrete MIME types.
1427 *
1428 * @see #getType(Uri)
1429 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001430 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001431 */
1432 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
1433 return null;
1434 }
1435
1436 /**
1437 * Called by a client to open a read-only stream containing data of a
1438 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1439 * except the file can only be read-only and the content provider may
1440 * perform data conversions to generate data of the desired type.
1441 *
1442 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001443 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001444 * {@link #openAssetFile(Uri, String)}.
1445 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001446 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001447 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001448 * <p>
1449 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1450 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001451 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001452 * <p class="note">For better interoperability with other applications, it is recommended
1453 * that for any URIs that can be opened, you also support queries on them
1454 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1455 * You may also want to support other common columns if you have additional meta-data
1456 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1457 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1458 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001459 * @param uri The data in the content provider being queried.
1460 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001461 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001462 * requirements; in this case the content provider will pick its best
1463 * type matching the pattern.
1464 * @param opts Additional options from the client. The definitions of
1465 * these are specific to the content provider being called.
1466 *
1467 * @return Returns a new AssetFileDescriptor from which the client can
1468 * read data of the desired type.
1469 *
1470 * @throws FileNotFoundException Throws FileNotFoundException if there is
1471 * no file associated with the given URI or the mode is invalid.
1472 * @throws SecurityException Throws SecurityException if the caller does
1473 * not have permission to access the data.
1474 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1475 * content provider does not support the requested MIME type.
1476 *
1477 * @see #getStreamTypes(Uri, String)
1478 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001479 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001480 */
1481 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
1482 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001483 if ("*/*".equals(mimeTypeFilter)) {
1484 // If they can take anything, the untyped open call is good enough.
1485 return openAssetFile(uri, "r");
1486 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001487 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001488 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001489 // Use old untyped open call if this provider has a type for this
1490 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001491 return openAssetFile(uri, "r");
1492 }
1493 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1494 }
1495
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001496
1497 /**
1498 * Called by a client to open a read-only stream containing data of a
1499 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1500 * except the file can only be read-only and the content provider may
1501 * perform data conversions to generate data of the desired type.
1502 *
1503 * <p>The default implementation compares the given mimeType against the
1504 * result of {@link #getType(Uri)} and, if they match, simply calls
1505 * {@link #openAssetFile(Uri, String)}.
1506 *
1507 * <p>See {@link ClipData} for examples of the use and implementation
1508 * of this method.
1509 * <p>
1510 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1511 * streaming of data.
1512 *
1513 * <p class="note">For better interoperability with other applications, it is recommended
1514 * that for any URIs that can be opened, you also support queries on them
1515 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1516 * You may also want to support other common columns if you have additional meta-data
1517 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1518 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1519 *
1520 * @param uri The data in the content provider being queried.
1521 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001522 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001523 * requirements; in this case the content provider will pick its best
1524 * type matching the pattern.
1525 * @param opts Additional options from the client. The definitions of
1526 * these are specific to the content provider being called.
1527 * @param signal A signal to cancel the operation in progress, or
1528 * {@code null} if none. For example, if you are downloading a
1529 * file from the network to service a "rw" mode request, you
1530 * should periodically call
1531 * {@link CancellationSignal#throwIfCanceled()} to check whether
1532 * the client has canceled the request and abort the download.
1533 *
1534 * @return Returns a new AssetFileDescriptor from which the client can
1535 * read data of the desired type.
1536 *
1537 * @throws FileNotFoundException Throws FileNotFoundException if there is
1538 * no file associated with the given URI or the mode is invalid.
1539 * @throws SecurityException Throws SecurityException if the caller does
1540 * not have permission to access the data.
1541 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1542 * content provider does not support the requested MIME type.
1543 *
1544 * @see #getStreamTypes(Uri, String)
1545 * @see #openAssetFile(Uri, String)
1546 * @see ClipDescription#compareMimeTypes(String, String)
1547 */
1548 public AssetFileDescriptor openTypedAssetFile(
1549 Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)
1550 throws FileNotFoundException {
1551 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1552 }
1553
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001554 /**
1555 * Interface to write a stream of data to a pipe. Use with
1556 * {@link ContentProvider#openPipeHelper}.
1557 */
1558 public interface PipeDataWriter<T> {
1559 /**
1560 * Called from a background thread to stream data out to a pipe.
1561 * Note that the pipe is blocking, so this thread can block on
1562 * writes for an arbitrary amount of time if the client is slow
1563 * at reading.
1564 *
1565 * @param output The pipe where data should be written. This will be
1566 * closed for you upon returning from this function.
1567 * @param uri The URI whose data is to be written.
1568 * @param mimeType The desired type of data to be written.
1569 * @param opts Options supplied by caller.
1570 * @param args Your own custom arguments.
1571 */
1572 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
1573 Bundle opts, T args);
1574 }
1575
1576 /**
1577 * A helper function for implementing {@link #openTypedAssetFile}, for
1578 * creating a data pipe and background thread allowing you to stream
1579 * generated data back to the client. This function returns a new
1580 * ParcelFileDescriptor that should be returned to the caller (the caller
1581 * is responsible for closing it).
1582 *
1583 * @param uri The URI whose data is to be written.
1584 * @param mimeType The desired type of data to be written.
1585 * @param opts Options supplied by caller.
1586 * @param args Your own custom arguments.
1587 * @param func Interface implementing the function that will actually
1588 * stream the data.
1589 * @return Returns a new ParcelFileDescriptor holding the read side of
1590 * the pipe. This should be returned to the caller for reading; the caller
1591 * is responsible for closing it when done.
1592 */
1593 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
1594 final Bundle opts, final T args, final PipeDataWriter<T> func)
1595 throws FileNotFoundException {
1596 try {
1597 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1598
1599 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1600 @Override
1601 protected Object doInBackground(Object... params) {
1602 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1603 try {
1604 fds[1].close();
1605 } catch (IOException e) {
1606 Log.w(TAG, "Failure closing pipe", e);
1607 }
1608 return null;
1609 }
1610 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001611 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001612
1613 return fds[0];
1614 } catch (IOException e) {
1615 throw new FileNotFoundException("failure making pipe");
1616 }
1617 }
1618
1619 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 * Returns true if this instance is a temporary content provider.
1621 * @return true if this instance is a temporary content provider
1622 */
1623 protected boolean isTemporary() {
1624 return false;
1625 }
1626
1627 /**
1628 * Returns the Binder object for this provider.
1629 *
1630 * @return the Binder object for this provider
1631 * @hide
1632 */
1633 public IContentProvider getIContentProvider() {
1634 return mTransport;
1635 }
1636
1637 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001638 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1639 * when directly instantiating the provider for testing.
1640 * @hide
1641 */
1642 public void attachInfoForTesting(Context context, ProviderInfo info) {
1643 attachInfo(context, info, true);
1644 }
1645
1646 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 * After being instantiated, this is called to tell the content provider
1648 * about itself.
1649 *
1650 * @param context The context this provider is running in
1651 * @param info Registered information about this content provider
1652 */
1653 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001654 attachInfo(context, info, false);
1655 }
1656
1657 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001658 mNoPerms = testing;
1659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 /*
1661 * Only allow it to be set once, so after the content service gives
1662 * this to us clients can't change it.
1663 */
1664 if (mContext == null) {
1665 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001666 if (context != null) {
1667 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1668 Context.APP_OPS_SERVICE);
1669 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001670 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 if (info != null) {
1672 setReadPermission(info.readPermission);
1673 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001674 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001675 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001676 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001677 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 }
1679 ContentProvider.this.onCreate();
1680 }
1681 }
Fred Quintanace31b232009-05-04 16:01:15 -07001682
1683 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001684 * Override this to handle requests to perform a batch of operations, or the
1685 * default implementation will iterate over the operations and call
1686 * {@link ContentProviderOperation#apply} on each of them.
1687 * If all calls to {@link ContentProviderOperation#apply} succeed
1688 * then a {@link ContentProviderResult} array with as many
1689 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001690 * fail, it is up to the implementation how many of the others take effect.
1691 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001692 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1693 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001694 *
Fred Quintanace31b232009-05-04 16:01:15 -07001695 * @param operations the operations to apply
1696 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001697 * @throws OperationApplicationException thrown if any operation fails.
1698 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001699 */
Fred Quintana03d94902009-05-22 14:23:31 -07001700 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001701 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001702 final int numOperations = operations.size();
1703 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1704 for (int i = 0; i < numOperations; i++) {
1705 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001706 }
1707 return results;
1708 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001709
1710 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001711 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001712 * interfaces that are cheaper and/or unnatural for a table-like
1713 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001714 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001715 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1716 * on this entry into the content provider besides the basic ability for the application
1717 * to get access to the provider at all. For example, it has no idea whether the call
1718 * being executed may read or write data in the provider, so can't enforce those
1719 * individual permissions. Any implementation of this method <strong>must</strong>
1720 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1721 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001722 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1723 * @param arg provider-defined String argument. May be {@code null}.
1724 * @param extras provider-defined Bundle argument. May be {@code null}.
1725 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001726 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001727 */
Scott Kennedy9f78f652015-03-01 15:29:25 -08001728 public Bundle call(String method, @Nullable String arg, @Nullable Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001729 return null;
1730 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001731
1732 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001733 * Implement this to shut down the ContentProvider instance. You can then
1734 * invoke this method in unit tests.
1735 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001736 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001737 * Android normally handles ContentProvider startup and shutdown
1738 * automatically. You do not need to start up or shut down a
1739 * ContentProvider. When you invoke a test method on a ContentProvider,
1740 * however, a ContentProvider instance is started and keeps running after
1741 * the test finishes, even if a succeeding test instantiates another
1742 * ContentProvider. A conflict develops because the two instances are
1743 * usually running against the same underlying data source (for example, an
1744 * sqlite database).
1745 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001746 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001747 * Implementing shutDown() avoids this conflict by providing a way to
1748 * terminate the ContentProvider. This method can also prevent memory leaks
1749 * from multiple instantiations of the ContentProvider, and it can ensure
1750 * unit test isolation by allowing you to completely clean up the test
1751 * fixture before moving on to the next test.
1752 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001753 */
1754 public void shutdown() {
1755 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1756 "connections are gracefully shutdown");
1757 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001758
1759 /**
1760 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001761 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001762 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001763 * @param fd The raw file descriptor that the dump is being sent to.
1764 * @param writer The PrintWriter to which you should dump your state. This will be
1765 * closed for you after you return.
1766 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001767 */
1768 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1769 writer.println("nothing to dump");
1770 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001771
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001772 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001773 private void validateIncomingUri(Uri uri) throws SecurityException {
1774 String auth = uri.getAuthority();
1775 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001776 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
1777 throw new SecurityException("trying to query a ContentProvider in user "
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001778 + mContext.getUserId() + " with a uri belonging to user " + userId);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001779 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001780 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
1781 String message = "The authority of the uri " + uri + " does not match the one of the "
1782 + "contentProvider: ";
1783 if (mAuthority != null) {
1784 message += mAuthority;
1785 } else {
1786 message += mAuthorities;
1787 }
1788 throw new SecurityException(message);
1789 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001790 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001791
1792 /** @hide */
1793 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1794 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001795 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001796 if (end == -1) return defaultUserId;
1797 String userIdString = auth.substring(0, end);
1798 try {
1799 return Integer.parseInt(userIdString);
1800 } catch (NumberFormatException e) {
1801 Log.w(TAG, "Error parsing userId.", e);
1802 return UserHandle.USER_NULL;
1803 }
1804 }
1805
1806 /** @hide */
1807 public static int getUserIdFromAuthority(String auth) {
1808 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1809 }
1810
1811 /** @hide */
1812 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1813 if (uri == null) return defaultUserId;
1814 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1815 }
1816
1817 /** @hide */
1818 public static int getUserIdFromUri(Uri uri) {
1819 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1820 }
1821
1822 /**
1823 * Removes userId part from authority string. Expects format:
1824 * userId@some.authority
1825 * If there is no userId in the authority, it symply returns the argument
1826 * @hide
1827 */
1828 public static String getAuthorityWithoutUserId(String auth) {
1829 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001830 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001831 return auth.substring(end+1);
1832 }
1833
1834 /** @hide */
1835 public static Uri getUriWithoutUserId(Uri uri) {
1836 if (uri == null) return null;
1837 Uri.Builder builder = uri.buildUpon();
1838 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1839 return builder.build();
1840 }
1841
1842 /** @hide */
1843 public static boolean uriHasUserId(Uri uri) {
1844 if (uri == null) return false;
1845 return !TextUtils.isEmpty(uri.getUserInfo());
1846 }
1847
1848 /** @hide */
1849 public static Uri maybeAddUserId(Uri uri, int userId) {
1850 if (uri == null) return null;
1851 if (userId != UserHandle.USER_CURRENT
1852 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1853 if (!uriHasUserId(uri)) {
1854 //We don't add the user Id if there's already one
1855 Uri.Builder builder = uri.buildUpon();
1856 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1857 return builder.build();
1858 }
1859 }
1860 return uri;
1861 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001862}