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