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