1 /* 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 17 package android.content; 18 19 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 20 import static android.Manifest.permission.INTERACT_ACROSS_USERS; 21 22 import android.app.AppOpsManager; 23 import android.content.pm.PathPermission; 24 import android.content.pm.ProviderInfo; 25 import android.content.res.AssetFileDescriptor; 26 import android.content.res.Configuration; 27 import android.database.Cursor; 28 import android.database.SQLException; 29 import android.net.Uri; 30 import android.os.AsyncTask; 31 import android.os.Binder; 32 import android.os.Bundle; 33 import android.os.CancellationSignal; 34 import android.os.ICancellationSignal; 35 import android.os.OperationCanceledException; 36 import android.os.ParcelFileDescriptor; 37 import android.os.Process; 38 import android.os.UserHandle; 39 import android.util.Log; 40 import android.text.TextUtils; 41 42 import java.io.File; 43 import java.io.FileDescriptor; 44 import java.io.FileNotFoundException; 45 import java.io.IOException; 46 import java.io.PrintWriter; 47 import java.util.ArrayList; 48 49 /** 50 * Content providers are one of the primary building blocks of Android applications, providing 51 * content to applications. They encapsulate data and provide it to applications through the single 52 * {@link ContentResolver} interface. A content provider is only required if you need to share 53 * data between multiple applications. For example, the contacts data is used by multiple 54 * applications and must be stored in a content provider. If you don't need to share data amongst 55 * multiple applications you can use a database directly via 56 * {@link android.database.sqlite.SQLiteDatabase}. 57 * 58 * <p>When a request is made via 59 * a {@link ContentResolver} the system inspects the authority of the given URI and passes the 60 * request to the content provider registered with the authority. The content provider can interpret 61 * the rest of the URI however it wants. The {@link UriMatcher} class is helpful for parsing 62 * URIs.</p> 63 * 64 * <p>The primary methods that need to be implemented are: 65 * <ul> 66 * <li>{@link #onCreate} which is called to initialize the provider</li> 67 * <li>{@link #query} which returns data to the caller</li> 68 * <li>{@link #insert} which inserts new data into the content provider</li> 69 * <li>{@link #update} which updates existing data in the content provider</li> 70 * <li>{@link #delete} which deletes data from the content provider</li> 71 * <li>{@link #getType} which returns the MIME type of data in the content provider</li> 72 * </ul></p> 73 * 74 * <p class="caution">Data access methods (such as {@link #insert} and 75 * {@link #update}) may be called from many threads at once, and must be thread-safe. 76 * Other methods (such as {@link #onCreate}) are only called from the application 77 * main thread, and must avoid performing lengthy operations. See the method 78 * descriptions for their expected thread behavior.</p> 79 * 80 * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate 81 * ContentProvider instance, so subclasses don't have to worry about the details of 82 * cross-process calls.</p> 83 * 84 * <div class="special reference"> 85 * <h3>Developer Guides</h3> 86 * <p>For more information about using content providers, read the 87 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a> 88 * developer guide.</p> 89 */ 90 public abstract class ContentProvider implements ComponentCallbacks2 { 91 private static final String TAG = "ContentProvider"; 92 93 /* 94 * Note: if you add methods to ContentProvider, you must add similar methods to 95 * MockContentProvider. 96 */ 97 98 private Context mContext = null; 99 private int mMyUid; 100 101 // Since most Providers have only one authority, we keep both a String and a String[] to improve 102 // performance. 103 private String mAuthority; 104 private String[] mAuthorities; 105 private String mReadPermission; 106 private String mWritePermission; 107 private PathPermission[] mPathPermissions; 108 private boolean mExported; 109 private boolean mNoPerms; 110 private boolean mSingleUser; 111 112 private final ThreadLocal<String> mCallingPackage = new ThreadLocal<String>(); 113 114 private Transport mTransport = new Transport(); 115 116 /** 117 * Construct a ContentProvider instance. Content providers must be 118 * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared 119 * in the manifest</a>, accessed with {@link ContentResolver}, and created 120 * automatically by the system, so applications usually do not create 121 * ContentProvider instances directly. 122 * 123 * <p>At construction time, the object is uninitialized, and most fields and 124 * methods are unavailable. Subclasses should initialize themselves in 125 * {@link #onCreate}, not the constructor. 126 * 127 * <p>Content providers are created on the application main thread at 128 * application launch time. The constructor must not perform lengthy 129 * operations, or application startup will be delayed. 130 */ ContentProvider()131 public ContentProvider() { 132 } 133 134 /** 135 * Constructor just for mocking. 136 * 137 * @param context A Context object which should be some mock instance (like the 138 * instance of {@link android.test.mock.MockContext}). 139 * @param readPermission The read permision you want this instance should have in the 140 * test, which is available via {@link #getReadPermission()}. 141 * @param writePermission The write permission you want this instance should have 142 * in the test, which is available via {@link #getWritePermission()}. 143 * @param pathPermissions The PathPermissions you want this instance should have 144 * in the test, which is available via {@link #getPathPermissions()}. 145 * @hide 146 */ ContentProvider( Context context, String readPermission, String writePermission, PathPermission[] pathPermissions)147 public ContentProvider( 148 Context context, 149 String readPermission, 150 String writePermission, 151 PathPermission[] pathPermissions) { 152 mContext = context; 153 mReadPermission = readPermission; 154 mWritePermission = writePermission; 155 mPathPermissions = pathPermissions; 156 } 157 158 /** 159 * Given an IContentProvider, try to coerce it back to the real 160 * ContentProvider object if it is running in the local process. This can 161 * be used if you know you are running in the same process as a provider, 162 * and want to get direct access to its implementation details. Most 163 * clients should not nor have a reason to use it. 164 * 165 * @param abstractInterface The ContentProvider interface that is to be 166 * coerced. 167 * @return If the IContentProvider is non-{@code null} and local, returns its actual 168 * ContentProvider instance. Otherwise returns {@code null}. 169 * @hide 170 */ coerceToLocalContentProvider( IContentProvider abstractInterface)171 public static ContentProvider coerceToLocalContentProvider( 172 IContentProvider abstractInterface) { 173 if (abstractInterface instanceof Transport) { 174 return ((Transport)abstractInterface).getContentProvider(); 175 } 176 return null; 177 } 178 179 /** 180 * Binder object that deals with remoting. 181 * 182 * @hide 183 */ 184 class Transport extends ContentProviderNative { 185 AppOpsManager mAppOpsManager = null; 186 int mReadOp = AppOpsManager.OP_NONE; 187 int mWriteOp = AppOpsManager.OP_NONE; 188 getContentProvider()189 ContentProvider getContentProvider() { 190 return ContentProvider.this; 191 } 192 193 @Override getProviderName()194 public String getProviderName() { 195 return getContentProvider().getClass().getName(); 196 } 197 198 @Override query(String callingPkg, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, ICancellationSignal cancellationSignal)199 public Cursor query(String callingPkg, Uri uri, String[] projection, 200 String selection, String[] selectionArgs, String sortOrder, 201 ICancellationSignal cancellationSignal) { 202 validateIncomingUri(uri); 203 uri = getUriWithoutUserId(uri); 204 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) { 205 return rejectQuery(uri, projection, selection, selectionArgs, sortOrder, 206 CancellationSignal.fromTransport(cancellationSignal)); 207 } 208 final String original = setCallingPackage(callingPkg); 209 try { 210 return ContentProvider.this.query( 211 uri, projection, selection, selectionArgs, sortOrder, 212 CancellationSignal.fromTransport(cancellationSignal)); 213 } finally { 214 setCallingPackage(original); 215 } 216 } 217 218 @Override getType(Uri uri)219 public String getType(Uri uri) { 220 validateIncomingUri(uri); 221 uri = getUriWithoutUserId(uri); 222 return ContentProvider.this.getType(uri); 223 } 224 225 @Override insert(String callingPkg, Uri uri, ContentValues initialValues)226 public Uri insert(String callingPkg, Uri uri, ContentValues initialValues) { 227 validateIncomingUri(uri); 228 int userId = getUserIdFromUri(uri); 229 uri = getUriWithoutUserId(uri); 230 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) { 231 return rejectInsert(uri, initialValues); 232 } 233 final String original = setCallingPackage(callingPkg); 234 try { 235 return maybeAddUserId(ContentProvider.this.insert(uri, initialValues), userId); 236 } finally { 237 setCallingPackage(original); 238 } 239 } 240 241 @Override bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues)242 public int bulkInsert(String callingPkg, Uri uri, ContentValues[] initialValues) { 243 validateIncomingUri(uri); 244 uri = getUriWithoutUserId(uri); 245 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) { 246 return 0; 247 } 248 final String original = setCallingPackage(callingPkg); 249 try { 250 return ContentProvider.this.bulkInsert(uri, initialValues); 251 } finally { 252 setCallingPackage(original); 253 } 254 } 255 256 @Override applyBatch(String callingPkg, ArrayList<ContentProviderOperation> operations)257 public ContentProviderResult[] applyBatch(String callingPkg, 258 ArrayList<ContentProviderOperation> operations) 259 throws OperationApplicationException { 260 int numOperations = operations.size(); 261 final int[] userIds = new int[numOperations]; 262 for (int i = 0; i < numOperations; i++) { 263 ContentProviderOperation operation = operations.get(i); 264 Uri uri = operation.getUri(); 265 validateIncomingUri(uri); 266 userIds[i] = getUserIdFromUri(uri); 267 if (userIds[i] != UserHandle.USER_CURRENT) { 268 // Removing the user id from the uri. 269 operation = new ContentProviderOperation(operation, true); 270 operations.set(i, operation); 271 } 272 if (operation.isReadOperation()) { 273 if (enforceReadPermission(callingPkg, uri) 274 != AppOpsManager.MODE_ALLOWED) { 275 throw new OperationApplicationException("App op not allowed", 0); 276 } 277 } 278 if (operation.isWriteOperation()) { 279 if (enforceWritePermission(callingPkg, uri) 280 != AppOpsManager.MODE_ALLOWED) { 281 throw new OperationApplicationException("App op not allowed", 0); 282 } 283 } 284 } 285 final String original = setCallingPackage(callingPkg); 286 try { 287 ContentProviderResult[] results = ContentProvider.this.applyBatch(operations); 288 for (int i = 0; i < results.length ; i++) { 289 if (userIds[i] != UserHandle.USER_CURRENT) { 290 // Adding the userId to the uri. 291 results[i] = new ContentProviderResult(results[i], userIds[i]); 292 } 293 } 294 return results; 295 } finally { 296 setCallingPackage(original); 297 } 298 } 299 300 @Override delete(String callingPkg, Uri uri, String selection, String[] selectionArgs)301 public int delete(String callingPkg, Uri uri, String selection, String[] selectionArgs) { 302 validateIncomingUri(uri); 303 uri = getUriWithoutUserId(uri); 304 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) { 305 return 0; 306 } 307 final String original = setCallingPackage(callingPkg); 308 try { 309 return ContentProvider.this.delete(uri, selection, selectionArgs); 310 } finally { 311 setCallingPackage(original); 312 } 313 } 314 315 @Override update(String callingPkg, Uri uri, ContentValues values, String selection, String[] selectionArgs)316 public int update(String callingPkg, Uri uri, ContentValues values, String selection, 317 String[] selectionArgs) { 318 validateIncomingUri(uri); 319 uri = getUriWithoutUserId(uri); 320 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) { 321 return 0; 322 } 323 final String original = setCallingPackage(callingPkg); 324 try { 325 return ContentProvider.this.update(uri, values, selection, selectionArgs); 326 } finally { 327 setCallingPackage(original); 328 } 329 } 330 331 @Override openFile( String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)332 public ParcelFileDescriptor openFile( 333 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal) 334 throws FileNotFoundException { 335 validateIncomingUri(uri); 336 uri = getUriWithoutUserId(uri); 337 enforceFilePermission(callingPkg, uri, mode); 338 final String original = setCallingPackage(callingPkg); 339 try { 340 return ContentProvider.this.openFile( 341 uri, mode, CancellationSignal.fromTransport(cancellationSignal)); 342 } finally { 343 setCallingPackage(original); 344 } 345 } 346 347 @Override openAssetFile( String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal)348 public AssetFileDescriptor openAssetFile( 349 String callingPkg, Uri uri, String mode, ICancellationSignal cancellationSignal) 350 throws FileNotFoundException { 351 validateIncomingUri(uri); 352 uri = getUriWithoutUserId(uri); 353 enforceFilePermission(callingPkg, uri, mode); 354 final String original = setCallingPackage(callingPkg); 355 try { 356 return ContentProvider.this.openAssetFile( 357 uri, mode, CancellationSignal.fromTransport(cancellationSignal)); 358 } finally { 359 setCallingPackage(original); 360 } 361 } 362 363 @Override call(String callingPkg, String method, String arg, Bundle extras)364 public Bundle call(String callingPkg, String method, String arg, Bundle extras) { 365 final String original = setCallingPackage(callingPkg); 366 try { 367 return ContentProvider.this.call(method, arg, extras); 368 } finally { 369 setCallingPackage(original); 370 } 371 } 372 373 @Override getStreamTypes(Uri uri, String mimeTypeFilter)374 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) { 375 validateIncomingUri(uri); 376 uri = getUriWithoutUserId(uri); 377 return ContentProvider.this.getStreamTypes(uri, mimeTypeFilter); 378 } 379 380 @Override openTypedAssetFile(String callingPkg, Uri uri, String mimeType, Bundle opts, ICancellationSignal cancellationSignal)381 public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri uri, String mimeType, 382 Bundle opts, ICancellationSignal cancellationSignal) throws FileNotFoundException { 383 validateIncomingUri(uri); 384 uri = getUriWithoutUserId(uri); 385 enforceFilePermission(callingPkg, uri, "r"); 386 final String original = setCallingPackage(callingPkg); 387 try { 388 return ContentProvider.this.openTypedAssetFile( 389 uri, mimeType, opts, CancellationSignal.fromTransport(cancellationSignal)); 390 } finally { 391 setCallingPackage(original); 392 } 393 } 394 395 @Override createCancellationSignal()396 public ICancellationSignal createCancellationSignal() { 397 return CancellationSignal.createTransport(); 398 } 399 400 @Override canonicalize(String callingPkg, Uri uri)401 public Uri canonicalize(String callingPkg, Uri uri) { 402 validateIncomingUri(uri); 403 int userId = getUserIdFromUri(uri); 404 uri = getUriWithoutUserId(uri); 405 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) { 406 return null; 407 } 408 final String original = setCallingPackage(callingPkg); 409 try { 410 return maybeAddUserId(ContentProvider.this.canonicalize(uri), userId); 411 } finally { 412 setCallingPackage(original); 413 } 414 } 415 416 @Override uncanonicalize(String callingPkg, Uri uri)417 public Uri uncanonicalize(String callingPkg, Uri uri) { 418 validateIncomingUri(uri); 419 int userId = getUserIdFromUri(uri); 420 uri = getUriWithoutUserId(uri); 421 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) { 422 return null; 423 } 424 final String original = setCallingPackage(callingPkg); 425 try { 426 return maybeAddUserId(ContentProvider.this.uncanonicalize(uri), userId); 427 } finally { 428 setCallingPackage(original); 429 } 430 } 431 enforceFilePermission(String callingPkg, Uri uri, String mode)432 private void enforceFilePermission(String callingPkg, Uri uri, String mode) 433 throws FileNotFoundException, SecurityException { 434 if (mode != null && mode.indexOf('w') != -1) { 435 if (enforceWritePermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) { 436 throw new FileNotFoundException("App op not allowed"); 437 } 438 } else { 439 if (enforceReadPermission(callingPkg, uri) != AppOpsManager.MODE_ALLOWED) { 440 throw new FileNotFoundException("App op not allowed"); 441 } 442 } 443 } 444 enforceReadPermission(String callingPkg, Uri uri)445 private int enforceReadPermission(String callingPkg, Uri uri) throws SecurityException { 446 enforceReadPermissionInner(uri); 447 if (mReadOp != AppOpsManager.OP_NONE) { 448 return mAppOpsManager.noteOp(mReadOp, Binder.getCallingUid(), callingPkg); 449 } 450 return AppOpsManager.MODE_ALLOWED; 451 } 452 enforceWritePermission(String callingPkg, Uri uri)453 private int enforceWritePermission(String callingPkg, Uri uri) throws SecurityException { 454 enforceWritePermissionInner(uri); 455 if (mWriteOp != AppOpsManager.OP_NONE) { 456 return mAppOpsManager.noteOp(mWriteOp, Binder.getCallingUid(), callingPkg); 457 } 458 return AppOpsManager.MODE_ALLOWED; 459 } 460 } 461 checkUser(int pid, int uid, Context context)462 boolean checkUser(int pid, int uid, Context context) { 463 return UserHandle.getUserId(uid) == context.getUserId() 464 || mSingleUser 465 || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid) 466 == PERMISSION_GRANTED; 467 } 468 469 /** {@hide} */ enforceReadPermissionInner(Uri uri)470 protected void enforceReadPermissionInner(Uri uri) throws SecurityException { 471 final Context context = getContext(); 472 final int pid = Binder.getCallingPid(); 473 final int uid = Binder.getCallingUid(); 474 String missingPerm = null; 475 476 if (UserHandle.isSameApp(uid, mMyUid)) { 477 return; 478 } 479 480 if (mExported && checkUser(pid, uid, context)) { 481 final String componentPerm = getReadPermission(); 482 if (componentPerm != null) { 483 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) { 484 return; 485 } else { 486 missingPerm = componentPerm; 487 } 488 } 489 490 // track if unprotected read is allowed; any denied 491 // <path-permission> below removes this ability 492 boolean allowDefaultRead = (componentPerm == null); 493 494 final PathPermission[] pps = getPathPermissions(); 495 if (pps != null) { 496 final String path = uri.getPath(); 497 for (PathPermission pp : pps) { 498 final String pathPerm = pp.getReadPermission(); 499 if (pathPerm != null && pp.match(path)) { 500 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) { 501 return; 502 } else { 503 // any denied <path-permission> means we lose 504 // default <provider> access. 505 allowDefaultRead = false; 506 missingPerm = pathPerm; 507 } 508 } 509 } 510 } 511 512 // if we passed <path-permission> checks above, and no default 513 // <provider> permission, then allow access. 514 if (allowDefaultRead) return; 515 } 516 517 // last chance, check against any uri grants 518 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_READ_URI_PERMISSION) 519 == PERMISSION_GRANTED) { 520 return; 521 } 522 523 final String failReason = mExported 524 ? " requires " + missingPerm + ", or grantUriPermission()" 525 : " requires the provider be exported, or grantUriPermission()"; 526 throw new SecurityException("Permission Denial: reading " 527 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid 528 + ", uid=" + uid + failReason); 529 } 530 531 /** {@hide} */ enforceWritePermissionInner(Uri uri)532 protected void enforceWritePermissionInner(Uri uri) throws SecurityException { 533 final Context context = getContext(); 534 final int pid = Binder.getCallingPid(); 535 final int uid = Binder.getCallingUid(); 536 String missingPerm = null; 537 538 if (UserHandle.isSameApp(uid, mMyUid)) { 539 return; 540 } 541 542 if (mExported && checkUser(pid, uid, context)) { 543 final String componentPerm = getWritePermission(); 544 if (componentPerm != null) { 545 if (context.checkPermission(componentPerm, pid, uid) == PERMISSION_GRANTED) { 546 return; 547 } else { 548 missingPerm = componentPerm; 549 } 550 } 551 552 // track if unprotected write is allowed; any denied 553 // <path-permission> below removes this ability 554 boolean allowDefaultWrite = (componentPerm == null); 555 556 final PathPermission[] pps = getPathPermissions(); 557 if (pps != null) { 558 final String path = uri.getPath(); 559 for (PathPermission pp : pps) { 560 final String pathPerm = pp.getWritePermission(); 561 if (pathPerm != null && pp.match(path)) { 562 if (context.checkPermission(pathPerm, pid, uid) == PERMISSION_GRANTED) { 563 return; 564 } else { 565 // any denied <path-permission> means we lose 566 // default <provider> access. 567 allowDefaultWrite = false; 568 missingPerm = pathPerm; 569 } 570 } 571 } 572 } 573 574 // if we passed <path-permission> checks above, and no default 575 // <provider> permission, then allow access. 576 if (allowDefaultWrite) return; 577 } 578 579 // last chance, check against any uri grants 580 if (context.checkUriPermission(uri, pid, uid, Intent.FLAG_GRANT_WRITE_URI_PERMISSION) 581 == PERMISSION_GRANTED) { 582 return; 583 } 584 585 final String failReason = mExported 586 ? " requires " + missingPerm + ", or grantUriPermission()" 587 : " requires the provider be exported, or grantUriPermission()"; 588 throw new SecurityException("Permission Denial: writing " 589 + ContentProvider.this.getClass().getName() + " uri " + uri + " from pid=" + pid 590 + ", uid=" + uid + failReason); 591 } 592 593 /** 594 * Retrieves the Context this provider is running in. Only available once 595 * {@link #onCreate} has been called -- this will return {@code null} in the 596 * constructor. 597 */ getContext()598 public final Context getContext() { 599 return mContext; 600 } 601 602 /** 603 * Set the calling package, returning the current value (or {@code null}) 604 * which can be used later to restore the previous state. 605 */ setCallingPackage(String callingPackage)606 private String setCallingPackage(String callingPackage) { 607 final String original = mCallingPackage.get(); 608 mCallingPackage.set(callingPackage); 609 return original; 610 } 611 612 /** 613 * Return the package name of the caller that initiated the request being 614 * processed on the current thread. The returned package will have been 615 * verified to belong to the calling UID. Returns {@code null} if not 616 * currently processing a request. 617 * <p> 618 * This will always return {@code null} when processing 619 * {@link #getType(Uri)} or {@link #getStreamTypes(Uri, String)} requests. 620 * 621 * @see Binder#getCallingUid() 622 * @see Context#grantUriPermission(String, Uri, int) 623 * @throws SecurityException if the calling package doesn't belong to the 624 * calling UID. 625 */ getCallingPackage()626 public final String getCallingPackage() { 627 final String pkg = mCallingPackage.get(); 628 if (pkg != null) { 629 mTransport.mAppOpsManager.checkPackage(Binder.getCallingUid(), pkg); 630 } 631 return pkg; 632 } 633 634 /** 635 * Change the authorities of the ContentProvider. 636 * This is normally set for you from its manifest information when the provider is first 637 * created. 638 * @hide 639 * @param authorities the semi-colon separated authorities of the ContentProvider. 640 */ setAuthorities(String authorities)641 protected final void setAuthorities(String authorities) { 642 if (authorities != null) { 643 if (authorities.indexOf(';') == -1) { 644 mAuthority = authorities; 645 mAuthorities = null; 646 } else { 647 mAuthority = null; 648 mAuthorities = authorities.split(";"); 649 } 650 } 651 } 652 653 /** @hide */ matchesOurAuthorities(String authority)654 protected final boolean matchesOurAuthorities(String authority) { 655 if (mAuthority != null) { 656 return mAuthority.equals(authority); 657 } 658 if (mAuthorities != null) { 659 int length = mAuthorities.length; 660 for (int i = 0; i < length; i++) { 661 if (mAuthorities[i].equals(authority)) return true; 662 } 663 } 664 return false; 665 } 666 667 668 /** 669 * Change the permission required to read data from the content 670 * provider. This is normally set for you from its manifest information 671 * when the provider is first created. 672 * 673 * @param permission Name of the permission required for read-only access. 674 */ setReadPermission(String permission)675 protected final void setReadPermission(String permission) { 676 mReadPermission = permission; 677 } 678 679 /** 680 * Return the name of the permission required for read-only access to 681 * this content provider. This method can be called from multiple 682 * threads, as described in 683 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes 684 * and Threads</a>. 685 */ getReadPermission()686 public final String getReadPermission() { 687 return mReadPermission; 688 } 689 690 /** 691 * Change the permission required to read and write data in the content 692 * provider. This is normally set for you from its manifest information 693 * when the provider is first created. 694 * 695 * @param permission Name of the permission required for read/write access. 696 */ setWritePermission(String permission)697 protected final void setWritePermission(String permission) { 698 mWritePermission = permission; 699 } 700 701 /** 702 * Return the name of the permission required for read/write access to 703 * this content provider. This method can be called from multiple 704 * threads, as described in 705 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes 706 * and Threads</a>. 707 */ getWritePermission()708 public final String getWritePermission() { 709 return mWritePermission; 710 } 711 712 /** 713 * Change the path-based permission required to read and/or write data in 714 * the content provider. This is normally set for you from its manifest 715 * information when the provider is first created. 716 * 717 * @param permissions Array of path permission descriptions. 718 */ setPathPermissions(PathPermission[] permissions)719 protected final void setPathPermissions(PathPermission[] permissions) { 720 mPathPermissions = permissions; 721 } 722 723 /** 724 * Return the path-based permissions required for read and/or write access to 725 * this content provider. This method can be called from multiple 726 * threads, as described in 727 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes 728 * and Threads</a>. 729 */ getPathPermissions()730 public final PathPermission[] getPathPermissions() { 731 return mPathPermissions; 732 } 733 734 /** @hide */ setAppOps(int readOp, int writeOp)735 public final void setAppOps(int readOp, int writeOp) { 736 if (!mNoPerms) { 737 mTransport.mReadOp = readOp; 738 mTransport.mWriteOp = writeOp; 739 } 740 } 741 742 /** @hide */ getAppOpsManager()743 public AppOpsManager getAppOpsManager() { 744 return mTransport.mAppOpsManager; 745 } 746 747 /** 748 * Implement this to initialize your content provider on startup. 749 * This method is called for all registered content providers on the 750 * application main thread at application launch time. It must not perform 751 * lengthy operations, or application startup will be delayed. 752 * 753 * <p>You should defer nontrivial initialization (such as opening, 754 * upgrading, and scanning databases) until the content provider is used 755 * (via {@link #query}, {@link #insert}, etc). Deferred initialization 756 * keeps application startup fast, avoids unnecessary work if the provider 757 * turns out not to be needed, and stops database errors (such as a full 758 * disk) from halting application launch. 759 * 760 * <p>If you use SQLite, {@link android.database.sqlite.SQLiteOpenHelper} 761 * is a helpful utility class that makes it easy to manage databases, 762 * and will automatically defer opening until first use. If you do use 763 * SQLiteOpenHelper, make sure to avoid calling 764 * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or 765 * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase} 766 * from this method. (Instead, override 767 * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the 768 * database when it is first opened.) 769 * 770 * @return true if the provider was successfully loaded, false otherwise 771 */ onCreate()772 public abstract boolean onCreate(); 773 774 /** 775 * {@inheritDoc} 776 * This method is always called on the application main thread, and must 777 * not perform lengthy operations. 778 * 779 * <p>The default content provider implementation does nothing. 780 * Override this method to take appropriate action. 781 * (Content providers do not usually care about things like screen 782 * orientation, but may want to know about locale changes.) 783 */ onConfigurationChanged(Configuration newConfig)784 public void onConfigurationChanged(Configuration newConfig) { 785 } 786 787 /** 788 * {@inheritDoc} 789 * This method is always called on the application main thread, and must 790 * not perform lengthy operations. 791 * 792 * <p>The default content provider implementation does nothing. 793 * Subclasses may override this method to take appropriate action. 794 */ onLowMemory()795 public void onLowMemory() { 796 } 797 onTrimMemory(int level)798 public void onTrimMemory(int level) { 799 } 800 801 /** 802 * @hide 803 * Implementation when a caller has performed a query on the content 804 * provider, but that call has been rejected for the operation given 805 * to {@link #setAppOps(int, int)}. The default implementation 806 * rewrites the <var>selection</var> argument to include a condition 807 * that is never true (so will always result in an empty cursor) 808 * and calls through to {@link #query(android.net.Uri, String[], String, String[], 809 * String, android.os.CancellationSignal)} with that. 810 */ rejectQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, CancellationSignal cancellationSignal)811 public Cursor rejectQuery(Uri uri, String[] projection, 812 String selection, String[] selectionArgs, String sortOrder, 813 CancellationSignal cancellationSignal) { 814 // The read is not allowed... to fake it out, we replace the given 815 // selection statement with a dummy one that will always be false. 816 // This way we will get a cursor back that has the correct structure 817 // but contains no rows. 818 if (selection == null || selection.isEmpty()) { 819 selection = "'A' = 'B'"; 820 } else { 821 selection = "'A' = 'B' AND (" + selection + ")"; 822 } 823 return query(uri, projection, selection, selectionArgs, sortOrder, cancellationSignal); 824 } 825 826 /** 827 * Implement this to handle query requests from clients. 828 * This method can be called from multiple threads, as described in 829 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes 830 * and Threads</a>. 831 * <p> 832 * Example client call:<p> 833 * <pre>// Request a specific record. 834 * Cursor managedCursor = managedQuery( 835 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2), 836 projection, // Which columns to return. 837 null, // WHERE clause. 838 null, // WHERE clause value substitution 839 People.NAME + " ASC"); // Sort order.</pre> 840 * Example implementation:<p> 841 * <pre>// SQLiteQueryBuilder is a helper class that creates the 842 // proper SQL syntax for us. 843 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder(); 844 845 // Set the table we're querying. 846 qBuilder.setTables(DATABASE_TABLE_NAME); 847 848 // If the query ends in a specific record number, we're 849 // being asked for a specific record, so set the 850 // WHERE clause in our query. 851 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){ 852 qBuilder.appendWhere("_id=" + uri.getPathLeafId()); 853 } 854 855 // Make the query. 856 Cursor c = qBuilder.query(mDb, 857 projection, 858 selection, 859 selectionArgs, 860 groupBy, 861 having, 862 sortOrder); 863 c.setNotificationUri(getContext().getContentResolver(), uri); 864 return c;</pre> 865 * 866 * @param uri The URI to query. This will be the full URI sent by the client; 867 * if the client is requesting a specific record, the URI will end in a record number 868 * that the implementation should parse and add to a WHERE or HAVING clause, specifying 869 * that _id value. 870 * @param projection The list of columns to put into the cursor. If 871 * {@code null} all columns are included. 872 * @param selection A selection criteria to apply when filtering rows. 873 * If {@code null} then all rows are included. 874 * @param selectionArgs You may include ?s in selection, which will be replaced by 875 * the values from selectionArgs, in order that they appear in the selection. 876 * The values will be bound as Strings. 877 * @param sortOrder How the rows in the cursor should be sorted. 878 * If {@code null} then the provider is free to define the sort order. 879 * @return a Cursor or {@code null}. 880 */ query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)881 public abstract Cursor query(Uri uri, String[] projection, 882 String selection, String[] selectionArgs, String sortOrder); 883 884 /** 885 * Implement this to handle query requests from clients with support for cancellation. 886 * This method can be called from multiple threads, as described in 887 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes 888 * and Threads</a>. 889 * <p> 890 * Example client call:<p> 891 * <pre>// Request a specific record. 892 * Cursor managedCursor = managedQuery( 893 ContentUris.withAppendedId(Contacts.People.CONTENT_URI, 2), 894 projection, // Which columns to return. 895 null, // WHERE clause. 896 null, // WHERE clause value substitution 897 People.NAME + " ASC"); // Sort order.</pre> 898 * Example implementation:<p> 899 * <pre>// SQLiteQueryBuilder is a helper class that creates the 900 // proper SQL syntax for us. 901 SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder(); 902 903 // Set the table we're querying. 904 qBuilder.setTables(DATABASE_TABLE_NAME); 905 906 // If the query ends in a specific record number, we're 907 // being asked for a specific record, so set the 908 // WHERE clause in our query. 909 if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){ 910 qBuilder.appendWhere("_id=" + uri.getPathLeafId()); 911 } 912 913 // Make the query. 914 Cursor c = qBuilder.query(mDb, 915 projection, 916 selection, 917 selectionArgs, 918 groupBy, 919 having, 920 sortOrder); 921 c.setNotificationUri(getContext().getContentResolver(), uri); 922 return c;</pre> 923 * <p> 924 * If you implement this method then you must also implement the version of 925 * {@link #query(Uri, String[], String, String[], String)} that does not take a cancellation 926 * signal to ensure correct operation on older versions of the Android Framework in 927 * which the cancellation signal overload was not available. 928 * 929 * @param uri The URI to query. This will be the full URI sent by the client; 930 * if the client is requesting a specific record, the URI will end in a record number 931 * that the implementation should parse and add to a WHERE or HAVING clause, specifying 932 * that _id value. 933 * @param projection The list of columns to put into the cursor. If 934 * {@code null} all columns are included. 935 * @param selection A selection criteria to apply when filtering rows. 936 * If {@code null} then all rows are included. 937 * @param selectionArgs You may include ?s in selection, which will be replaced by 938 * the values from selectionArgs, in order that they appear in the selection. 939 * The values will be bound as Strings. 940 * @param sortOrder How the rows in the cursor should be sorted. 941 * If {@code null} then the provider is free to define the sort order. 942 * @param cancellationSignal A signal to cancel the operation in progress, or {@code null} if none. 943 * If the operation is canceled, then {@link OperationCanceledException} will be thrown 944 * when the query is executed. 945 * @return a Cursor or {@code null}. 946 */ query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, CancellationSignal cancellationSignal)947 public Cursor query(Uri uri, String[] projection, 948 String selection, String[] selectionArgs, String sortOrder, 949 CancellationSignal cancellationSignal) { 950 return query(uri, projection, selection, selectionArgs, sortOrder); 951 } 952 953 /** 954 * Implement this to handle requests for the MIME type of the data at the 955 * given URI. The returned MIME type should start with 956 * <code>vnd.android.cursor.item</code> for a single record, 957 * or <code>vnd.android.cursor.dir/</code> for multiple items. 958 * This method can be called from multiple threads, as described in 959 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes 960 * and Threads</a>. 961 * 962 * <p>Note that there are no permissions needed for an application to 963 * access this information; if your content provider requires read and/or 964 * write permissions, or is not exported, all applications can still call 965 * this method regardless of their access permissions. This allows them 966 * to retrieve the MIME type for a URI when dispatching intents. 967 * 968 * @param uri the URI to query. 969 * @return a MIME type string, or {@code null} if there is no type. 970 */ getType(Uri uri)971 public abstract String getType(Uri uri); 972 973 /** 974 * Implement this to support canonicalization of URIs that refer to your 975 * content provider. A canonical URI is one that can be transported across 976 * devices, backup/restore, and other contexts, and still be able to refer 977 * to the same data item. Typically this is implemented by adding query 978 * params to the URI allowing the content provider to verify that an incoming 979 * canonical URI references the same data as it was originally intended for and, 980 * if it doesn't, to find that data (if it exists) in the current environment. 981 * 982 * <p>For example, if the content provider holds people and a normal URI in it 983 * is created with a row index into that people database, the cananical representation 984 * may have an additional query param at the end which specifies the name of the 985 * person it is intended for. Later calls into the provider with that URI will look 986 * up the row of that URI's base index and, if it doesn't match or its entry's 987 * name doesn't match the name in the query param, perform a query on its database 988 * to find the correct row to operate on.</p> 989 * 990 * <p>If you implement support for canonical URIs, <b>all</b> incoming calls with 991 * URIs (including this one) must perform this verification and recovery of any 992 * canonical URIs they receive. In addition, you must also implement 993 * {@link #uncanonicalize} to strip the canonicalization of any of these URIs.</p> 994 * 995 * <p>The default implementation of this method returns null, indicating that 996 * canonical URIs are not supported.</p> 997 * 998 * @param url The Uri to canonicalize. 999 * 1000 * @return Return the canonical representation of <var>url</var>, or null if 1001 * canonicalization of that Uri is not supported. 1002 */ canonicalize(Uri url)1003 public Uri canonicalize(Uri url) { 1004 return null; 1005 } 1006 1007 /** 1008 * Remove canonicalization from canonical URIs previously returned by 1009 * {@link #canonicalize}. For example, if your implementation is to add 1010 * a query param to canonicalize a URI, this method can simply trip any 1011 * query params on the URI. The default implementation always returns the 1012 * same <var>url</var> that was passed in. 1013 * 1014 * @param url The Uri to remove any canonicalization from. 1015 * 1016 * @return Return the non-canonical representation of <var>url</var>, return 1017 * the <var>url</var> as-is if there is nothing to do, or return null if 1018 * the data identified by the canonical representation can not be found in 1019 * the current environment. 1020 */ uncanonicalize(Uri url)1021 public Uri uncanonicalize(Uri url) { 1022 return url; 1023 } 1024 1025 /** 1026 * @hide 1027 * Implementation when a caller has performed an insert on the content 1028 * provider, but that call has been rejected for the operation given 1029 * to {@link #setAppOps(int, int)}. The default implementation simply 1030 * returns a dummy URI that is the base URI with a 0 path element 1031 * appended. 1032 */ rejectInsert(Uri uri, ContentValues values)1033 public Uri rejectInsert(Uri uri, ContentValues values) { 1034 // If not allowed, we need to return some reasonable URI. Maybe the 1035 // content provider should be responsible for this, but for now we 1036 // will just return the base URI with a dummy '0' tagged on to it. 1037 // You shouldn't be able to read if you can't write, anyway, so it 1038 // shouldn't matter much what is returned. 1039 return uri.buildUpon().appendPath("0").build(); 1040 } 1041 1042 /** 1043 * Implement this to handle requests to insert a new row. 1044 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()} 1045 * after inserting. 1046 * This method can be called from multiple threads, as described in 1047 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes 1048 * and Threads</a>. 1049 * @param uri The content:// URI of the insertion request. This must not be {@code null}. 1050 * @param values A set of column_name/value pairs to add to the database. 1051 * This must not be {@code null}. 1052 * @return The URI for the newly inserted item. 1053 */ insert(Uri uri, ContentValues values)1054 public abstract Uri insert(Uri uri, ContentValues values); 1055 1056 /** 1057 * Override this to handle requests to insert a set of new rows, or the 1058 * default implementation will iterate over the values and call 1059 * {@link #insert} on each of them. 1060 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()} 1061 * after inserting. 1062 * This method can be called from multiple threads, as described in 1063 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes 1064 * and Threads</a>. 1065 * 1066 * @param uri The content:// URI of the insertion request. 1067 * @param values An array of sets of column_name/value pairs to add to the database. 1068 * This must not be {@code null}. 1069 * @return The number of values that were inserted. 1070 */ bulkInsert(Uri uri, ContentValues[] values)1071 public int bulkInsert(Uri uri, ContentValues[] values) { 1072 int numValues = values.length; 1073 for (int i = 0; i < numValues; i++) { 1074 insert(uri, values[i]); 1075 } 1076 return numValues; 1077 } 1078 1079 /** 1080 * Implement this to handle requests to delete one or more rows. 1081 * The implementation should apply the selection clause when performing 1082 * deletion, allowing the operation to affect multiple rows in a directory. 1083 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()} 1084 * after deleting. 1085 * This method can be called from multiple threads, as described in 1086 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes 1087 * and Threads</a>. 1088 * 1089 * <p>The implementation is responsible for parsing out a row ID at the end 1090 * of the URI, if a specific row is being deleted. That is, the client would 1091 * pass in <code>content://contacts/people/22</code> and the implementation is 1092 * responsible for parsing the record number (22) when creating a SQL statement. 1093 * 1094 * @param uri The full URI to query, including a row ID (if a specific record is requested). 1095 * @param selection An optional restriction to apply to rows when deleting. 1096 * @return The number of rows affected. 1097 * @throws SQLException 1098 */ delete(Uri uri, String selection, String[] selectionArgs)1099 public abstract int delete(Uri uri, String selection, String[] selectionArgs); 1100 1101 /** 1102 * Implement this to handle requests to update one or more rows. 1103 * The implementation should update all rows matching the selection 1104 * to set the columns according to the provided values map. 1105 * As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()} 1106 * after updating. 1107 * This method can be called from multiple threads, as described in 1108 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes 1109 * and Threads</a>. 1110 * 1111 * @param uri The URI to query. This can potentially have a record ID if this 1112 * is an update request for a specific record. 1113 * @param values A set of column_name/value pairs to update in the database. 1114 * This must not be {@code null}. 1115 * @param selection An optional filter to match rows to update. 1116 * @return the number of rows affected. 1117 */ update(Uri uri, ContentValues values, String selection, String[] selectionArgs)1118 public abstract int update(Uri uri, ContentValues values, String selection, 1119 String[] selectionArgs); 1120 1121 /** 1122 * Override this to handle requests to open a file blob. 1123 * The default implementation always throws {@link FileNotFoundException}. 1124 * This method can be called from multiple threads, as described in 1125 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes 1126 * and Threads</a>. 1127 * 1128 * <p>This method returns a ParcelFileDescriptor, which is returned directly 1129 * to the caller. This way large data (such as images and documents) can be 1130 * returned without copying the content. 1131 * 1132 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is 1133 * their responsibility to close it when done. That is, the implementation 1134 * of this method should create a new ParcelFileDescriptor for each call. 1135 * <p> 1136 * If opened with the exclusive "r" or "w" modes, the returned 1137 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming 1138 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that 1139 * supports seeking. 1140 * <p> 1141 * If you need to detect when the returned ParcelFileDescriptor has been 1142 * closed, or if the remote process has crashed or encountered some other 1143 * error, you can use {@link ParcelFileDescriptor#open(File, int, 1144 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)}, 1145 * {@link ParcelFileDescriptor#createReliablePipe()}, or 1146 * {@link ParcelFileDescriptor#createReliableSocketPair()}. 1147 * 1148 * <p class="note">For use in Intents, you will want to implement {@link #getType} 1149 * to return the appropriate MIME type for the data returned here with 1150 * the same URI. This will allow intent resolution to automatically determine the data MIME 1151 * type and select the appropriate matching targets as part of its operation.</p> 1152 * 1153 * <p class="note">For better interoperability with other applications, it is recommended 1154 * that for any URIs that can be opened, you also support queries on them 1155 * containing at least the columns specified by {@link android.provider.OpenableColumns}. 1156 * You may also want to support other common columns if you have additional meta-data 1157 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED} 1158 * in {@link android.provider.MediaStore.MediaColumns}.</p> 1159 * 1160 * @param uri The URI whose file is to be opened. 1161 * @param mode Access mode for the file. May be "r" for read-only access, 1162 * "rw" for read and write access, or "rwt" for read and write access 1163 * that truncates any existing file. 1164 * 1165 * @return Returns a new ParcelFileDescriptor which you can use to access 1166 * the file. 1167 * 1168 * @throws FileNotFoundException Throws FileNotFoundException if there is 1169 * no file associated with the given URI or the mode is invalid. 1170 * @throws SecurityException Throws SecurityException if the caller does 1171 * not have permission to access the file. 1172 * 1173 * @see #openAssetFile(Uri, String) 1174 * @see #openFileHelper(Uri, String) 1175 * @see #getType(android.net.Uri) 1176 * @see ParcelFileDescriptor#parseMode(String) 1177 */ openFile(Uri uri, String mode)1178 public ParcelFileDescriptor openFile(Uri uri, String mode) 1179 throws FileNotFoundException { 1180 throw new FileNotFoundException("No files supported by provider at " 1181 + uri); 1182 } 1183 1184 /** 1185 * Override this to handle requests to open a file blob. 1186 * The default implementation always throws {@link FileNotFoundException}. 1187 * This method can be called from multiple threads, as described in 1188 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes 1189 * and Threads</a>. 1190 * 1191 * <p>This method returns a ParcelFileDescriptor, which is returned directly 1192 * to the caller. This way large data (such as images and documents) can be 1193 * returned without copying the content. 1194 * 1195 * <p>The returned ParcelFileDescriptor is owned by the caller, so it is 1196 * their responsibility to close it when done. That is, the implementation 1197 * of this method should create a new ParcelFileDescriptor for each call. 1198 * <p> 1199 * If opened with the exclusive "r" or "w" modes, the returned 1200 * ParcelFileDescriptor can be a pipe or socket pair to enable streaming 1201 * of data. Opening with the "rw" or "rwt" modes implies a file on disk that 1202 * supports seeking. 1203 * <p> 1204 * If you need to detect when the returned ParcelFileDescriptor has been 1205 * closed, or if the remote process has crashed or encountered some other 1206 * error, you can use {@link ParcelFileDescriptor#open(File, int, 1207 * android.os.Handler, android.os.ParcelFileDescriptor.OnCloseListener)}, 1208 * {@link ParcelFileDescriptor#createReliablePipe()}, or 1209 * {@link ParcelFileDescriptor#createReliableSocketPair()}. 1210 * 1211 * <p class="note">For use in Intents, you will want to implement {@link #getType} 1212 * to return the appropriate MIME type for the data returned here with 1213 * the same URI. This will allow intent resolution to automatically determine the data MIME 1214 * type and select the appropriate matching targets as part of its operation.</p> 1215 * 1216 * <p class="note">For better interoperability with other applications, it is recommended 1217 * that for any URIs that can be opened, you also support queries on them 1218 * containing at least the columns specified by {@link android.provider.OpenableColumns}. 1219 * You may also want to support other common columns if you have additional meta-data 1220 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED} 1221 * in {@link android.provider.MediaStore.MediaColumns}.</p> 1222 * 1223 * @param uri The URI whose file is to be opened. 1224 * @param mode Access mode for the file. May be "r" for read-only access, 1225 * "w" for write-only access, "rw" for read and write access, or 1226 * "rwt" for read and write access that truncates any existing 1227 * file. 1228 * @param signal A signal to cancel the operation in progress, or 1229 * {@code null} if none. For example, if you are downloading a 1230 * file from the network to service a "rw" mode request, you 1231 * should periodically call 1232 * {@link CancellationSignal#throwIfCanceled()} to check whether 1233 * the client has canceled the request and abort the download. 1234 * 1235 * @return Returns a new ParcelFileDescriptor which you can use to access 1236 * the file. 1237 * 1238 * @throws FileNotFoundException Throws FileNotFoundException if there is 1239 * no file associated with the given URI or the mode is invalid. 1240 * @throws SecurityException Throws SecurityException if the caller does 1241 * not have permission to access the file. 1242 * 1243 * @see #openAssetFile(Uri, String) 1244 * @see #openFileHelper(Uri, String) 1245 * @see #getType(android.net.Uri) 1246 * @see ParcelFileDescriptor#parseMode(String) 1247 */ openFile(Uri uri, String mode, CancellationSignal signal)1248 public ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal) 1249 throws FileNotFoundException { 1250 return openFile(uri, mode); 1251 } 1252 1253 /** 1254 * This is like {@link #openFile}, but can be implemented by providers 1255 * that need to be able to return sub-sections of files, often assets 1256 * inside of their .apk. 1257 * This method can be called from multiple threads, as described in 1258 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes 1259 * and Threads</a>. 1260 * 1261 * <p>If you implement this, your clients must be able to deal with such 1262 * file slices, either directly with 1263 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level 1264 * {@link ContentResolver#openInputStream ContentResolver.openInputStream} 1265 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream} 1266 * methods. 1267 * <p> 1268 * The returned AssetFileDescriptor can be a pipe or socket pair to enable 1269 * streaming of data. 1270 * 1271 * <p class="note">If you are implementing this to return a full file, you 1272 * should create the AssetFileDescriptor with 1273 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with 1274 * applications that cannot handle sub-sections of files.</p> 1275 * 1276 * <p class="note">For use in Intents, you will want to implement {@link #getType} 1277 * to return the appropriate MIME type for the data returned here with 1278 * the same URI. This will allow intent resolution to automatically determine the data MIME 1279 * type and select the appropriate matching targets as part of its operation.</p> 1280 * 1281 * <p class="note">For better interoperability with other applications, it is recommended 1282 * that for any URIs that can be opened, you also support queries on them 1283 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p> 1284 * 1285 * @param uri The URI whose file is to be opened. 1286 * @param mode Access mode for the file. May be "r" for read-only access, 1287 * "w" for write-only access (erasing whatever data is currently in 1288 * the file), "wa" for write-only access to append to any existing data, 1289 * "rw" for read and write access on any existing data, and "rwt" for read 1290 * and write access that truncates any existing file. 1291 * 1292 * @return Returns a new AssetFileDescriptor which you can use to access 1293 * the file. 1294 * 1295 * @throws FileNotFoundException Throws FileNotFoundException if there is 1296 * no file associated with the given URI or the mode is invalid. 1297 * @throws SecurityException Throws SecurityException if the caller does 1298 * not have permission to access the file. 1299 * 1300 * @see #openFile(Uri, String) 1301 * @see #openFileHelper(Uri, String) 1302 * @see #getType(android.net.Uri) 1303 */ openAssetFile(Uri uri, String mode)1304 public AssetFileDescriptor openAssetFile(Uri uri, String mode) 1305 throws FileNotFoundException { 1306 ParcelFileDescriptor fd = openFile(uri, mode); 1307 return fd != null ? new AssetFileDescriptor(fd, 0, -1) : null; 1308 } 1309 1310 /** 1311 * This is like {@link #openFile}, but can be implemented by providers 1312 * that need to be able to return sub-sections of files, often assets 1313 * inside of their .apk. 1314 * This method can be called from multiple threads, as described in 1315 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes 1316 * and Threads</a>. 1317 * 1318 * <p>If you implement this, your clients must be able to deal with such 1319 * file slices, either directly with 1320 * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level 1321 * {@link ContentResolver#openInputStream ContentResolver.openInputStream} 1322 * or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream} 1323 * methods. 1324 * <p> 1325 * The returned AssetFileDescriptor can be a pipe or socket pair to enable 1326 * streaming of data. 1327 * 1328 * <p class="note">If you are implementing this to return a full file, you 1329 * should create the AssetFileDescriptor with 1330 * {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with 1331 * applications that cannot handle sub-sections of files.</p> 1332 * 1333 * <p class="note">For use in Intents, you will want to implement {@link #getType} 1334 * to return the appropriate MIME type for the data returned here with 1335 * the same URI. This will allow intent resolution to automatically determine the data MIME 1336 * type and select the appropriate matching targets as part of its operation.</p> 1337 * 1338 * <p class="note">For better interoperability with other applications, it is recommended 1339 * that for any URIs that can be opened, you also support queries on them 1340 * containing at least the columns specified by {@link android.provider.OpenableColumns}.</p> 1341 * 1342 * @param uri The URI whose file is to be opened. 1343 * @param mode Access mode for the file. May be "r" for read-only access, 1344 * "w" for write-only access (erasing whatever data is currently in 1345 * the file), "wa" for write-only access to append to any existing data, 1346 * "rw" for read and write access on any existing data, and "rwt" for read 1347 * and write access that truncates any existing file. 1348 * @param signal A signal to cancel the operation in progress, or 1349 * {@code null} if none. For example, if you are downloading a 1350 * file from the network to service a "rw" mode request, you 1351 * should periodically call 1352 * {@link CancellationSignal#throwIfCanceled()} to check whether 1353 * the client has canceled the request and abort the download. 1354 * 1355 * @return Returns a new AssetFileDescriptor which you can use to access 1356 * the file. 1357 * 1358 * @throws FileNotFoundException Throws FileNotFoundException if there is 1359 * no file associated with the given URI or the mode is invalid. 1360 * @throws SecurityException Throws SecurityException if the caller does 1361 * not have permission to access the file. 1362 * 1363 * @see #openFile(Uri, String) 1364 * @see #openFileHelper(Uri, String) 1365 * @see #getType(android.net.Uri) 1366 */ openAssetFile(Uri uri, String mode, CancellationSignal signal)1367 public AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal) 1368 throws FileNotFoundException { 1369 return openAssetFile(uri, mode); 1370 } 1371 1372 /** 1373 * Convenience for subclasses that wish to implement {@link #openFile} 1374 * by looking up a column named "_data" at the given URI. 1375 * 1376 * @param uri The URI to be opened. 1377 * @param mode The file mode. May be "r" for read-only access, 1378 * "w" for write-only access (erasing whatever data is currently in 1379 * the file), "wa" for write-only access to append to any existing data, 1380 * "rw" for read and write access on any existing data, and "rwt" for read 1381 * and write access that truncates any existing file. 1382 * 1383 * @return Returns a new ParcelFileDescriptor that can be used by the 1384 * client to access the file. 1385 */ openFileHelper(Uri uri, String mode)1386 protected final ParcelFileDescriptor openFileHelper(Uri uri, 1387 String mode) throws FileNotFoundException { 1388 Cursor c = query(uri, new String[]{"_data"}, null, null, null); 1389 int count = (c != null) ? c.getCount() : 0; 1390 if (count != 1) { 1391 // If there is not exactly one result, throw an appropriate 1392 // exception. 1393 if (c != null) { 1394 c.close(); 1395 } 1396 if (count == 0) { 1397 throw new FileNotFoundException("No entry for " + uri); 1398 } 1399 throw new FileNotFoundException("Multiple items at " + uri); 1400 } 1401 1402 c.moveToFirst(); 1403 int i = c.getColumnIndex("_data"); 1404 String path = (i >= 0 ? c.getString(i) : null); 1405 c.close(); 1406 if (path == null) { 1407 throw new FileNotFoundException("Column _data not found."); 1408 } 1409 1410 int modeBits = ParcelFileDescriptor.parseMode(mode); 1411 return ParcelFileDescriptor.open(new File(path), modeBits); 1412 } 1413 1414 /** 1415 * Called by a client to determine the types of data streams that this 1416 * content provider supports for the given URI. The default implementation 1417 * returns {@code null}, meaning no types. If your content provider stores data 1418 * of a particular type, return that MIME type if it matches the given 1419 * mimeTypeFilter. If it can perform type conversions, return an array 1420 * of all supported MIME types that match mimeTypeFilter. 1421 * 1422 * @param uri The data in the content provider being queried. 1423 * @param mimeTypeFilter The type of data the client desires. May be 1424 * a pattern, such as */* to retrieve all possible data types. 1425 * @return Returns {@code null} if there are no possible data streams for the 1426 * given mimeTypeFilter. Otherwise returns an array of all available 1427 * concrete MIME types. 1428 * 1429 * @see #getType(Uri) 1430 * @see #openTypedAssetFile(Uri, String, Bundle) 1431 * @see ClipDescription#compareMimeTypes(String, String) 1432 */ getStreamTypes(Uri uri, String mimeTypeFilter)1433 public String[] getStreamTypes(Uri uri, String mimeTypeFilter) { 1434 return null; 1435 } 1436 1437 /** 1438 * Called by a client to open a read-only stream containing data of a 1439 * particular MIME type. This is like {@link #openAssetFile(Uri, String)}, 1440 * except the file can only be read-only and the content provider may 1441 * perform data conversions to generate data of the desired type. 1442 * 1443 * <p>The default implementation compares the given mimeType against the 1444 * result of {@link #getType(Uri)} and, if they match, simply calls 1445 * {@link #openAssetFile(Uri, String)}. 1446 * 1447 * <p>See {@link ClipData} for examples of the use and implementation 1448 * of this method. 1449 * <p> 1450 * The returned AssetFileDescriptor can be a pipe or socket pair to enable 1451 * streaming of data. 1452 * 1453 * <p class="note">For better interoperability with other applications, it is recommended 1454 * that for any URIs that can be opened, you also support queries on them 1455 * containing at least the columns specified by {@link android.provider.OpenableColumns}. 1456 * You may also want to support other common columns if you have additional meta-data 1457 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED} 1458 * in {@link android.provider.MediaStore.MediaColumns}.</p> 1459 * 1460 * @param uri The data in the content provider being queried. 1461 * @param mimeTypeFilter The type of data the client desires. May be 1462 * a pattern, such as */*, if the caller does not have specific type 1463 * requirements; in this case the content provider will pick its best 1464 * type matching the pattern. 1465 * @param opts Additional options from the client. The definitions of 1466 * these are specific to the content provider being called. 1467 * 1468 * @return Returns a new AssetFileDescriptor from which the client can 1469 * read data of the desired type. 1470 * 1471 * @throws FileNotFoundException Throws FileNotFoundException if there is 1472 * no file associated with the given URI or the mode is invalid. 1473 * @throws SecurityException Throws SecurityException if the caller does 1474 * not have permission to access the data. 1475 * @throws IllegalArgumentException Throws IllegalArgumentException if the 1476 * content provider does not support the requested MIME type. 1477 * 1478 * @see #getStreamTypes(Uri, String) 1479 * @see #openAssetFile(Uri, String) 1480 * @see ClipDescription#compareMimeTypes(String, String) 1481 */ openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)1482 public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts) 1483 throws FileNotFoundException { 1484 if ("*/*".equals(mimeTypeFilter)) { 1485 // If they can take anything, the untyped open call is good enough. 1486 return openAssetFile(uri, "r"); 1487 } 1488 String baseType = getType(uri); 1489 if (baseType != null && ClipDescription.compareMimeTypes(baseType, mimeTypeFilter)) { 1490 // Use old untyped open call if this provider has a type for this 1491 // URI and it matches the request. 1492 return openAssetFile(uri, "r"); 1493 } 1494 throw new FileNotFoundException("Can't open " + uri + " as type " + mimeTypeFilter); 1495 } 1496 1497 1498 /** 1499 * Called by a client to open a read-only stream containing data of a 1500 * particular MIME type. This is like {@link #openAssetFile(Uri, String)}, 1501 * except the file can only be read-only and the content provider may 1502 * perform data conversions to generate data of the desired type. 1503 * 1504 * <p>The default implementation compares the given mimeType against the 1505 * result of {@link #getType(Uri)} and, if they match, simply calls 1506 * {@link #openAssetFile(Uri, String)}. 1507 * 1508 * <p>See {@link ClipData} for examples of the use and implementation 1509 * of this method. 1510 * <p> 1511 * The returned AssetFileDescriptor can be a pipe or socket pair to enable 1512 * streaming of data. 1513 * 1514 * <p class="note">For better interoperability with other applications, it is recommended 1515 * that for any URIs that can be opened, you also support queries on them 1516 * containing at least the columns specified by {@link android.provider.OpenableColumns}. 1517 * You may also want to support other common columns if you have additional meta-data 1518 * to supply, such as {@link android.provider.MediaStore.MediaColumns#DATE_ADDED} 1519 * in {@link android.provider.MediaStore.MediaColumns}.</p> 1520 * 1521 * @param uri The data in the content provider being queried. 1522 * @param mimeTypeFilter The type of data the client desires. May be 1523 * a pattern, such as */*, if the caller does not have specific type 1524 * requirements; in this case the content provider will pick its best 1525 * type matching the pattern. 1526 * @param opts Additional options from the client. The definitions of 1527 * these are specific to the content provider being called. 1528 * @param signal A signal to cancel the operation in progress, or 1529 * {@code null} if none. For example, if you are downloading a 1530 * file from the network to service a "rw" mode request, you 1531 * should periodically call 1532 * {@link CancellationSignal#throwIfCanceled()} to check whether 1533 * the client has canceled the request and abort the download. 1534 * 1535 * @return Returns a new AssetFileDescriptor from which the client can 1536 * read data of the desired type. 1537 * 1538 * @throws FileNotFoundException Throws FileNotFoundException if there is 1539 * no file associated with the given URI or the mode is invalid. 1540 * @throws SecurityException Throws SecurityException if the caller does 1541 * not have permission to access the data. 1542 * @throws IllegalArgumentException Throws IllegalArgumentException if the 1543 * content provider does not support the requested MIME type. 1544 * 1545 * @see #getStreamTypes(Uri, String) 1546 * @see #openAssetFile(Uri, String) 1547 * @see ClipDescription#compareMimeTypes(String, String) 1548 */ openTypedAssetFile( Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)1549 public AssetFileDescriptor openTypedAssetFile( 1550 Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal) 1551 throws FileNotFoundException { 1552 return openTypedAssetFile(uri, mimeTypeFilter, opts); 1553 } 1554 1555 /** 1556 * Interface to write a stream of data to a pipe. Use with 1557 * {@link ContentProvider#openPipeHelper}. 1558 */ 1559 public interface PipeDataWriter<T> { 1560 /** 1561 * Called from a background thread to stream data out to a pipe. 1562 * Note that the pipe is blocking, so this thread can block on 1563 * writes for an arbitrary amount of time if the client is slow 1564 * at reading. 1565 * 1566 * @param output The pipe where data should be written. This will be 1567 * closed for you upon returning from this function. 1568 * @param uri The URI whose data is to be written. 1569 * @param mimeType The desired type of data to be written. 1570 * @param opts Options supplied by caller. 1571 * @param args Your own custom arguments. 1572 */ writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType, Bundle opts, T args)1573 public void writeDataToPipe(ParcelFileDescriptor output, Uri uri, String mimeType, 1574 Bundle opts, T args); 1575 } 1576 1577 /** 1578 * A helper function for implementing {@link #openTypedAssetFile}, for 1579 * creating a data pipe and background thread allowing you to stream 1580 * generated data back to the client. This function returns a new 1581 * ParcelFileDescriptor that should be returned to the caller (the caller 1582 * is responsible for closing it). 1583 * 1584 * @param uri The URI whose data is to be written. 1585 * @param mimeType The desired type of data to be written. 1586 * @param opts Options supplied by caller. 1587 * @param args Your own custom arguments. 1588 * @param func Interface implementing the function that will actually 1589 * stream the data. 1590 * @return Returns a new ParcelFileDescriptor holding the read side of 1591 * the pipe. This should be returned to the caller for reading; the caller 1592 * is responsible for closing it when done. 1593 */ openPipeHelper(final Uri uri, final String mimeType, final Bundle opts, final T args, final PipeDataWriter<T> func)1594 public <T> ParcelFileDescriptor openPipeHelper(final Uri uri, final String mimeType, 1595 final Bundle opts, final T args, final PipeDataWriter<T> func) 1596 throws FileNotFoundException { 1597 try { 1598 final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createPipe(); 1599 1600 AsyncTask<Object, Object, Object> task = new AsyncTask<Object, Object, Object>() { 1601 @Override 1602 protected Object doInBackground(Object... params) { 1603 func.writeDataToPipe(fds[1], uri, mimeType, opts, args); 1604 try { 1605 fds[1].close(); 1606 } catch (IOException e) { 1607 Log.w(TAG, "Failure closing pipe", e); 1608 } 1609 return null; 1610 } 1611 }; 1612 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])null); 1613 1614 return fds[0]; 1615 } catch (IOException e) { 1616 throw new FileNotFoundException("failure making pipe"); 1617 } 1618 } 1619 1620 /** 1621 * Returns true if this instance is a temporary content provider. 1622 * @return true if this instance is a temporary content provider 1623 */ isTemporary()1624 protected boolean isTemporary() { 1625 return false; 1626 } 1627 1628 /** 1629 * Returns the Binder object for this provider. 1630 * 1631 * @return the Binder object for this provider 1632 * @hide 1633 */ getIContentProvider()1634 public IContentProvider getIContentProvider() { 1635 return mTransport; 1636 } 1637 1638 /** 1639 * Like {@link #attachInfo(Context, android.content.pm.ProviderInfo)}, but for use 1640 * when directly instantiating the provider for testing. 1641 * @hide 1642 */ attachInfoForTesting(Context context, ProviderInfo info)1643 public void attachInfoForTesting(Context context, ProviderInfo info) { 1644 attachInfo(context, info, true); 1645 } 1646 1647 /** 1648 * After being instantiated, this is called to tell the content provider 1649 * about itself. 1650 * 1651 * @param context The context this provider is running in 1652 * @param info Registered information about this content provider 1653 */ attachInfo(Context context, ProviderInfo info)1654 public void attachInfo(Context context, ProviderInfo info) { 1655 attachInfo(context, info, false); 1656 } 1657 attachInfo(Context context, ProviderInfo info, boolean testing)1658 private void attachInfo(Context context, ProviderInfo info, boolean testing) { 1659 /* 1660 * We may be using AsyncTask from binder threads. Make it init here 1661 * so its static handler is on the main thread. 1662 */ 1663 AsyncTask.init(); 1664 1665 mNoPerms = testing; 1666 1667 /* 1668 * Only allow it to be set once, so after the content service gives 1669 * this to us clients can't change it. 1670 */ 1671 if (mContext == null) { 1672 mContext = context; 1673 if (context != null) { 1674 mTransport.mAppOpsManager = (AppOpsManager) context.getSystemService( 1675 Context.APP_OPS_SERVICE); 1676 } 1677 mMyUid = Process.myUid(); 1678 if (info != null) { 1679 setReadPermission(info.readPermission); 1680 setWritePermission(info.writePermission); 1681 setPathPermissions(info.pathPermissions); 1682 mExported = info.exported; 1683 mSingleUser = (info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0; 1684 setAuthorities(info.authority); 1685 } 1686 ContentProvider.this.onCreate(); 1687 } 1688 } 1689 1690 /** 1691 * Override this to handle requests to perform a batch of operations, or the 1692 * default implementation will iterate over the operations and call 1693 * {@link ContentProviderOperation#apply} on each of them. 1694 * If all calls to {@link ContentProviderOperation#apply} succeed 1695 * then a {@link ContentProviderResult} array with as many 1696 * elements as there were operations will be returned. If any of the calls 1697 * fail, it is up to the implementation how many of the others take effect. 1698 * This method can be called from multiple threads, as described in 1699 * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#Threads">Processes 1700 * and Threads</a>. 1701 * 1702 * @param operations the operations to apply 1703 * @return the results of the applications 1704 * @throws OperationApplicationException thrown if any operation fails. 1705 * @see ContentProviderOperation#apply 1706 */ applyBatch(ArrayList<ContentProviderOperation> operations)1707 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) 1708 throws OperationApplicationException { 1709 final int numOperations = operations.size(); 1710 final ContentProviderResult[] results = new ContentProviderResult[numOperations]; 1711 for (int i = 0; i < numOperations; i++) { 1712 results[i] = operations.get(i).apply(this, results, i); 1713 } 1714 return results; 1715 } 1716 1717 /** 1718 * Call a provider-defined method. This can be used to implement 1719 * interfaces that are cheaper and/or unnatural for a table-like 1720 * model. 1721 * 1722 * <p class="note"><strong>WARNING:</strong> The framework does no permission checking 1723 * on this entry into the content provider besides the basic ability for the application 1724 * to get access to the provider at all. For example, it has no idea whether the call 1725 * being executed may read or write data in the provider, so can't enforce those 1726 * individual permissions. Any implementation of this method <strong>must</strong> 1727 * do its own permission checks on incoming calls to make sure they are allowed.</p> 1728 * 1729 * @param method method name to call. Opaque to framework, but should not be {@code null}. 1730 * @param arg provider-defined String argument. May be {@code null}. 1731 * @param extras provider-defined Bundle argument. May be {@code null}. 1732 * @return provider-defined return value. May be {@code null}, which is also 1733 * the default for providers which don't implement any call methods. 1734 */ call(String method, String arg, Bundle extras)1735 public Bundle call(String method, String arg, Bundle extras) { 1736 return null; 1737 } 1738 1739 /** 1740 * Implement this to shut down the ContentProvider instance. You can then 1741 * invoke this method in unit tests. 1742 * 1743 * <p> 1744 * Android normally handles ContentProvider startup and shutdown 1745 * automatically. You do not need to start up or shut down a 1746 * ContentProvider. When you invoke a test method on a ContentProvider, 1747 * however, a ContentProvider instance is started and keeps running after 1748 * the test finishes, even if a succeeding test instantiates another 1749 * ContentProvider. A conflict develops because the two instances are 1750 * usually running against the same underlying data source (for example, an 1751 * sqlite database). 1752 * </p> 1753 * <p> 1754 * Implementing shutDown() avoids this conflict by providing a way to 1755 * terminate the ContentProvider. This method can also prevent memory leaks 1756 * from multiple instantiations of the ContentProvider, and it can ensure 1757 * unit test isolation by allowing you to completely clean up the test 1758 * fixture before moving on to the next test. 1759 * </p> 1760 */ shutdown()1761 public void shutdown() { 1762 Log.w(TAG, "implement ContentProvider shutdown() to make sure all database " + 1763 "connections are gracefully shutdown"); 1764 } 1765 1766 /** 1767 * Print the Provider's state into the given stream. This gets invoked if 1768 * you run "adb shell dumpsys activity provider <provider_component_name>". 1769 * 1770 * @param fd The raw file descriptor that the dump is being sent to. 1771 * @param writer The PrintWriter to which you should dump your state. This will be 1772 * closed for you after you return. 1773 * @param args additional arguments to the dump request. 1774 */ dump(FileDescriptor fd, PrintWriter writer, String[] args)1775 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) { 1776 writer.println("nothing to dump"); 1777 } 1778 1779 /** @hide */ validateIncomingUri(Uri uri)1780 private void validateIncomingUri(Uri uri) throws SecurityException { 1781 String auth = uri.getAuthority(); 1782 int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT); 1783 if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) { 1784 throw new SecurityException("trying to query a ContentProvider in user " 1785 + mContext.getUserId() + " with a uri belonging to user " + userId); 1786 } 1787 if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) { 1788 String message = "The authority of the uri " + uri + " does not match the one of the " 1789 + "contentProvider: "; 1790 if (mAuthority != null) { 1791 message += mAuthority; 1792 } else { 1793 message += mAuthorities; 1794 } 1795 throw new SecurityException(message); 1796 } 1797 } 1798 1799 /** @hide */ getUserIdFromAuthority(String auth, int defaultUserId)1800 public static int getUserIdFromAuthority(String auth, int defaultUserId) { 1801 if (auth == null) return defaultUserId; 1802 int end = auth.lastIndexOf('@'); 1803 if (end == -1) return defaultUserId; 1804 String userIdString = auth.substring(0, end); 1805 try { 1806 return Integer.parseInt(userIdString); 1807 } catch (NumberFormatException e) { 1808 Log.w(TAG, "Error parsing userId.", e); 1809 return UserHandle.USER_NULL; 1810 } 1811 } 1812 1813 /** @hide */ getUserIdFromAuthority(String auth)1814 public static int getUserIdFromAuthority(String auth) { 1815 return getUserIdFromAuthority(auth, UserHandle.USER_CURRENT); 1816 } 1817 1818 /** @hide */ getUserIdFromUri(Uri uri, int defaultUserId)1819 public static int getUserIdFromUri(Uri uri, int defaultUserId) { 1820 if (uri == null) return defaultUserId; 1821 return getUserIdFromAuthority(uri.getAuthority(), defaultUserId); 1822 } 1823 1824 /** @hide */ getUserIdFromUri(Uri uri)1825 public static int getUserIdFromUri(Uri uri) { 1826 return getUserIdFromUri(uri, UserHandle.USER_CURRENT); 1827 } 1828 1829 /** 1830 * Removes userId part from authority string. Expects format: 1831 * userId@some.authority 1832 * If there is no userId in the authority, it symply returns the argument 1833 * @hide 1834 */ getAuthorityWithoutUserId(String auth)1835 public static String getAuthorityWithoutUserId(String auth) { 1836 if (auth == null) return null; 1837 int end = auth.lastIndexOf('@'); 1838 return auth.substring(end+1); 1839 } 1840 1841 /** @hide */ getUriWithoutUserId(Uri uri)1842 public static Uri getUriWithoutUserId(Uri uri) { 1843 if (uri == null) return null; 1844 Uri.Builder builder = uri.buildUpon(); 1845 builder.authority(getAuthorityWithoutUserId(uri.getAuthority())); 1846 return builder.build(); 1847 } 1848 1849 /** @hide */ uriHasUserId(Uri uri)1850 public static boolean uriHasUserId(Uri uri) { 1851 if (uri == null) return false; 1852 return !TextUtils.isEmpty(uri.getUserInfo()); 1853 } 1854 1855 /** @hide */ maybeAddUserId(Uri uri, int userId)1856 public static Uri maybeAddUserId(Uri uri, int userId) { 1857 if (uri == null) return null; 1858 if (userId != UserHandle.USER_CURRENT 1859 && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) { 1860 if (!uriHasUserId(uri)) { 1861 //We don't add the user Id if there's already one 1862 Uri.Builder builder = uri.buildUpon(); 1863 builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority()); 1864 return builder.build(); 1865 } 1866 } 1867 return uri; 1868 } 1869 } 1870