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