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