blob: 360f30889afd9cf91a3a661d2eb5b132d1ffc81f [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.content;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Nicolas Prevot504d78e2014-06-26 10:07:33 +010020import static android.Manifest.permission.INTERACT_ACROSS_USERS;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070021
Dianne Hackborn35654b62013-01-14 17:38:02 -080022import android.app.AppOpsManager;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070023import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.pm.ProviderInfo;
25import android.content.res.AssetFileDescriptor;
26import android.content.res.Configuration;
27import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.database.SQLException;
29import android.net.Uri;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070030import android.os.AsyncTask;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.os.Binder;
Brad Fitzpatrick1877d012010-03-04 17:48:13 -080032import android.os.Bundle;
Jeff Browna7771df2012-05-07 20:06:46 -070033import android.os.CancellationSignal;
Dianne Hackbornff170242014-11-19 10:59:01 -080034import android.os.IBinder;
Jeff Browna7771df2012-05-07 20:06:46 -070035import android.os.ICancellationSignal;
36import android.os.OperationCanceledException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.os.ParcelFileDescriptor;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070038import android.os.Process;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070039import android.os.UserHandle;
Vasu Nori0c9e14a2010-08-04 13:31:48 -070040import android.util.Log;
Nicolas Prevotd85fc722014-04-16 19:52:08 +010041import android.text.TextUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042
43import java.io.File;
Marco Nelissen18cb2872011-11-15 11:19:53 -080044import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import java.io.FileNotFoundException;
Dianne Hackborn23fdaf62010-08-06 12:16:55 -070046import java.io.IOException;
Marco Nelissen18cb2872011-11-15 11:19:53 -080047import java.io.PrintWriter;
Fred Quintana03d94902009-05-22 14:23:31 -070048import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049
50/**
51 * Content providers are one of the primary building blocks of Android applications, providing
52 * content to applications. They encapsulate data and provide it to applications through the single
53 * {@link ContentResolver} interface. A content provider is only required if you need to share
54 * data between multiple applications. For example, the contacts data is used by multiple
55 * applications and must be stored in a content provider. If you don't need to share data amongst
56 * multiple applications you can use a database directly via
57 * {@link android.database.sqlite.SQLiteDatabase}.
58 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059 * <p>When a request is made via
60 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the
61 * request to the content provider registered with the authority. The content provider can interpret
62 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing
63 * URIs.</p>
64 *
65 * <p>The primary methods that need to be implemented are:
66 * <ul>
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070067 * <li>{@link #onCreate} which is called to initialize the provider</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 * <li>{@link #query} which returns data to the caller</li>
69 * <li>{@link #insert} which inserts new data into the content provider</li>
70 * <li>{@link #update} which updates existing data in the content provider</li>
71 * <li>{@link #delete} which deletes data from the content provider</li>
72 * <li>{@link #getType} which returns the MIME type of data in the content provider</li>
73 * </ul></p>
74 *
Dan Egnor6fcc0f0732010-07-27 16:32:17 -070075 * <p class="caution">Data access methods (such as {@link #insert} and
76 * {@link #update}) may be called from many threads at once, and must be thread-safe.
77 * Other methods (such as {@link #onCreate}) are only called from the application
78 * main thread, and must avoid performing lengthy operations. See the method
79 * descriptions for their expected thread behavior.</p>
80 *
81 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
82 * ContentProvider instance, so subclasses don't have to worry about the details of
83 * cross-process calls.</p>
Joe Fernandez558459f2011-10-13 16:47:36 -070084 *
85 * <div class="special reference">
86 * <h3>Developer Guides</h3>
87 * <p>For more information about using content providers, read the
88 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
89 * developer guide.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090 */
Dianne Hackbornc68c9132011-07-29 01:25:18 -070091public abstract class ContentProvider implements ComponentCallbacks2 {
Vasu Nori0c9e14a2010-08-04 13:31:48 -070092 private static final String TAG = "ContentProvider";
93
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +090094 /*
95 * Note: if you add methods to ContentProvider, you must add similar methods to
96 * MockContentProvider.
97 */
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 private Context mContext = null;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700100 private int mMyUid;
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100101
102 // Since most Providers have only one authority, we keep both a String and a String[] to improve
103 // performance.
104 private String mAuthority;
105 private String[] mAuthorities;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 private String mReadPermission;
107 private String mWritePermission;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700108 private PathPermission[] mPathPermissions;
Dianne Hackbornb424b632010-08-18 15:59:05 -0700109 private boolean mExported;
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800110 private boolean mNoPerms;
Amith Yamasania6f4d582014-08-07 17:58:39 -0700111 private boolean mSingleUser;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700113 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<String>();
114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 private Transport mTransport = new Transport();
116
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700117 /**
118 * Construct a ContentProvider instance. Content providers must be
119 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
120 * in the manifest</a>, accessed with {@link ContentResolver}, and created
121 * automatically by the system, so applications usually do not create
122 * ContentProvider instances directly.
123 *
124 * <p>At construction time, the object is uninitialized, and most fields and
125 * methods are unavailable. Subclasses should initialize themselves in
126 * {@link #onCreate}, not the constructor.
127 *
128 * <p>Content providers are created on the application main thread at
129 * application launch time. The constructor must not perform lengthy
130 * operations, or application startup will be delayed.
131 */
Daisuke Miyakawa8280c2b2009-10-22 08:36:42 +0900132 public ContentProvider() {
133 }
134
135 /**
136 * Constructor just for mocking.
137 *
138 * @param context A Context object which should be some mock instance (like the
139 * instance of {@link android.test.mock.MockContext}).
140 * @param readPermission The read permision you want this instance should have in the
141 * test, which is available via {@link #getReadPermission()}.
142 * @param writePermission The write permission you want this instance should have
143 * in the test, which is available via {@link #getWritePermission()}.
144 * @param pathPermissions The PathPermissions you want this instance should have
145 * in the test, which is available via {@link #getPathPermissions()}.
146 * @hide
147 */
148 public ContentProvider(
149 Context context,
150 String readPermission,
151 String writePermission,
152 PathPermission[] pathPermissions) {
153 mContext = context;
154 mReadPermission = readPermission;
155 mWritePermission = writePermission;
156 mPathPermissions = pathPermissions;
157 }
158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 /**
160 * Given an IContentProvider, try to coerce it back to the real
161 * ContentProvider object if it is running in the local process. This can
162 * be used if you know you are running in the same process as a provider,
163 * and want to get direct access to its implementation details. Most
164 * clients should not nor have a reason to use it.
165 *
166 * @param abstractInterface The ContentProvider interface that is to be
167 * coerced.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800168 * @return If the IContentProvider is non-{@code null} and local, returns its actual
169 * ContentProvider instance. Otherwise returns {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 * @hide
171 */
172 public static ContentProvider coerceToLocalContentProvider(
173 IContentProvider abstractInterface) {
174 if (abstractInterface instanceof Transport) {
175 return ((Transport)abstractInterface).getContentProvider();
176 }
177 return null;
178 }
179
180 /**
181 * Binder object that deals with remoting.
182 *
183 * @hide
184 */
185 class Transport extends ContentProviderNative {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800186 AppOpsManager mAppOpsManager = null;
Dianne Hackborn961321f2013-02-05 17:22:41 -0800187 int mReadOp = AppOpsManager.OP_NONE;
188 int mWriteOp = AppOpsManager.OP_NONE;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 ContentProvider getContentProvider() {
191 return ContentProvider.this;
192 }
193
Jeff Brownd2183652011-10-09 12:39:53 -0700194 @Override
195 public String getProviderName() {
196 return getContentProvider().getClass().getName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 }
198
Jeff Brown75ea64f2012-01-25 19:37:13 -0800199 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800200 public Cursor query(String callingPkg, Uri uri, String[] projection,
Jeff Brown75ea64f2012-01-25 19:37:13 -0800201 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800202 ICancellationSignal cancellationSignal) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100203 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100204 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800205 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800206 return rejectQuery(uri, projection, selection, selectionArgs, sortOrder,
207 CancellationSignal.fromTransport(cancellationSignal));
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800208 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700209 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700210 try {
211 return ContentProvider.this.query(
212 uri, projection, selection, selectionArgs, sortOrder,
213 CancellationSignal.fromTransport(cancellationSignal));
214 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700215 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 }
218
Jeff Brown75ea64f2012-01-25 19:37:13 -0800219 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 public String getType(Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100221 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100222 uri = getUriWithoutUserId(uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 return ContentProvider.this.getType(uri);
224 }
225
Jeff Brown75ea64f2012-01-25 19:37:13 -0800226 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800227 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100228 validateIncomingUri(uri);
229 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100230 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800231 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800232 return rejectInsert(uri, initialValues);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800233 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700234 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700235 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100236 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700237 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700238 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 }
241
Jeff Brown75ea64f2012-01-25 19:37:13 -0800242 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800243 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100244 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100245 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800246 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800247 return 0;
248 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700249 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700250 try {
251 return ContentProvider.this.bulkInsert(uri, initialValues);
252 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700253 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 }
256
Jeff Brown75ea64f2012-01-25 19:37:13 -0800257 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800258 public ContentProviderResult[] applyBatch(String callingPkg,
259 ArrayList<ContentProviderOperation> operations)
Fred Quintana89437372009-05-15 15:10:40 -0700260 throws OperationApplicationException {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100261 int numOperations = operations.size();
262 final int[] userIds = new int[numOperations];
263 for (int i = 0; i < numOperations; i++) {
264 ContentProviderOperation operation = operations.get(i);
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100265 Uri uri = operation.getUri();
266 validateIncomingUri(uri);
267 userIds[i] = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100268 if (userIds[i] != UserHandle.USER_CURRENT) {
269 // Removing the user id from the uri.
270 operation = new ContentProviderOperation(operation, true);
271 operations.set(i, operation);
272 }
Fred Quintana89437372009-05-15 15:10:40 -0700273 if (operation.isReadOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800274 if (enforceReadPermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800275 != AppOpsManager.MODE_ALLOWED) {
276 throw new OperationApplicationException("App op not allowed", 0);
277 }
Fred Quintana89437372009-05-15 15:10:40 -0700278 }
Fred Quintana89437372009-05-15 15:10:40 -0700279 if (operation.isWriteOperation()) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800280 if (enforceWritePermission(callingPkg, uri, null)
Dianne Hackborn35654b62013-01-14 17:38:02 -0800281 != AppOpsManager.MODE_ALLOWED) {
282 throw new OperationApplicationException("App op not allowed", 0);
283 }
Fred Quintana89437372009-05-15 15:10:40 -0700284 }
285 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700286 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700287 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100288 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
289 for (int i = 0; i < results.length ; i++) {
290 if (userIds[i] != UserHandle.USER_CURRENT) {
291 // Adding the userId to the uri.
292 results[i] = new ContentProviderResult(results[i], userIds[i]);
293 }
294 }
295 return results;
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700296 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700297 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700298 }
Fred Quintana6a8d5332009-05-07 17:35:38 -0700299 }
300
Jeff Brown75ea64f2012-01-25 19:37:13 -0800301 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800302 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100303 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100304 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800305 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800306 return 0;
307 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700308 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700309 try {
310 return ContentProvider.this.delete(uri, selection, selectionArgs);
311 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700312 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800314 }
315
Jeff Brown75ea64f2012-01-25 19:37:13 -0800316 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800317 public int update(String callingPkg, Uri uri, ContentValues values, String selection,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 String[] selectionArgs) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100319 validateIncomingUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100320 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800321 if (enforceWritePermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800322 return 0;
323 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700324 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700325 try {
326 return ContentProvider.this.update(uri, values, selection, selectionArgs);
327 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700328 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 }
331
Jeff Brown75ea64f2012-01-25 19:37:13 -0800332 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700333 public ParcelFileDescriptor openFile(
Dianne Hackbornff170242014-11-19 10:59:01 -0800334 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal,
335 IBinder callerToken) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100336 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100337 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800338 enforceFilePermission(callingPkg, uri, mode, callerToken);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700339 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700340 try {
341 return ContentProvider.this.openFile(
342 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
343 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700344 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 }
347
Jeff Brown75ea64f2012-01-25 19:37:13 -0800348 @Override
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700349 public AssetFileDescriptor openAssetFile(
350 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800351 throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100352 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100353 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800354 enforceFilePermission(callingPkg, uri, mode, null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700355 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700356 try {
357 return ContentProvider.this.openAssetFile(
358 uri, mode, CancellationSignal.fromTransport(cancellationSignal));
359 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700360 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362 }
363
Jeff Brown75ea64f2012-01-25 19:37:13 -0800364 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800365 public Bundle call(String callingPkg, String method, String arg, Bundle extras) {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700366 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700367 try {
368 return ContentProvider.this.call(method, arg, extras);
369 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700370 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700371 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -0800372 }
373
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700374 @Override
375 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100376 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100377 uri = getUriWithoutUserId(uri);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700378 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter);
379 }
380
381 @Override
Dianne Hackborn35654b62013-01-14 17:38:02 -0800382 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType,
Jeff Sharkeybd3b9022013-08-20 15:20:04 -0700383 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100384 validateIncomingUri(uri);
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100385 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800386 enforceFilePermission(callingPkg, uri, "r", null);
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700387 final String original = setCallingPackage(callingPkg);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700388 try {
389 return ContentProvider.this.openTypedAssetFile(
390 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal));
391 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700392 setCallingPackage(original);
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700393 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -0700394 }
395
Jeff Brown75ea64f2012-01-25 19:37:13 -0800396 @Override
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700397 public ICancellationSignal createCancellationSignal() {
Jeff Brown4c1241d2012-02-02 17:05:00 -0800398 return CancellationSignal.createTransport();
Jeff Brown75ea64f2012-01-25 19:37:13 -0800399 }
400
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700401 @Override
402 public Uri canonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100403 validateIncomingUri(uri);
404 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100405 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800406 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700407 return null;
408 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700409 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700410 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100411 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700412 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700413 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700414 }
415 }
416
417 @Override
418 public Uri uncanonicalize(String callingPkg, Uri uri) {
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100419 validateIncomingUri(uri);
420 int userId = getUserIdFromUri(uri);
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100421 uri = getUriWithoutUserId(uri);
Dianne Hackbornff170242014-11-19 10:59:01 -0800422 if (enforceReadPermission(callingPkg, uri, null) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700423 return null;
424 }
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700425 final String original = setCallingPackage(callingPkg);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700426 try {
Nicolas Prevotd85fc722014-04-16 19:52:08 +0100427 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700428 } finally {
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700429 setCallingPackage(original);
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700430 }
431 }
432
Dianne Hackbornff170242014-11-19 10:59:01 -0800433 private void enforceFilePermission(String callingPkg, Uri uri, String mode,
434 IBinder callerToken) throws FileNotFoundException, SecurityException {
Jeff Sharkeyba761972013-02-28 15:57:36 -0800435 if (mode != null && mode.indexOf('w') != -1) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800436 if (enforceWritePermission(callingPkg, uri, callerToken)
437 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800438 throw new FileNotFoundException("App op not allowed");
439 }
440 } else {
Dianne Hackbornff170242014-11-19 10:59:01 -0800441 if (enforceReadPermission(callingPkg, uri, callerToken)
442 != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800443 throw new FileNotFoundException("App op not allowed");
444 }
445 }
446 }
447
Dianne Hackbornff170242014-11-19 10:59:01 -0800448 private int enforceReadPermission(String callingPkg, Uri uri, IBinder callerToken)
449 throws SecurityException {
450 enforceReadPermissionInner(uri, callerToken);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800451 if (mReadOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800452 return mAppOpsManager.noteOp(mReadOp, Binder.getCallingUid(), callingPkg);
453 }
454 return AppOpsManager.MODE_ALLOWED;
455 }
456
Dianne Hackbornff170242014-11-19 10:59:01 -0800457 private int enforceWritePermission(String callingPkg, Uri uri, IBinder callerToken)
458 throws SecurityException {
459 enforceWritePermissionInner(uri, callerToken);
Dianne Hackborn961321f2013-02-05 17:22:41 -0800460 if (mWriteOp != AppOpsManager.OP_NONE) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800461 return mAppOpsManager.noteOp(mWriteOp, Binder.getCallingUid(), callingPkg);
462 }
463 return AppOpsManager.MODE_ALLOWED;
464 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700465 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800466
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100467 boolean checkUser(int pid, int uid, Context context) {
468 return UserHandle.getUserId(uid) == context.getUserId()
Amith Yamasania6f4d582014-08-07 17:58:39 -0700469 || mSingleUser
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100470 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid)
471 == PERMISSION_GRANTED;
472 }
473
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700474 /** {@hide} */
Dianne Hackbornff170242014-11-19 10:59:01 -0800475 protected void enforceReadPermissionInner(Uri uri, IBinder callerToken)
476 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700477 final Context context = getContext();
478 final int pid = Binder.getCallingPid();
479 final int uid = Binder.getCallingUid();
480 String missingPerm = null;
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700481
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700482 if (UserHandle.isSameApp(uid, mMyUid)) {
483 return;
484 }
485
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100486 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700487 final String componentPerm = getReadPermission();
488 if (componentPerm != null) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800489 if (context.checkPermission(componentPerm, pid, uid, callerToken)
490 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700491 return;
492 } else {
493 missingPerm = componentPerm;
494 }
Jeff Sharkeye5d49332012-03-13 12:13:17 -0700495 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700496
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700497 // track if unprotected read is allowed; any denied
498 // <path-permission> below removes this ability
499 boolean allowDefaultRead = (componentPerm == null);
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700500
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700501 final PathPermission[] pps = getPathPermissions();
502 if (pps != null) {
503 final String path = uri.getPath();
504 for (PathPermission pp : pps) {
505 final String pathPerm = pp.getReadPermission();
506 if (pathPerm != null && pp.match(path)) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800507 if (context.checkPermission(pathPerm, pid, uid, callerToken)
508 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700509 return;
510 } else {
511 // any denied <path-permission> means we lose
512 // default <provider> access.
513 allowDefaultRead = false;
514 missingPerm = pathPerm;
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700515 }
516 }
517 }
518 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -0700519
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700520 // if we passed <path-permission> checks above, and no default
521 // <provider> permission, then allow access.
522 if (allowDefaultRead) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 }
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700524
525 // last chance, check against any uri grants
Amith Yamasani7d2d4fd2014-11-05 15:46:09 -0800526 final int callingUserId = UserHandle.getUserId(uid);
527 final Uri userUri = (mSingleUser && !UserHandle.isSameUser(mMyUid, uid))
528 ? maybeAddUserId(uri, callingUserId) : uri;
Dianne Hackbornff170242014-11-19 10:59:01 -0800529 if (context.checkUriPermission(userUri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION,
530 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700531 return;
532 }
533
534 final String failReason = mExported
535 ? " requires " + missingPerm + ", or grantUriPermission()"
536 : " requires the provider be exported, or grantUriPermission()";
537 throw new SecurityException("Permission Denial: reading "
538 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
539 + ", uid=" + uid + failReason);
540 }
541
542 /** {@hide} */
Dianne Hackbornff170242014-11-19 10:59:01 -0800543 protected void enforceWritePermissionInner(Uri uri, IBinder callerToken)
544 throws SecurityException {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700545 final Context context = getContext();
546 final int pid = Binder.getCallingPid();
547 final int uid = Binder.getCallingUid();
548 String missingPerm = null;
549
550 if (UserHandle.isSameApp(uid, mMyUid)) {
551 return;
552 }
553
Nicolas Prevot504d78e2014-06-26 10:07:33 +0100554 if (mExported && checkUser(pid, uid, context)) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700555 final String componentPerm = getWritePermission();
556 if (componentPerm != null) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800557 if (context.checkPermission(componentPerm, pid, uid, callerToken)
558 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700559 return;
560 } else {
561 missingPerm = componentPerm;
562 }
563 }
564
565 // track if unprotected write is allowed; any denied
566 // <path-permission> below removes this ability
567 boolean allowDefaultWrite = (componentPerm == null);
568
569 final PathPermission[] pps = getPathPermissions();
570 if (pps != null) {
571 final String path = uri.getPath();
572 for (PathPermission pp : pps) {
573 final String pathPerm = pp.getWritePermission();
574 if (pathPerm != null && pp.match(path)) {
Dianne Hackbornff170242014-11-19 10:59:01 -0800575 if (context.checkPermission(pathPerm, pid, uid, callerToken)
576 == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700577 return;
578 } else {
579 // any denied <path-permission> means we lose
580 // default <provider> access.
581 allowDefaultWrite = false;
582 missingPerm = pathPerm;
583 }
584 }
585 }
586 }
587
588 // if we passed <path-permission> checks above, and no default
589 // <provider> permission, then allow access.
590 if (allowDefaultWrite) return;
591 }
592
593 // last chance, check against any uri grants
Dianne Hackbornff170242014-11-19 10:59:01 -0800594 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION,
595 callerToken) == PERMISSION_GRANTED) {
Jeff Sharkey8a2998e2013-10-31 14:55:44 -0700596 return;
597 }
598
599 final String failReason = mExported
600 ? " requires " + missingPerm + ", or grantUriPermission()"
601 : " requires the provider be exported, or grantUriPermission()";
602 throw new SecurityException("Permission Denial: writing "
603 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid
604 + ", uid=" + uid + failReason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 }
606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700608 * Retrieves the Context this provider is running in. Only available once
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800609 * {@link #onCreate} has been called -- this will return {@code null} in the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 * constructor.
611 */
612 public final Context getContext() {
613 return mContext;
614 }
615
616 /**
Jeff Sharkey72e2e352013-09-09 18:52:48 -0700617 * Set the calling package, returning the current value (or {@code null})
618 * which can be used later to restore the previous state.
619 */
620 private String setCallingPackage(String callingPackage) {
621 final String original = mCallingPackage.get();
622 mCallingPackage.set(callingPackage);
623 return original;
624 }
625
626 /**
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700627 * Return the package name of the caller that initiated the request being
628 * processed on the current thread. The returned package will have been
629 * verified to belong to the calling UID. Returns {@code null} if not
630 * currently processing a request.
631 * <p>
632 * This will always return {@code null} when processing
633 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests.
634 *
635 * @see Binder#getCallingUid()
636 * @see Context#grantUriPermission(String, Uri, int)
637 * @throws SecurityException if the calling package doesn't belong to the
638 * calling UID.
639 */
640 public final String getCallingPackage() {
641 final String pkg = mCallingPackage.get();
642 if (pkg != null) {
643 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg);
644 }
645 return pkg;
646 }
647
648 /**
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100649 * Change the authorities of the ContentProvider.
650 * This is normally set for you from its manifest information when the provider is first
651 * created.
652 * @hide
653 * @param authorities the semi-colon separated authorities of the ContentProvider.
654 */
655 protected final void setAuthorities(String authorities) {
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100656 if (authorities != null) {
657 if (authorities.indexOf(';') == -1) {
658 mAuthority = authorities;
659 mAuthorities = null;
660 } else {
661 mAuthority = null;
662 mAuthorities = authorities.split(";");
663 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100664 }
665 }
666
667 /** @hide */
668 protected final boolean matchesOurAuthorities(String authority) {
669 if (mAuthority != null) {
670 return mAuthority.equals(authority);
671 }
Nicolas Prevot6e412ad2014-09-08 18:26:55 +0100672 if (mAuthorities != null) {
673 int length = mAuthorities.length;
674 for (int i = 0; i < length; i++) {
675 if (mAuthorities[i].equals(authority)) return true;
676 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +0100677 }
678 return false;
679 }
680
681
682 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 * Change the permission required to read data from the content
684 * provider. This is normally set for you from its manifest information
685 * when the provider is first created.
686 *
687 * @param permission Name of the permission required for read-only access.
688 */
689 protected final void setReadPermission(String permission) {
690 mReadPermission = permission;
691 }
692
693 /**
694 * Return the name of the permission required for read-only access to
695 * this content provider. This method can be called from multiple
696 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800697 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
698 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 */
700 public final String getReadPermission() {
701 return mReadPermission;
702 }
703
704 /**
705 * Change the permission required to read and write data in the content
706 * provider. This is normally set for you from its manifest information
707 * when the provider is first created.
708 *
709 * @param permission Name of the permission required for read/write access.
710 */
711 protected final void setWritePermission(String permission) {
712 mWritePermission = permission;
713 }
714
715 /**
716 * Return the name of the permission required for read/write access to
717 * this content provider. This method can be called from multiple
718 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800719 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
720 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 */
722 public final String getWritePermission() {
723 return mWritePermission;
724 }
725
726 /**
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700727 * Change the path-based permission required to read and/or write data in
728 * the content provider. This is normally set for you from its manifest
729 * information when the provider is first created.
730 *
731 * @param permissions Array of path permission descriptions.
732 */
733 protected final void setPathPermissions(PathPermission[] permissions) {
734 mPathPermissions = permissions;
735 }
736
737 /**
738 * Return the path-based permissions required for read and/or write access to
739 * this content provider. This method can be called from multiple
740 * threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800741 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
742 * and Threads</a>.
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700743 */
744 public final PathPermission[] getPathPermissions() {
745 return mPathPermissions;
746 }
747
Dianne Hackborn35654b62013-01-14 17:38:02 -0800748 /** @hide */
749 public final void setAppOps(int readOp, int writeOp) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800750 if (!mNoPerms) {
Dianne Hackborn7e6f9762013-02-26 13:35:11 -0800751 mTransport.mReadOp = readOp;
752 mTransport.mWriteOp = writeOp;
753 }
Dianne Hackborn35654b62013-01-14 17:38:02 -0800754 }
755
Dianne Hackborn961321f2013-02-05 17:22:41 -0800756 /** @hide */
757 public AppOpsManager getAppOpsManager() {
758 return mTransport.mAppOpsManager;
759 }
760
Dianne Hackborn2af632f2009-07-08 14:56:37 -0700761 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700762 * Implement this to initialize your content provider on startup.
763 * This method is called for all registered content providers on the
764 * application main thread at application launch time. It must not perform
765 * lengthy operations, or application startup will be delayed.
766 *
767 * <p>You should defer nontrivial initialization (such as opening,
768 * upgrading, and scanning databases) until the content provider is used
769 * (via {@link #query}, {@link #insert}, etc). Deferred initialization
770 * keeps application startup fast, avoids unnecessary work if the provider
771 * turns out not to be needed, and stops database errors (such as a full
772 * disk) from halting application launch.
773 *
Dan Egnor17876aa2010-07-28 12:28:04 -0700774 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper}
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700775 * is a helpful utility class that makes it easy to manage databases,
776 * and will automatically defer opening until first use. If you do use
777 * SQLiteOpenHelper, make sure to avoid calling
778 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
779 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
780 * from this method. (Instead, override
781 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
782 * database when it is first opened.)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800783 *
784 * @return true if the provider was successfully loaded, false otherwise
785 */
786 public abstract boolean onCreate();
787
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700788 /**
789 * {@inheritDoc}
790 * This method is always called on the application main thread, and must
791 * not perform lengthy operations.
792 *
793 * <p>The default content provider implementation does nothing.
794 * Override this method to take appropriate action.
795 * (Content providers do not usually care about things like screen
796 * orientation, but may want to know about locale changes.)
797 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 public void onConfigurationChanged(Configuration newConfig) {
799 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700800
801 /**
802 * {@inheritDoc}
803 * This method is always called on the application main thread, and must
804 * not perform lengthy operations.
805 *
806 * <p>The default content provider implementation does nothing.
807 * Subclasses may override this method to take appropriate action.
808 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 public void onLowMemory() {
810 }
811
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700812 public void onTrimMemory(int level) {
813 }
814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800816 * @hide
817 * Implementation when a caller has performed a query on the content
818 * provider, but that call has been rejected for the operation given
819 * to {@link #setAppOps(int, int)}. The default implementation
820 * rewrites the <var>selection</var> argument to include a condition
821 * that is never true (so will always result in an empty cursor)
822 * and calls through to {@link #query(android.net.Uri, String[], String, String[],
823 * String, android.os.CancellationSignal)} with that.
824 */
825 public Cursor rejectQuery(Uri uri, String[] projection,
826 String selection, String[] selectionArgs, String sortOrder,
827 CancellationSignal cancellationSignal) {
828 // The read is not allowed... to fake it out, we replace the given
829 // selection statement with a dummy one that will always be false.
830 // This way we will get a cursor back that has the correct structure
831 // but contains no rows.
Dianne Hackborn9fa39bd2013-03-22 18:42:14 -0700832 if (selection == null || selection.isEmpty()) {
Dianne Hackbornd7960d12013-01-29 18:55:48 -0800833 selection = "'A' = 'B'";
834 } else {
835 selection = "'A' = 'B' AND (" + selection + ")";
836 }
837 return query(uri, projection, selection, selectionArgs, sortOrder, cancellationSignal);
838 }
839
840 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700841 * Implement this to handle query requests from clients.
842 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800843 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
844 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 * <p>
846 * Example client call:<p>
847 * <pre>// Request a specific record.
848 * Cursor managedCursor = managedQuery(
Alan Jones81a476f2009-05-21 12:32:17 +1000849 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 projection, // Which columns to return.
851 null, // WHERE clause.
Alan Jones81a476f2009-05-21 12:32:17 +1000852 null, // WHERE clause value substitution
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 People.NAME + " ASC"); // Sort order.</pre>
854 * Example implementation:<p>
855 * <pre>// SQLiteQueryBuilder is a helper class that creates the
856 // proper SQL syntax for us.
857 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
858
859 // Set the table we're querying.
860 qBuilder.setTables(DATABASE_TABLE_NAME);
861
862 // If the query ends in a specific record number, we're
863 // being asked for a specific record, so set the
864 // WHERE clause in our query.
865 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
866 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
867 }
868
869 // Make the query.
870 Cursor c = qBuilder.query(mDb,
871 projection,
872 selection,
873 selectionArgs,
874 groupBy,
875 having,
876 sortOrder);
877 c.setNotificationUri(getContext().getContentResolver(), uri);
878 return c;</pre>
879 *
880 * @param uri The URI to query. This will be the full URI sent by the client;
Alan Jones81a476f2009-05-21 12:32:17 +1000881 * if the client is requesting a specific record, the URI will end in a record number
882 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
883 * that _id value.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800885 * {@code null} all columns are included.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800887 * If {@code null} then all rows are included.
Alan Jones81a476f2009-05-21 12:32:17 +1000888 * @param selectionArgs You may include ?s in selection, which will be replaced by
889 * the values from selectionArgs, in order that they appear in the selection.
890 * The values will be bound as Strings.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800892 * If {@code null} then the provider is free to define the sort order.
893 * @return a Cursor or {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 */
895 public abstract Cursor query(Uri uri, String[] projection,
896 String selection, String[] selectionArgs, String sortOrder);
897
Fred Quintana5bba6322009-10-05 14:21:12 -0700898 /**
Jeff Brown4c1241d2012-02-02 17:05:00 -0800899 * Implement this to handle query requests from clients with support for cancellation.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800900 * This method can be called from multiple threads, as described in
901 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
902 * and Threads</a>.
903 * <p>
904 * Example client call:<p>
905 * <pre>// Request a specific record.
906 * Cursor managedCursor = managedQuery(
907 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2),
908 projection, // Which columns to return.
909 null, // WHERE clause.
910 null, // WHERE clause value substitution
911 People.NAME + " ASC"); // Sort order.</pre>
912 * Example implementation:<p>
913 * <pre>// SQLiteQueryBuilder is a helper class that creates the
914 // proper SQL syntax for us.
915 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
916
917 // Set the table we're querying.
918 qBuilder.setTables(DATABASE_TABLE_NAME);
919
920 // If the query ends in a specific record number, we're
921 // being asked for a specific record, so set the
922 // WHERE clause in our query.
923 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
924 qBuilder.appendWhere("_id=" + uri.getPathLeafId());
925 }
926
927 // Make the query.
928 Cursor c = qBuilder.query(mDb,
929 projection,
930 selection,
931 selectionArgs,
932 groupBy,
933 having,
934 sortOrder);
935 c.setNotificationUri(getContext().getContentResolver(), uri);
936 return c;</pre>
937 * <p>
938 * If you implement this method then you must also implement the version of
Jeff Brown4c1241d2012-02-02 17:05:00 -0800939 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation
940 * signal to ensure correct operation on older versions of the Android Framework in
941 * which the cancellation signal overload was not available.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800942 *
943 * @param uri The URI to query. This will be the full URI sent by the client;
944 * if the client is requesting a specific record, the URI will end in a record number
945 * that the implementation should parse and add to a WHERE or HAVING clause, specifying
946 * that _id value.
947 * @param projection The list of columns to put into the cursor. If
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800948 * {@code null} all columns are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800949 * @param selection A selection criteria to apply when filtering rows.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800950 * If {@code null} then all rows are included.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800951 * @param selectionArgs You may include ?s in selection, which will be replaced by
952 * the values from selectionArgs, in order that they appear in the selection.
953 * The values will be bound as Strings.
954 * @param sortOrder How the rows in the cursor should be sorted.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800955 * If {@code null} then the provider is free to define the sort order.
956 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800957 * If the operation is canceled, then {@link OperationCanceledException} will be thrown
958 * when the query is executed.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800959 * @return a Cursor or {@code null}.
Jeff Brown75ea64f2012-01-25 19:37:13 -0800960 */
961 public Cursor query(Uri uri, String[] projection,
962 String selection, String[] selectionArgs, String sortOrder,
Jeff Brown4c1241d2012-02-02 17:05:00 -0800963 CancellationSignal cancellationSignal) {
Jeff Brown75ea64f2012-01-25 19:37:13 -0800964 return query(uri, projection, selection, selectionArgs, sortOrder);
965 }
966
967 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700968 * Implement this to handle requests for the MIME type of the data at the
969 * given URI. The returned MIME type should start with
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 * <code>vnd.android.cursor.item</code> for a single record,
971 * or <code>vnd.android.cursor.dir/</code> for multiple items.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -0700972 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -0800973 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
974 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 *
Dianne Hackborncca1f0e2010-09-26 18:34:53 -0700976 * <p>Note that there are no permissions needed for an application to
977 * access this information; if your content provider requires read and/or
978 * write permissions, or is not exported, all applications can still call
979 * this method regardless of their access permissions. This allows them
980 * to retrieve the MIME type for a URI when dispatching intents.
981 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 * @param uri the URI to query.
Christopher Tate2bc6eb82013-01-03 12:04:08 -0800983 * @return a MIME type string, or {@code null} if there is no type.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 */
985 public abstract String getType(Uri uri);
986
987 /**
Dianne Hackborn38ed2a42013-09-06 16:17:22 -0700988 * Implement this to support canonicalization of URIs that refer to your
989 * content provider. A canonical URI is one that can be transported across
990 * devices, backup/restore, and other contexts, and still be able to refer
991 * to the same data item. Typically this is implemented by adding query
992 * params to the URI allowing the content provider to verify that an incoming
993 * canonical URI references the same data as it was originally intended for and,
994 * if it doesn't, to find that data (if it exists) in the current environment.
995 *
996 * <p>For example, if the content provider holds people and a normal URI in it
997 * is created with a row index into that people database, the cananical representation
998 * may have an additional query param at the end which specifies the name of the
999 * person it is intended for. Later calls into the provider with that URI will look
1000 * up the row of that URI's base index and, if it doesn't match or its entry's
1001 * name doesn't match the name in the query param, perform a query on its database
1002 * to find the correct row to operate on.</p>
1003 *
1004 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with
1005 * URIs (including this one) must perform this verification and recovery of any
1006 * canonical URIs they receive. In addition, you must also implement
1007 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p>
1008 *
1009 * <p>The default implementation of this method returns null, indicating that
1010 * canonical URIs are not supported.</p>
1011 *
1012 * @param url The Uri to canonicalize.
1013 *
1014 * @return Return the canonical representation of <var>url</var>, or null if
1015 * canonicalization of that Uri is not supported.
1016 */
1017 public Uri canonicalize(Uri url) {
1018 return null;
1019 }
1020
1021 /**
1022 * Remove canonicalization from canonical URIs previously returned by
1023 * {@link #canonicalize}. For example, if your implementation is to add
1024 * a query param to canonicalize a URI, this method can simply trip any
1025 * query params on the URI. The default implementation always returns the
1026 * same <var>url</var> that was passed in.
1027 *
1028 * @param url The Uri to remove any canonicalization from.
1029 *
Dianne Hackbornb3ac67a2013-09-11 11:02:24 -07001030 * @return Return the non-canonical representation of <var>url</var>, return
1031 * the <var>url</var> as-is if there is nothing to do, or return null if
1032 * the data identified by the canonical representation can not be found in
1033 * the current environment.
Dianne Hackborn38ed2a42013-09-06 16:17:22 -07001034 */
1035 public Uri uncanonicalize(Uri url) {
1036 return url;
1037 }
1038
1039 /**
Dianne Hackbornd7960d12013-01-29 18:55:48 -08001040 * @hide
1041 * Implementation when a caller has performed an insert on the content
1042 * provider, but that call has been rejected for the operation given
1043 * to {@link #setAppOps(int, int)}. The default implementation simply
1044 * returns a dummy URI that is the base URI with a 0 path element
1045 * appended.
1046 */
1047 public Uri rejectInsert(Uri uri, ContentValues values) {
1048 // If not allowed, we need to return some reasonable URI. Maybe the
1049 // content provider should be responsible for this, but for now we
1050 // will just return the base URI with a dummy '0' tagged on to it.
1051 // You shouldn't be able to read if you can't write, anyway, so it
1052 // shouldn't matter much what is returned.
1053 return uri.buildUpon().appendPath("0").build();
1054 }
1055
1056 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001057 * Implement this to handle requests to insert a new row.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1059 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001060 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001061 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1062 * and Threads</a>.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001063 * @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 -08001064 * @param values A set of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001065 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 * @return The URI for the newly inserted item.
1067 */
1068 public abstract Uri insert(Uri uri, ContentValues values);
1069
1070 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001071 * Override this to handle requests to insert a set of new rows, or the
1072 * default implementation will iterate over the values and call
1073 * {@link #insert} on each of them.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1075 * after inserting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001076 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001077 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1078 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 *
1080 * @param uri The content:// URI of the insertion request.
1081 * @param values An array of sets of column_name/value pairs to add to the database.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001082 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 * @return The number of values that were inserted.
1084 */
1085 public int bulkInsert(Uri uri, ContentValues[] values) {
1086 int numValues = values.length;
1087 for (int i = 0; i < numValues; i++) {
1088 insert(uri, values[i]);
1089 }
1090 return numValues;
1091 }
1092
1093 /**
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001094 * Implement this to handle requests to delete one or more rows.
1095 * The implementation should apply the selection clause when performing
1096 * deletion, allowing the operation to affect multiple rows in a directory.
Taeho Kimbd88de42013-10-28 15:08:53 +09001097 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 * after deleting.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001099 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001100 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1101 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 *
1103 * <p>The implementation is responsible for parsing out a row ID at the end
1104 * of the URI, if a specific row is being deleted. That is, the client would
1105 * pass in <code>content://contacts/people/22</code> and the implementation is
1106 * responsible for parsing the record number (22) when creating a SQL statement.
1107 *
1108 * @param uri The full URI to query, including a row ID (if a specific record is requested).
1109 * @param selection An optional restriction to apply to rows when deleting.
1110 * @return The number of rows affected.
1111 * @throws SQLException
1112 */
1113 public abstract int delete(Uri uri, String selection, String[] selectionArgs);
1114
1115 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001116 * Implement this to handle requests to update one or more rows.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001117 * The implementation should update all rows matching the selection
1118 * to set the columns according to the provided values map.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
1120 * after updating.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001121 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001122 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1123 * and Threads</a>.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 *
1125 * @param uri The URI to query. This can potentially have a record ID if this
1126 * is an update request for a specific record.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001127 * @param values A set of column_name/value pairs to update in the database.
1128 * This must not be {@code null}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 * @param selection An optional filter to match rows to update.
1130 * @return the number of rows affected.
1131 */
1132 public abstract int update(Uri uri, ContentValues values, String selection,
1133 String[] selectionArgs);
1134
1135 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001136 * Override this to handle requests to open a file blob.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001137 * The default implementation always throws {@link FileNotFoundException}.
1138 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001139 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1140 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001141 *
Dan Egnor17876aa2010-07-28 12:28:04 -07001142 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1143 * to the caller. This way large data (such as images and documents) can be
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001144 * returned without copying the content.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 *
1146 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1147 * their responsibility to close it when done. That is, the implementation
1148 * of this method should create a new ParcelFileDescriptor for each call.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001149 * <p>
1150 * If opened with the exclusive "r" or "w" modes, the returned
1151 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1152 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1153 * supports seeking.
1154 * <p>
1155 * If you need to detect when the returned ParcelFileDescriptor has been
1156 * closed, or if the remote process has crashed or encountered some other
1157 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1158 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1159 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1160 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001162 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1163 * to return the appropriate MIME type for the data returned here with
1164 * the same URI. This will allow intent resolution to automatically determine the data MIME
1165 * type and select the appropriate matching targets as part of its operation.</p>
1166 *
1167 * <p class="note">For better interoperability with other applications, it is recommended
1168 * that for any URIs that can be opened, you also support queries on them
1169 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1170 * You may also want to support other common columns if you have additional meta-data
1171 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1172 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1173 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 * @param uri The URI whose file is to be opened.
1175 * @param mode Access mode for the file. May be "r" for read-only access,
1176 * "rw" for read and write access, or "rwt" for read and write access
1177 * that truncates any existing file.
1178 *
1179 * @return Returns a new ParcelFileDescriptor which you can use to access
1180 * the file.
1181 *
1182 * @throws FileNotFoundException Throws FileNotFoundException if there is
1183 * no file associated with the given URI or the mode is invalid.
1184 * @throws SecurityException Throws SecurityException if the caller does
1185 * not have permission to access the file.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001186 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 * @see #openAssetFile(Uri, String)
1188 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001189 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001190 * @see ParcelFileDescriptor#parseMode(String)
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001191 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 public ParcelFileDescriptor openFile(Uri uri, String mode)
1193 throws FileNotFoundException {
1194 throw new FileNotFoundException("No files supported by provider at "
1195 + uri);
1196 }
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001199 * Override this to handle requests to open a file blob.
1200 * The default implementation always throws {@link FileNotFoundException}.
1201 * This method can be called from multiple threads, as described in
1202 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1203 * and Threads</a>.
1204 *
1205 * <p>This method returns a ParcelFileDescriptor, which is returned directly
1206 * to the caller. This way large data (such as images and documents) can be
1207 * returned without copying the content.
1208 *
1209 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is
1210 * their responsibility to close it when done. That is, the implementation
1211 * of this method should create a new ParcelFileDescriptor for each call.
1212 * <p>
1213 * If opened with the exclusive "r" or "w" modes, the returned
1214 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming
1215 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that
1216 * supports seeking.
1217 * <p>
1218 * If you need to detect when the returned ParcelFileDescriptor has been
1219 * closed, or if the remote process has crashed or encountered some other
1220 * error, you can use {@link ParcelFileDescriptor#open(File, int,
1221 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)},
1222 * {@link ParcelFileDescriptor#createReliablePipe()}, or
1223 * {@link ParcelFileDescriptor#createReliableSocketPair()}.
1224 *
1225 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1226 * to return the appropriate MIME type for the data returned here with
1227 * the same URI. This will allow intent resolution to automatically determine the data MIME
1228 * type and select the appropriate matching targets as part of its operation.</p>
1229 *
1230 * <p class="note">For better interoperability with other applications, it is recommended
1231 * that for any URIs that can be opened, you also support queries on them
1232 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1233 * You may also want to support other common columns if you have additional meta-data
1234 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1235 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1236 *
1237 * @param uri The URI whose file is to be opened.
1238 * @param mode Access mode for the file. May be "r" for read-only access,
1239 * "w" for write-only access, "rw" for read and write access, or
1240 * "rwt" for read and write access that truncates any existing
1241 * file.
1242 * @param signal A signal to cancel the operation in progress, or
1243 * {@code null} if none. For example, if you are downloading a
1244 * file from the network to service a "rw" mode request, you
1245 * should periodically call
1246 * {@link CancellationSignal#throwIfCanceled()} to check whether
1247 * the client has canceled the request and abort the download.
1248 *
1249 * @return Returns a new ParcelFileDescriptor which you can use to access
1250 * the file.
1251 *
1252 * @throws FileNotFoundException Throws FileNotFoundException if there is
1253 * no file associated with the given URI or the mode is invalid.
1254 * @throws SecurityException Throws SecurityException if the caller does
1255 * not have permission to access the file.
1256 *
1257 * @see #openAssetFile(Uri, String)
1258 * @see #openFileHelper(Uri, String)
1259 * @see #getType(android.net.Uri)
Jeff Sharkeye8c00d82013-10-15 15:46:10 -07001260 * @see ParcelFileDescriptor#parseMode(String)
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001261 */
1262 public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)
1263 throws FileNotFoundException {
1264 return openFile(uri, mode);
1265 }
1266
1267 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 * This is like {@link #openFile}, but can be implemented by providers
1269 * that need to be able to return sub-sections of files, often assets
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001270 * inside of their .apk.
1271 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001272 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1273 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001274 *
1275 * <p>If you implement this, your clients must be able to deal with such
Dan Egnor17876aa2010-07-28 12:28:04 -07001276 * file slices, either directly with
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001277 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1279 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1280 * methods.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001281 * <p>
1282 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1283 * streaming of data.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001284 *
1285 * <p class="note">If you are implementing this to return a full file, you
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 * should create the AssetFileDescriptor with
1287 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001288 * applications that cannot handle sub-sections of files.</p>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001290 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1291 * to return the appropriate MIME type for the data returned here with
1292 * the same URI. This will allow intent resolution to automatically determine the data MIME
1293 * type and select the appropriate matching targets as part of its operation.</p>
1294 *
1295 * <p class="note">For better interoperability with other applications, it is recommended
1296 * that for any URIs that can be opened, you also support queries on them
1297 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1298 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 * @param uri The URI whose file is to be opened.
1300 * @param mode Access mode for the file. May be "r" for read-only access,
1301 * "w" for write-only access (erasing whatever data is currently in
1302 * the file), "wa" for write-only access to append to any existing data,
1303 * "rw" for read and write access on any existing data, and "rwt" for read
1304 * and write access that truncates any existing file.
1305 *
1306 * @return Returns a new AssetFileDescriptor which you can use to access
1307 * the file.
1308 *
1309 * @throws FileNotFoundException Throws FileNotFoundException if there is
1310 * no file associated with the given URI or the mode is invalid.
1311 * @throws SecurityException Throws SecurityException if the caller does
1312 * not have permission to access the file.
1313 *
1314 * @see #openFile(Uri, String)
1315 * @see #openFileHelper(Uri, String)
Dianne Hackborna53ee352013-02-20 12:47:02 -08001316 * @see #getType(android.net.Uri)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 */
1318 public AssetFileDescriptor openAssetFile(Uri uri, String mode)
1319 throws FileNotFoundException {
1320 ParcelFileDescriptor fd = openFile(uri, mode);
1321 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null;
1322 }
1323
1324 /**
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001325 * This is like {@link #openFile}, but can be implemented by providers
1326 * that need to be able to return sub-sections of files, often assets
1327 * inside of their .apk.
1328 * This method can be called from multiple threads, as described in
1329 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1330 * and Threads</a>.
1331 *
1332 * <p>If you implement this, your clients must be able to deal with such
1333 * file slices, either directly with
1334 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
1335 * {@link ContentResolver#openInputStream ContentResolver.openInputStream}
1336 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
1337 * methods.
1338 * <p>
1339 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1340 * streaming of data.
1341 *
1342 * <p class="note">If you are implementing this to return a full file, you
1343 * should create the AssetFileDescriptor with
1344 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
1345 * applications that cannot handle sub-sections of files.</p>
1346 *
1347 * <p class="note">For use in Intents, you will want to implement {@link #getType}
1348 * to return the appropriate MIME type for the data returned here with
1349 * the same URI. This will allow intent resolution to automatically determine the data MIME
1350 * type and select the appropriate matching targets as part of its operation.</p>
1351 *
1352 * <p class="note">For better interoperability with other applications, it is recommended
1353 * that for any URIs that can be opened, you also support queries on them
1354 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p>
1355 *
1356 * @param uri The URI whose file is to be opened.
1357 * @param mode Access mode for the file. May be "r" for read-only access,
1358 * "w" for write-only access (erasing whatever data is currently in
1359 * the file), "wa" for write-only access to append to any existing data,
1360 * "rw" for read and write access on any existing data, and "rwt" for read
1361 * and write access that truncates any existing file.
1362 * @param signal A signal to cancel the operation in progress, or
1363 * {@code null} if none. For example, if you are downloading a
1364 * file from the network to service a "rw" mode request, you
1365 * should periodically call
1366 * {@link CancellationSignal#throwIfCanceled()} to check whether
1367 * the client has canceled the request and abort the download.
1368 *
1369 * @return Returns a new AssetFileDescriptor which you can use to access
1370 * the file.
1371 *
1372 * @throws FileNotFoundException Throws FileNotFoundException if there is
1373 * no file associated with the given URI or the mode is invalid.
1374 * @throws SecurityException Throws SecurityException if the caller does
1375 * not have permission to access the file.
1376 *
1377 * @see #openFile(Uri, String)
1378 * @see #openFileHelper(Uri, String)
1379 * @see #getType(android.net.Uri)
1380 */
1381 public AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)
1382 throws FileNotFoundException {
1383 return openAssetFile(uri, mode);
1384 }
1385
1386 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 * Convenience for subclasses that wish to implement {@link #openFile}
1388 * by looking up a column named "_data" at the given URI.
1389 *
1390 * @param uri The URI to be opened.
1391 * @param mode The file mode. May be "r" for read-only access,
1392 * "w" for write-only access (erasing whatever data is currently in
1393 * the file), "wa" for write-only access to append to any existing data,
1394 * "rw" for read and write access on any existing data, and "rwt" for read
1395 * and write access that truncates any existing file.
1396 *
1397 * @return Returns a new ParcelFileDescriptor that can be used by the
1398 * client to access the file.
1399 */
1400 protected final ParcelFileDescriptor openFileHelper(Uri uri,
1401 String mode) throws FileNotFoundException {
1402 Cursor c = query(uri, new String[]{"_data"}, null, null, null);
1403 int count = (c != null) ? c.getCount() : 0;
1404 if (count != 1) {
1405 // If there is not exactly one result, throw an appropriate
1406 // exception.
1407 if (c != null) {
1408 c.close();
1409 }
1410 if (count == 0) {
1411 throw new FileNotFoundException("No entry for " + uri);
1412 }
1413 throw new FileNotFoundException("Multiple items at " + uri);
1414 }
1415
1416 c.moveToFirst();
1417 int i = c.getColumnIndex("_data");
1418 String path = (i >= 0 ? c.getString(i) : null);
1419 c.close();
1420 if (path == null) {
1421 throw new FileNotFoundException("Column _data not found.");
1422 }
1423
Adam Lesinskieb8c3f92013-09-20 14:08:25 -07001424 int modeBits = ParcelFileDescriptor.parseMode(mode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 return ParcelFileDescriptor.open(new File(path), modeBits);
1426 }
1427
1428 /**
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001429 * Called by a client to determine the types of data streams that this
1430 * content provider supports for the given URI. The default implementation
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001431 * returns {@code null}, meaning no types. If your content provider stores data
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001432 * of a particular type, return that MIME type if it matches the given
1433 * mimeTypeFilter. If it can perform type conversions, return an array
1434 * of all supported MIME types that match mimeTypeFilter.
1435 *
1436 * @param uri The data in the content provider being queried.
1437 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001438 * a pattern, such as *&#47;* to retrieve all possible data types.
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001439 * @return Returns {@code null} if there are no possible data streams for the
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001440 * given mimeTypeFilter. Otherwise returns an array of all available
1441 * concrete MIME types.
1442 *
1443 * @see #getType(Uri)
1444 * @see #openTypedAssetFile(Uri, String, Bundle)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001445 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001446 */
1447 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
1448 return null;
1449 }
1450
1451 /**
1452 * Called by a client to open a read-only stream containing data of a
1453 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1454 * except the file can only be read-only and the content provider may
1455 * perform data conversions to generate data of the desired type.
1456 *
1457 * <p>The default implementation compares the given mimeType against the
Dianne Hackborna53ee352013-02-20 12:47:02 -08001458 * result of {@link #getType(Uri)} and, if they match, simply calls
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001459 * {@link #openAssetFile(Uri, String)}.
1460 *
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001461 * <p>See {@link ClipData} for examples of the use and implementation
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001462 * of this method.
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001463 * <p>
1464 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1465 * streaming of data.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001466 *
Dianne Hackborna53ee352013-02-20 12:47:02 -08001467 * <p class="note">For better interoperability with other applications, it is recommended
1468 * that for any URIs that can be opened, you also support queries on them
1469 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1470 * You may also want to support other common columns if you have additional meta-data
1471 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1472 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1473 *
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001474 * @param uri The data in the content provider being queried.
1475 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001476 * a pattern, such as *&#47;*, if the caller does not have specific type
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001477 * requirements; in this case the content provider will pick its best
1478 * type matching the pattern.
1479 * @param opts Additional options from the client. The definitions of
1480 * these are specific to the content provider being called.
1481 *
1482 * @return Returns a new AssetFileDescriptor from which the client can
1483 * read data of the desired type.
1484 *
1485 * @throws FileNotFoundException Throws FileNotFoundException if there is
1486 * no file associated with the given URI or the mode is invalid.
1487 * @throws SecurityException Throws SecurityException if the caller does
1488 * not have permission to access the data.
1489 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1490 * content provider does not support the requested MIME type.
1491 *
1492 * @see #getStreamTypes(Uri, String)
1493 * @see #openAssetFile(Uri, String)
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001494 * @see ClipDescription#compareMimeTypes(String, String)
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001495 */
1496 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)
1497 throws FileNotFoundException {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001498 if ("*/*".equals(mimeTypeFilter)) {
1499 // If they can take anything, the untyped open call is good enough.
1500 return openAssetFile(uri, "r");
1501 }
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001502 String baseType = getType(uri);
Dianne Hackborn1040dc42010-08-26 22:11:06 -07001503 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) {
Dianne Hackborn02dfd262010-08-13 12:34:58 -07001504 // Use old untyped open call if this provider has a type for this
1505 // URI and it matches the request.
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001506 return openAssetFile(uri, "r");
1507 }
1508 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter);
1509 }
1510
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001511
1512 /**
1513 * Called by a client to open a read-only stream containing data of a
1514 * particular MIME type. This is like {@link #openAssetFile(Uri, String)},
1515 * except the file can only be read-only and the content provider may
1516 * perform data conversions to generate data of the desired type.
1517 *
1518 * <p>The default implementation compares the given mimeType against the
1519 * result of {@link #getType(Uri)} and, if they match, simply calls
1520 * {@link #openAssetFile(Uri, String)}.
1521 *
1522 * <p>See {@link ClipData} for examples of the use and implementation
1523 * of this method.
1524 * <p>
1525 * The returned AssetFileDescriptor can be a pipe or socket pair to enable
1526 * streaming of data.
1527 *
1528 * <p class="note">For better interoperability with other applications, it is recommended
1529 * that for any URIs that can be opened, you also support queries on them
1530 * containing at least the columns specified by {@link android.provider.OpenableColumns}.
1531 * You may also want to support other common columns if you have additional meta-data
1532 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED}
1533 * in {@link android.provider.MediaStore.MediaColumns}.</p>
1534 *
1535 * @param uri The data in the content provider being queried.
1536 * @param mimeTypeFilter The type of data the client desires. May be
John Spurlock33900182014-01-02 11:04:18 -05001537 * a pattern, such as *&#47;*, if the caller does not have specific type
Jeff Sharkeybd3b9022013-08-20 15:20:04 -07001538 * requirements; in this case the content provider will pick its best
1539 * type matching the pattern.
1540 * @param opts Additional options from the client. The definitions of
1541 * these are specific to the content provider being called.
1542 * @param signal A signal to cancel the operation in progress, or
1543 * {@code null} if none. For example, if you are downloading a
1544 * file from the network to service a "rw" mode request, you
1545 * should periodically call
1546 * {@link CancellationSignal#throwIfCanceled()} to check whether
1547 * the client has canceled the request and abort the download.
1548 *
1549 * @return Returns a new AssetFileDescriptor from which the client can
1550 * read data of the desired type.
1551 *
1552 * @throws FileNotFoundException Throws FileNotFoundException if there is
1553 * no file associated with the given URI or the mode is invalid.
1554 * @throws SecurityException Throws SecurityException if the caller does
1555 * not have permission to access the data.
1556 * @throws IllegalArgumentException Throws IllegalArgumentException if the
1557 * content provider does not support the requested MIME type.
1558 *
1559 * @see #getStreamTypes(Uri, String)
1560 * @see #openAssetFile(Uri, String)
1561 * @see ClipDescription#compareMimeTypes(String, String)
1562 */
1563 public AssetFileDescriptor openTypedAssetFile(
1564 Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)
1565 throws FileNotFoundException {
1566 return openTypedAssetFile(uri, mimeTypeFilter, opts);
1567 }
1568
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001569 /**
1570 * Interface to write a stream of data to a pipe. Use with
1571 * {@link ContentProvider#openPipeHelper}.
1572 */
1573 public interface PipeDataWriter<T> {
1574 /**
1575 * Called from a background thread to stream data out to a pipe.
1576 * Note that the pipe is blocking, so this thread can block on
1577 * writes for an arbitrary amount of time if the client is slow
1578 * at reading.
1579 *
1580 * @param output The pipe where data should be written. This will be
1581 * closed for you upon returning from this function.
1582 * @param uri The URI whose data is to be written.
1583 * @param mimeType The desired type of data to be written.
1584 * @param opts Options supplied by caller.
1585 * @param args Your own custom arguments.
1586 */
1587 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType,
1588 Bundle opts, T args);
1589 }
1590
1591 /**
1592 * A helper function for implementing {@link #openTypedAssetFile}, for
1593 * creating a data pipe and background thread allowing you to stream
1594 * generated data back to the client. This function returns a new
1595 * ParcelFileDescriptor that should be returned to the caller (the caller
1596 * is responsible for closing it).
1597 *
1598 * @param uri The URI whose data is to be written.
1599 * @param mimeType The desired type of data to be written.
1600 * @param opts Options supplied by caller.
1601 * @param args Your own custom arguments.
1602 * @param func Interface implementing the function that will actually
1603 * stream the data.
1604 * @return Returns a new ParcelFileDescriptor holding the read side of
1605 * the pipe. This should be returned to the caller for reading; the caller
1606 * is responsible for closing it when done.
1607 */
1608 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType,
1609 final Bundle opts, final T args, final PipeDataWriter<T> func)
1610 throws FileNotFoundException {
1611 try {
1612 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe();
1613
1614 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() {
1615 @Override
1616 protected Object doInBackground(Object... params) {
1617 func.writeDataToPipe(fds[1], uri, mimeType, opts, args);
1618 try {
1619 fds[1].close();
1620 } catch (IOException e) {
1621 Log.w(TAG, "Failure closing pipe", e);
1622 }
1623 return null;
1624 }
1625 };
Dianne Hackborn5d9d03a2011-01-24 13:15:09 -08001626 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null);
Dianne Hackborn23fdaf62010-08-06 12:16:55 -07001627
1628 return fds[0];
1629 } catch (IOException e) {
1630 throw new FileNotFoundException("failure making pipe");
1631 }
1632 }
1633
1634 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 * Returns true if this instance is a temporary content provider.
1636 * @return true if this instance is a temporary content provider
1637 */
1638 protected boolean isTemporary() {
1639 return false;
1640 }
1641
1642 /**
1643 * Returns the Binder object for this provider.
1644 *
1645 * @return the Binder object for this provider
1646 * @hide
1647 */
1648 public IContentProvider getIContentProvider() {
1649 return mTransport;
1650 }
1651
1652 /**
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001653 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use
1654 * when directly instantiating the provider for testing.
1655 * @hide
1656 */
1657 public void attachInfoForTesting(Context context, ProviderInfo info) {
1658 attachInfo(context, info, true);
1659 }
1660
1661 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 * After being instantiated, this is called to tell the content provider
1663 * about itself.
1664 *
1665 * @param context The context this provider is running in
1666 * @param info Registered information about this content provider
1667 */
1668 public void attachInfo(Context context, ProviderInfo info) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001669 attachInfo(context, info, false);
1670 }
1671
1672 private void attachInfo(Context context, ProviderInfo info, boolean testing) {
Dianne Hackborn334d9ae2013-02-26 15:02:06 -08001673 mNoPerms = testing;
1674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 /*
1676 * Only allow it to be set once, so after the content service gives
1677 * this to us clients can't change it.
1678 */
1679 if (mContext == null) {
1680 mContext = context;
Jeff Sharkey10cb3122013-09-17 15:18:43 -07001681 if (context != null) {
1682 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService(
1683 Context.APP_OPS_SERVICE);
1684 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001685 mMyUid = Process.myUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 if (info != null) {
1687 setReadPermission(info.readPermission);
1688 setWritePermission(info.writePermission);
Dianne Hackborn2af632f2009-07-08 14:56:37 -07001689 setPathPermissions(info.pathPermissions);
Dianne Hackbornb424b632010-08-18 15:59:05 -07001690 mExported = info.exported;
Amith Yamasania6f4d582014-08-07 17:58:39 -07001691 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0;
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001692 setAuthorities(info.authority);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 }
1694 ContentProvider.this.onCreate();
1695 }
1696 }
Fred Quintanace31b232009-05-04 16:01:15 -07001697
1698 /**
Dan Egnor17876aa2010-07-28 12:28:04 -07001699 * Override this to handle requests to perform a batch of operations, or the
1700 * default implementation will iterate over the operations and call
1701 * {@link ContentProviderOperation#apply} on each of them.
1702 * If all calls to {@link ContentProviderOperation#apply} succeed
1703 * then a {@link ContentProviderResult} array with as many
1704 * elements as there were operations will be returned. If any of the calls
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001705 * fail, it is up to the implementation how many of the others take effect.
1706 * This method can be called from multiple threads, as described in
Scott Main7aee61f2011-02-08 11:25:01 -08001707 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes
1708 * and Threads</a>.
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001709 *
Fred Quintanace31b232009-05-04 16:01:15 -07001710 * @param operations the operations to apply
1711 * @return the results of the applications
Dan Egnor6fcc0f0732010-07-27 16:32:17 -07001712 * @throws OperationApplicationException thrown if any operation fails.
1713 * @see ContentProviderOperation#apply
Fred Quintanace31b232009-05-04 16:01:15 -07001714 */
Fred Quintana03d94902009-05-22 14:23:31 -07001715 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
Fred Quintanace31b232009-05-04 16:01:15 -07001716 throws OperationApplicationException {
Fred Quintana03d94902009-05-22 14:23:31 -07001717 final int numOperations = operations.size();
1718 final ContentProviderResult[] results = new ContentProviderResult[numOperations];
1719 for (int i = 0; i < numOperations; i++) {
1720 results[i] = operations.get(i).apply(this, results, i);
Fred Quintanace31b232009-05-04 16:01:15 -07001721 }
1722 return results;
1723 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001724
1725 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001726 * Call a provider-defined method. This can be used to implement
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001727 * interfaces that are cheaper and/or unnatural for a table-like
1728 * model.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001729 *
Dianne Hackborn5d122d92013-03-12 18:37:07 -07001730 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking
1731 * on this entry into the content provider besides the basic ability for the application
1732 * to get access to the provider at all. For example, it has no idea whether the call
1733 * being executed may read or write data in the provider, so can't enforce those
1734 * individual permissions. Any implementation of this method <strong>must</strong>
1735 * do its own permission checks on incoming calls to make sure they are allowed.</p>
1736 *
Christopher Tate2bc6eb82013-01-03 12:04:08 -08001737 * @param method method name to call. Opaque to framework, but should not be {@code null}.
1738 * @param arg provider-defined String argument. May be {@code null}.
1739 * @param extras provider-defined Bundle argument. May be {@code null}.
1740 * @return provider-defined return value. May be {@code null}, which is also
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001741 * the default for providers which don't implement any call methods.
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001742 */
Brad Fitzpatrick534c84c2011-01-12 14:06:30 -08001743 public Bundle call(String method, String arg, Bundle extras) {
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001744 return null;
1745 }
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001746
1747 /**
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001748 * Implement this to shut down the ContentProvider instance. You can then
1749 * invoke this method in unit tests.
1750 *
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001751 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001752 * Android normally handles ContentProvider startup and shutdown
1753 * automatically. You do not need to start up or shut down a
1754 * ContentProvider. When you invoke a test method on a ContentProvider,
1755 * however, a ContentProvider instance is started and keeps running after
1756 * the test finishes, even if a succeeding test instantiates another
1757 * ContentProvider. A conflict develops because the two instances are
1758 * usually running against the same underlying data source (for example, an
1759 * sqlite database).
1760 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001761 * <p>
Manuel Roman2c96a0c2010-08-05 16:39:49 -07001762 * Implementing shutDown() avoids this conflict by providing a way to
1763 * terminate the ContentProvider. This method can also prevent memory leaks
1764 * from multiple instantiations of the ContentProvider, and it can ensure
1765 * unit test isolation by allowing you to completely clean up the test
1766 * fixture before moving on to the next test.
1767 * </p>
Vasu Nori0c9e14a2010-08-04 13:31:48 -07001768 */
1769 public void shutdown() {
1770 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " +
1771 "connections are gracefully shutdown");
1772 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08001773
1774 /**
1775 * Print the Provider's state into the given stream. This gets invoked if
Jeff Sharkey5554b702012-04-11 18:30:51 -07001776 * you run "adb shell dumpsys activity provider &lt;provider_component_name&gt;".
Marco Nelissen18cb2872011-11-15 11:19:53 -08001777 *
Marco Nelissen18cb2872011-11-15 11:19:53 -08001778 * @param fd The raw file descriptor that the dump is being sent to.
1779 * @param writer The PrintWriter to which you should dump your state. This will be
1780 * closed for you after you return.
1781 * @param args additional arguments to the dump request.
Marco Nelissen18cb2872011-11-15 11:19:53 -08001782 */
1783 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1784 writer.println("nothing to dump");
1785 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001786
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001787 /** @hide */
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001788 private void validateIncomingUri(Uri uri) throws SecurityException {
1789 String auth = uri.getAuthority();
1790 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001791 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
1792 throw new SecurityException("trying to query a ContentProvider in user "
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001793 + mContext.getUserId() + " with a uri belonging to user " + userId);
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001794 }
Nicolas Prevotf300bab2014-08-07 19:23:17 +01001795 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
1796 String message = "The authority of the uri " + uri + " does not match the one of the "
1797 + "contentProvider: ";
1798 if (mAuthority != null) {
1799 message += mAuthority;
1800 } else {
1801 message += mAuthorities;
1802 }
1803 throw new SecurityException(message);
1804 }
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001805 }
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001806
1807 /** @hide */
1808 public static int getUserIdFromAuthority(String auth, int defaultUserId) {
1809 if (auth == null) return defaultUserId;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001810 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001811 if (end == -1) return defaultUserId;
1812 String userIdString = auth.substring(0, end);
1813 try {
1814 return Integer.parseInt(userIdString);
1815 } catch (NumberFormatException e) {
1816 Log.w(TAG, "Error parsing userId.", e);
1817 return UserHandle.USER_NULL;
1818 }
1819 }
1820
1821 /** @hide */
1822 public static int getUserIdFromAuthority(String auth) {
1823 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
1824 }
1825
1826 /** @hide */
1827 public static int getUserIdFromUri(Uri uri, int defaultUserId) {
1828 if (uri == null) return defaultUserId;
1829 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId);
1830 }
1831
1832 /** @hide */
1833 public static int getUserIdFromUri(Uri uri) {
1834 return getUserIdFromUri(uri, UserHandle.USER_CURRENT);
1835 }
1836
1837 /**
1838 * Removes userId part from authority string. Expects format:
1839 * userId@some.authority
1840 * If there is no userId in the authority, it symply returns the argument
1841 * @hide
1842 */
1843 public static String getAuthorityWithoutUserId(String auth) {
1844 if (auth == null) return null;
Nicolas Prevot504d78e2014-06-26 10:07:33 +01001845 int end = auth.lastIndexOf('@');
Nicolas Prevotd85fc722014-04-16 19:52:08 +01001846 return auth.substring(end+1);
1847 }
1848
1849 /** @hide */
1850 public static Uri getUriWithoutUserId(Uri uri) {
1851 if (uri == null) return null;
1852 Uri.Builder builder = uri.buildUpon();
1853 builder.authority(getAuthorityWithoutUserId(uri.getAuthority()));
1854 return builder.build();
1855 }
1856
1857 /** @hide */
1858 public static boolean uriHasUserId(Uri uri) {
1859 if (uri == null) return false;
1860 return !TextUtils.isEmpty(uri.getUserInfo());
1861 }
1862
1863 /** @hide */
1864 public static Uri maybeAddUserId(Uri uri, int userId) {
1865 if (uri == null) return null;
1866 if (userId != UserHandle.USER_CURRENT
1867 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1868 if (!uriHasUserId(uri)) {
1869 //We don't add the user Id if there's already one
1870 Uri.Builder builder = uri.buildUpon();
1871 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
1872 return builder.build();
1873 }
1874 }
1875 return uri;
1876 }
Brad Fitzpatrick1877d012010-03-04 17:48:13 -08001877}