ContentResolver.java revision 38ed2a471a2291383821fb187bfa18450f0581c2
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 android.accounts.Account;
20import android.app.ActivityManagerNative;
21import android.app.ActivityThread;
22import android.app.AppGlobals;
23import android.content.pm.PackageManager.NameNotFoundException;
24import android.content.res.AssetFileDescriptor;
25import android.content.res.Resources;
26import android.database.ContentObserver;
27import android.database.CrossProcessCursorWrapper;
28import android.database.Cursor;
29import android.database.IContentObserver;
30import android.net.Uri;
31import android.os.Bundle;
32import android.os.CancellationSignal;
33import android.os.DeadObjectException;
34import android.os.IBinder;
35import android.os.ICancellationSignal;
36import android.os.OperationCanceledException;
37import android.os.ParcelFileDescriptor;
38import android.os.RemoteException;
39import android.os.ServiceManager;
40import android.os.SystemClock;
41import android.os.UserHandle;
42import android.text.TextUtils;
43import android.util.EventLog;
44import android.util.Log;
45
46import dalvik.system.CloseGuard;
47
48import java.io.File;
49import java.io.FileInputStream;
50import java.io.FileNotFoundException;
51import java.io.IOException;
52import java.io.InputStream;
53import java.io.OutputStream;
54import java.util.ArrayList;
55import java.util.List;
56import java.util.Random;
57
58/**
59 * This class provides applications access to the content model.
60 *
61 * <div class="special reference">
62 * <h3>Developer Guides</h3>
63 * <p>For more information about using a ContentResolver with content providers, read the
64 * <a href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>
65 * developer guide.</p>
66 */
67public abstract class ContentResolver {
68    /**
69     * @deprecated instead use
70     * {@link #requestSync(android.accounts.Account, String, android.os.Bundle)}
71     */
72    @Deprecated
73    public static final String SYNC_EXTRAS_ACCOUNT = "account";
74
75    /**
76     * If this extra is set to true, the sync request will be scheduled
77     * at the front of the sync request queue and without any delay
78     */
79    public static final String SYNC_EXTRAS_EXPEDITED = "expedited";
80
81    /**
82     * @deprecated instead use
83     * {@link #SYNC_EXTRAS_MANUAL}
84     */
85    @Deprecated
86    public static final String SYNC_EXTRAS_FORCE = "force";
87
88    /**
89     * If this extra is set to true then the sync settings (like getSyncAutomatically())
90     * are ignored by the sync scheduler.
91     */
92    public static final String SYNC_EXTRAS_IGNORE_SETTINGS = "ignore_settings";
93
94    /**
95     * If this extra is set to true then any backoffs for the initial attempt (e.g. due to retries)
96     * are ignored by the sync scheduler. If this request fails and gets rescheduled then the
97     * retries will still honor the backoff.
98     */
99    public static final String SYNC_EXTRAS_IGNORE_BACKOFF = "ignore_backoff";
100
101    /**
102     * If this extra is set to true then the request will not be retried if it fails.
103     */
104    public static final String SYNC_EXTRAS_DO_NOT_RETRY = "do_not_retry";
105
106    /**
107     * Setting this extra is the equivalent of setting both {@link #SYNC_EXTRAS_IGNORE_SETTINGS}
108     * and {@link #SYNC_EXTRAS_IGNORE_BACKOFF}
109     */
110    public static final String SYNC_EXTRAS_MANUAL = "force";
111
112    /**
113     * Indicates that this sync is intended to only upload local changes to the server.
114     * For example, this will be set to true if the sync is initiated by a call to
115     * {@link ContentResolver#notifyChange(android.net.Uri, android.database.ContentObserver, boolean)}
116     */
117    public static final String SYNC_EXTRAS_UPLOAD = "upload";
118
119    /**
120     * Indicates that the sync adapter should proceed with the delete operations,
121     * even if it determines that there are too many.
122     * See {@link SyncResult#tooManyDeletions}
123     */
124    public static final String SYNC_EXTRAS_OVERRIDE_TOO_MANY_DELETIONS = "deletions_override";
125
126    /**
127     * Indicates that the sync adapter should not proceed with the delete operations,
128     * if it determines that there are too many.
129     * See {@link SyncResult#tooManyDeletions}
130     */
131    public static final String SYNC_EXTRAS_DISCARD_LOCAL_DELETIONS = "discard_deletions";
132
133    /* Extensions to API. TODO: Not clear if we will keep these as public flags. */
134    /** {@hide} User-specified flag for expected upload size. */
135    public static final String SYNC_EXTRAS_EXPECTED_UPLOAD = "expected_upload";
136
137    /** {@hide} User-specified flag for expected download size. */
138    public static final String SYNC_EXTRAS_EXPECTED_DOWNLOAD = "expected_download";
139
140    /** {@hide} Priority of this sync with respect to other syncs scheduled for this application. */
141    public static final String SYNC_EXTRAS_PRIORITY = "sync_priority";
142
143    /** {@hide} Flag to allow sync to occur on metered network. */
144    public static final String SYNC_EXTRAS_DISALLOW_METERED = "disallow_metered";
145
146    /**
147     * Set by the SyncManager to request that the SyncAdapter initialize itself for
148     * the given account/authority pair. One required initialization step is to
149     * ensure that {@link #setIsSyncable(android.accounts.Account, String, int)} has been
150     * called with a >= 0 value. When this flag is set the SyncAdapter does not need to
151     * do a full sync, though it is allowed to do so.
152     */
153    public static final String SYNC_EXTRAS_INITIALIZE = "initialize";
154
155    /** @hide */
156    public static final Intent ACTION_SYNC_CONN_STATUS_CHANGED =
157            new Intent("com.android.sync.SYNC_CONN_STATUS_CHANGED");
158
159    public static final String SCHEME_CONTENT = "content";
160    public static final String SCHEME_ANDROID_RESOURCE = "android.resource";
161    public static final String SCHEME_FILE = "file";
162
163    /**
164     * This is the Android platform's base MIME type for a content: URI
165     * containing a Cursor of a single item.  Applications should use this
166     * as the base type along with their own sub-type of their content: URIs
167     * that represent a particular item.  For example, hypothetical IMAP email
168     * client may have a URI
169     * <code>content://com.company.provider.imap/inbox/1</code> for a particular
170     * message in the inbox, whose MIME type would be reported as
171     * <code>CURSOR_ITEM_BASE_TYPE + "/vnd.company.imap-msg"</code>
172     *
173     * <p>Compare with {@link #CURSOR_DIR_BASE_TYPE}.
174     */
175    public static final String CURSOR_ITEM_BASE_TYPE = "vnd.android.cursor.item";
176
177    /**
178     * This is the Android platform's base MIME type for a content: URI
179     * containing a Cursor of zero or more items.  Applications should use this
180     * as the base type along with their own sub-type of their content: URIs
181     * that represent a directory of items.  For example, hypothetical IMAP email
182     * client may have a URI
183     * <code>content://com.company.provider.imap/inbox</code> for all of the
184     * messages in its inbox, whose MIME type would be reported as
185     * <code>CURSOR_DIR_BASE_TYPE + "/vnd.company.imap-msg"</code>
186     *
187     * <p>Note how the base MIME type varies between this and
188     * {@link #CURSOR_ITEM_BASE_TYPE} depending on whether there is
189     * one single item or multiple items in the data set, while the sub-type
190     * remains the same because in either case the data structure contained
191     * in the cursor is the same.
192     */
193    public static final String CURSOR_DIR_BASE_TYPE = "vnd.android.cursor.dir";
194
195    /** @hide */
196    public static final int SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS = 1;
197    /** @hide */
198    public static final int SYNC_ERROR_AUTHENTICATION = 2;
199    /** @hide */
200    public static final int SYNC_ERROR_IO = 3;
201    /** @hide */
202    public static final int SYNC_ERROR_PARSE = 4;
203    /** @hide */
204    public static final int SYNC_ERROR_CONFLICT = 5;
205    /** @hide */
206    public static final int SYNC_ERROR_TOO_MANY_DELETIONS = 6;
207    /** @hide */
208    public static final int SYNC_ERROR_TOO_MANY_RETRIES = 7;
209    /** @hide */
210    public static final int SYNC_ERROR_INTERNAL = 8;
211
212    private static final String[] SYNC_ERROR_NAMES = new String[] {
213          "already-in-progress",
214          "authentication-error",
215          "io-error",
216          "parse-error",
217          "conflict",
218          "too-many-deletions",
219          "too-many-retries",
220          "internal-error",
221    };
222
223    /** @hide */
224    public static String syncErrorToString(int error) {
225        if (error < 1 || error > SYNC_ERROR_NAMES.length) {
226            return String.valueOf(error);
227        }
228        return SYNC_ERROR_NAMES[error - 1];
229    }
230
231    /** @hide */
232    public static int syncErrorStringToInt(String error) {
233        for (int i = 0, n = SYNC_ERROR_NAMES.length; i < n; i++) {
234            if (SYNC_ERROR_NAMES[i].equals(error)) {
235                return i + 1;
236            }
237        }
238        if (error != null) {
239            try {
240                return Integer.parseInt(error);
241            } catch (NumberFormatException e) {
242                Log.d(TAG, "error parsing sync error: " + error);
243            }
244        }
245        return 0;
246    }
247
248    public static final int SYNC_OBSERVER_TYPE_SETTINGS = 1<<0;
249    public static final int SYNC_OBSERVER_TYPE_PENDING = 1<<1;
250    public static final int SYNC_OBSERVER_TYPE_ACTIVE = 1<<2;
251    /** @hide */
252    public static final int SYNC_OBSERVER_TYPE_STATUS = 1<<3;
253    /** @hide */
254    public static final int SYNC_OBSERVER_TYPE_ALL = 0x7fffffff;
255
256    // Always log queries which take 500ms+; shorter queries are
257    // sampled accordingly.
258    private static final boolean ENABLE_CONTENT_SAMPLE = false;
259    private static final int SLOW_THRESHOLD_MILLIS = 500;
260    private final Random mRandom = new Random();  // guarded by itself
261
262    public ContentResolver(Context context) {
263        mContext = context != null ? context : ActivityThread.currentApplication();
264        mPackageName = mContext.getBasePackageName();
265    }
266
267    /** @hide */
268    protected abstract IContentProvider acquireProvider(Context c, String name);
269    /** Providing a default implementation of this, to avoid having to change
270     * a lot of other things, but implementations of ContentResolver should
271     * implement it. @hide */
272    protected IContentProvider acquireExistingProvider(Context c, String name) {
273        return acquireProvider(c, name);
274    }
275    /** @hide */
276    public abstract boolean releaseProvider(IContentProvider icp);
277    /** @hide */
278    protected abstract IContentProvider acquireUnstableProvider(Context c, String name);
279    /** @hide */
280    public abstract boolean releaseUnstableProvider(IContentProvider icp);
281    /** @hide */
282    public abstract void unstableProviderDied(IContentProvider icp);
283
284    /**
285     * Return the MIME type of the given content URL.
286     *
287     * @param url A Uri identifying content (either a list or specific type),
288     * using the content:// scheme.
289     * @return A MIME type for the content, or null if the URL is invalid or the type is unknown
290     */
291    public final String getType(Uri url) {
292        // XXX would like to have an acquireExistingUnstableProvider for this.
293        IContentProvider provider = acquireExistingProvider(url);
294        if (provider != null) {
295            try {
296                return provider.getType(url);
297            } catch (RemoteException e) {
298                return null;
299            } catch (java.lang.Exception e) {
300                Log.w(TAG, "Failed to get type for: " + url + " (" + e.getMessage() + ")");
301                return null;
302            } finally {
303                releaseProvider(provider);
304            }
305        }
306
307        if (!SCHEME_CONTENT.equals(url.getScheme())) {
308            return null;
309        }
310
311        try {
312            String type = ActivityManagerNative.getDefault().getProviderMimeType(
313                    url, UserHandle.myUserId());
314            return type;
315        } catch (RemoteException e) {
316            // Arbitrary and not worth documenting, as Activity
317            // Manager will kill this process shortly anyway.
318            return null;
319        } catch (java.lang.Exception e) {
320            Log.w(TAG, "Failed to get type for: " + url + " (" + e.getMessage() + ")");
321            return null;
322        }
323    }
324
325    /**
326     * Query for the possible MIME types for the representations the given
327     * content URL can be returned when opened as as stream with
328     * {@link #openTypedAssetFileDescriptor}.  Note that the types here are
329     * not necessarily a superset of the type returned by {@link #getType} --
330     * many content providers cannot return a raw stream for the structured
331     * data that they contain.
332     *
333     * @param url A Uri identifying content (either a list or specific type),
334     * using the content:// scheme.
335     * @param mimeTypeFilter The desired MIME type.  This may be a pattern,
336     * such as *\/*, to query for all available MIME types that match the
337     * pattern.
338     * @return Returns an array of MIME type strings for all available
339     * data streams that match the given mimeTypeFilter.  If there are none,
340     * null is returned.
341     */
342    public String[] getStreamTypes(Uri url, String mimeTypeFilter) {
343        IContentProvider provider = acquireProvider(url);
344        if (provider == null) {
345            return null;
346        }
347
348        try {
349            return provider.getStreamTypes(url, mimeTypeFilter);
350        } catch (RemoteException e) {
351            // Arbitrary and not worth documenting, as Activity
352            // Manager will kill this process shortly anyway.
353            return null;
354        } finally {
355            releaseProvider(provider);
356        }
357    }
358
359    /**
360     * <p>
361     * Query the given URI, returning a {@link Cursor} over the result set.
362     * </p>
363     * <p>
364     * For best performance, the caller should follow these guidelines:
365     * <ul>
366     * <li>Provide an explicit projection, to prevent
367     * reading data from storage that aren't going to be used.</li>
368     * <li>Use question mark parameter markers such as 'phone=?' instead of
369     * explicit values in the {@code selection} parameter, so that queries
370     * that differ only by those values will be recognized as the same
371     * for caching purposes.</li>
372     * </ul>
373     * </p>
374     *
375     * @param uri The URI, using the content:// scheme, for the content to
376     *         retrieve.
377     * @param projection A list of which columns to return. Passing null will
378     *         return all columns, which is inefficient.
379     * @param selection A filter declaring which rows to return, formatted as an
380     *         SQL WHERE clause (excluding the WHERE itself). Passing null will
381     *         return all rows for the given URI.
382     * @param selectionArgs You may include ?s in selection, which will be
383     *         replaced by the values from selectionArgs, in the order that they
384     *         appear in the selection. The values will be bound as Strings.
385     * @param sortOrder How to order the rows, formatted as an SQL ORDER BY
386     *         clause (excluding the ORDER BY itself). Passing null will use the
387     *         default sort order, which may be unordered.
388     * @return A Cursor object, which is positioned before the first entry, or null
389     * @see Cursor
390     */
391    public final Cursor query(Uri uri, String[] projection,
392            String selection, String[] selectionArgs, String sortOrder) {
393        return query(uri, projection, selection, selectionArgs, sortOrder, null);
394    }
395
396    /**
397     * <p>
398     * Query the given URI, returning a {@link Cursor} over the result set.
399     * </p>
400     * <p>
401     * For best performance, the caller should follow these guidelines:
402     * <ul>
403     * <li>Provide an explicit projection, to prevent
404     * reading data from storage that aren't going to be used.</li>
405     * <li>Use question mark parameter markers such as 'phone=?' instead of
406     * explicit values in the {@code selection} parameter, so that queries
407     * that differ only by those values will be recognized as the same
408     * for caching purposes.</li>
409     * </ul>
410     * </p>
411     *
412     * @param uri The URI, using the content:// scheme, for the content to
413     *         retrieve.
414     * @param projection A list of which columns to return. Passing null will
415     *         return all columns, which is inefficient.
416     * @param selection A filter declaring which rows to return, formatted as an
417     *         SQL WHERE clause (excluding the WHERE itself). Passing null will
418     *         return all rows for the given URI.
419     * @param selectionArgs You may include ?s in selection, which will be
420     *         replaced by the values from selectionArgs, in the order that they
421     *         appear in the selection. The values will be bound as Strings.
422     * @param sortOrder How to order the rows, formatted as an SQL ORDER BY
423     *         clause (excluding the ORDER BY itself). Passing null will use the
424     *         default sort order, which may be unordered.
425     * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
426     * If the operation is canceled, then {@link OperationCanceledException} will be thrown
427     * when the query is executed.
428     * @return A Cursor object, which is positioned before the first entry, or null
429     * @see Cursor
430     */
431    public final Cursor query(final Uri uri, String[] projection,
432            String selection, String[] selectionArgs, String sortOrder,
433            CancellationSignal cancellationSignal) {
434        IContentProvider unstableProvider = acquireUnstableProvider(uri);
435        if (unstableProvider == null) {
436            return null;
437        }
438        IContentProvider stableProvider = null;
439        Cursor qCursor = null;
440        try {
441            long startTime = SystemClock.uptimeMillis();
442
443            ICancellationSignal remoteCancellationSignal = null;
444            if (cancellationSignal != null) {
445                cancellationSignal.throwIfCanceled();
446                remoteCancellationSignal = unstableProvider.createCancellationSignal();
447                cancellationSignal.setRemote(remoteCancellationSignal);
448            }
449            try {
450                qCursor = unstableProvider.query(mPackageName, uri, projection,
451                        selection, selectionArgs, sortOrder, remoteCancellationSignal);
452            } catch (DeadObjectException e) {
453                // The remote process has died...  but we only hold an unstable
454                // reference though, so we might recover!!!  Let's try!!!!
455                // This is exciting!!1!!1!!!!1
456                unstableProviderDied(unstableProvider);
457                stableProvider = acquireProvider(uri);
458                if (stableProvider == null) {
459                    return null;
460                }
461                qCursor = stableProvider.query(mPackageName, uri, projection,
462                        selection, selectionArgs, sortOrder, remoteCancellationSignal);
463            }
464            if (qCursor == null) {
465                return null;
466            }
467
468            // Force query execution.  Might fail and throw a runtime exception here.
469            qCursor.getCount();
470            long durationMillis = SystemClock.uptimeMillis() - startTime;
471            maybeLogQueryToEventLog(durationMillis, uri, projection, selection, sortOrder);
472
473            // Wrap the cursor object into CursorWrapperInner object.
474            CursorWrapperInner wrapper = new CursorWrapperInner(qCursor,
475                    stableProvider != null ? stableProvider : acquireProvider(uri));
476            stableProvider = null;
477            qCursor = null;
478            return wrapper;
479        } catch (RemoteException e) {
480            // Arbitrary and not worth documenting, as Activity
481            // Manager will kill this process shortly anyway.
482            return null;
483        } finally {
484            if (qCursor != null) {
485                qCursor.close();
486            }
487            if (cancellationSignal != null) {
488                cancellationSignal.setRemote(null);
489            }
490            if (unstableProvider != null) {
491                releaseUnstableProvider(unstableProvider);
492            }
493            if (stableProvider != null) {
494                releaseProvider(stableProvider);
495            }
496        }
497    }
498
499    /**
500     * Transform the given <var>url</var> to a canonical representation of
501     * its referenced resource, which can be used across devices, persisted,
502     * backed up and restored, etc.  The returned Uri is still a fully capable
503     * Uri for use with its content provider, allowing you to do all of the
504     * same content provider operations as with the original Uri --
505     * {@link #query}, {@link #openInputStream(android.net.Uri)}, etc.  The
506     * only difference in behavior between the original and new Uris is that
507     * the content provider may need to do some additional work at each call
508     * using it to resolve it to the correct resource, especially if the
509     * canonical Uri has been moved to a different environment.
510     *
511     * <p>If you are moving a canonical Uri between environments, you should
512     * perform another call to {@link #canonicalize} with that original Uri to
513     * re-canonicalize it for the current environment.  Alternatively, you may
514     * want to use {@link #uncanonicalize} to transform it to a non-canonical
515     * Uri that works only in the current environment but potentially more
516     * efficiently than the canonical representation.</p>
517     *
518     * @param url The {@link Uri} that is to be transformed to a canonical
519     * representation.  Like all resolver calls, the input can be either
520     * a non-canonical or canonical Uri.
521     *
522     * @return Returns the official canonical representation of <var>url</var>,
523     * or null if the content provider does not support a canonical representation
524     * of the given Uri.  Many providers may not support canonicalization of some
525     * or all of their Uris.
526     *
527     * @see #uncanonicalize
528     */
529    public final Uri canonicalize(Uri url) {
530        IContentProvider provider = acquireProvider(url);
531        if (provider == null) {
532            return null;
533        }
534
535        try {
536            return provider.canonicalize(mPackageName, url);
537        } catch (RemoteException e) {
538            // Arbitrary and not worth documenting, as Activity
539            // Manager will kill this process shortly anyway.
540            return null;
541        } finally {
542            releaseProvider(provider);
543        }
544    }
545
546    /**
547     * Given a canonical Uri previously generated by {@link #canonicalize}, convert
548     * it to its local non-canonical form.  This can be useful in some cases where
549     * you know that you will only be using the Uri in the current environment and
550     * want to avoid any possible overhead when using it with the content
551     * provider.
552     *
553     * @param url The canonical {@link Uri} that is to be convered back to its
554     * non-canonical form.
555     *
556     * @return Returns the non-canonical representation of <var>url</var>.  This
557     * function never returns null; if there is no conversion to be done, it returns
558     * the same Uri that was provided.
559     *
560     * @see #canonicalize
561     */
562    public final Uri uncanonicalize(Uri url) {
563        IContentProvider provider = acquireProvider(url);
564        if (provider == null) {
565            return null;
566        }
567
568        try {
569            return provider.uncanonicalize(mPackageName, url);
570        } catch (RemoteException e) {
571            // Arbitrary and not worth documenting, as Activity
572            // Manager will kill this process shortly anyway.
573            return null;
574        } finally {
575            releaseProvider(provider);
576        }
577    }
578
579    /**
580     * Open a stream on to the content associated with a content URI.  If there
581     * is no data associated with the URI, FileNotFoundException is thrown.
582     *
583     * <h5>Accepts the following URI schemes:</h5>
584     * <ul>
585     * <li>content ({@link #SCHEME_CONTENT})</li>
586     * <li>android.resource ({@link #SCHEME_ANDROID_RESOURCE})</li>
587     * <li>file ({@link #SCHEME_FILE})</li>
588     * </ul>
589     *
590     * <p>See {@link #openAssetFileDescriptor(Uri, String)} for more information
591     * on these schemes.
592     *
593     * @param uri The desired URI.
594     * @return InputStream
595     * @throws FileNotFoundException if the provided URI could not be opened.
596     * @see #openAssetFileDescriptor(Uri, String)
597     */
598    public final InputStream openInputStream(Uri uri)
599            throws FileNotFoundException {
600        String scheme = uri.getScheme();
601        if (SCHEME_ANDROID_RESOURCE.equals(scheme)) {
602            // Note: left here to avoid breaking compatibility.  May be removed
603            // with sufficient testing.
604            OpenResourceIdResult r = getResourceId(uri);
605            try {
606                InputStream stream = r.r.openRawResource(r.id);
607                return stream;
608            } catch (Resources.NotFoundException ex) {
609                throw new FileNotFoundException("Resource does not exist: " + uri);
610            }
611        } else if (SCHEME_FILE.equals(scheme)) {
612            // Note: left here to avoid breaking compatibility.  May be removed
613            // with sufficient testing.
614            return new FileInputStream(uri.getPath());
615        } else {
616            AssetFileDescriptor fd = openAssetFileDescriptor(uri, "r", null);
617            try {
618                return fd != null ? fd.createInputStream() : null;
619            } catch (IOException e) {
620                throw new FileNotFoundException("Unable to create stream");
621            }
622        }
623    }
624
625    /**
626     * Synonym for {@link #openOutputStream(Uri, String)
627     * openOutputStream(uri, "w")}.
628     * @throws FileNotFoundException if the provided URI could not be opened.
629     */
630    public final OutputStream openOutputStream(Uri uri)
631            throws FileNotFoundException {
632        return openOutputStream(uri, "w");
633    }
634
635    /**
636     * Open a stream on to the content associated with a content URI.  If there
637     * is no data associated with the URI, FileNotFoundException is thrown.
638     *
639     * <h5>Accepts the following URI schemes:</h5>
640     * <ul>
641     * <li>content ({@link #SCHEME_CONTENT})</li>
642     * <li>file ({@link #SCHEME_FILE})</li>
643     * </ul>
644     *
645     * <p>See {@link #openAssetFileDescriptor(Uri, String)} for more information
646     * on these schemes.
647     *
648     * @param uri The desired URI.
649     * @param mode May be "w", "wa", "rw", or "rwt".
650     * @return OutputStream
651     * @throws FileNotFoundException if the provided URI could not be opened.
652     * @see #openAssetFileDescriptor(Uri, String)
653     */
654    public final OutputStream openOutputStream(Uri uri, String mode)
655            throws FileNotFoundException {
656        AssetFileDescriptor fd = openAssetFileDescriptor(uri, mode, null);
657        try {
658            return fd != null ? fd.createOutputStream() : null;
659        } catch (IOException e) {
660            throw new FileNotFoundException("Unable to create stream");
661        }
662    }
663
664    /**
665     * Open a raw file descriptor to access data under a URI.  This
666     * is like {@link #openAssetFileDescriptor(Uri, String)}, but uses the
667     * underlying {@link ContentProvider#openFile}
668     * ContentProvider.openFile()} method, so will <em>not</em> work with
669     * providers that return sub-sections of files.  If at all possible,
670     * you should use {@link #openAssetFileDescriptor(Uri, String)}.  You
671     * will receive a FileNotFoundException exception if the provider returns a
672     * sub-section of a file.
673     *
674     * <h5>Accepts the following URI schemes:</h5>
675     * <ul>
676     * <li>content ({@link #SCHEME_CONTENT})</li>
677     * <li>file ({@link #SCHEME_FILE})</li>
678     * </ul>
679     *
680     * <p>See {@link #openAssetFileDescriptor(Uri, String)} for more information
681     * on these schemes.
682     * <p>
683     * If opening with the exclusive "r" or "w" modes, the returned
684     * ParcelFileDescriptor could be a pipe or socket pair to enable streaming
685     * of data. Opening with the "rw" mode implies a file on disk that supports
686     * seeking. If possible, always use an exclusive mode to give the underlying
687     * {@link ContentProvider} the most flexibility.
688     * <p>
689     * If you are writing a file, and need to communicate an error to the
690     * provider, use {@link ParcelFileDescriptor#closeWithError(String)}.
691     *
692     * @param uri The desired URI to open.
693     * @param mode The file mode to use, as per {@link ContentProvider#openFile
694     * ContentProvider.openFile}.
695     * @return Returns a new ParcelFileDescriptor pointing to the file.  You
696     * own this descriptor and are responsible for closing it when done.
697     * @throws FileNotFoundException Throws FileNotFoundException if no
698     * file exists under the URI or the mode is invalid.
699     * @see #openAssetFileDescriptor(Uri, String)
700     */
701    public final ParcelFileDescriptor openFileDescriptor(Uri uri, String mode)
702            throws FileNotFoundException {
703        return openFileDescriptor(uri, mode, null);
704    }
705
706    /**
707     * Open a raw file descriptor to access data under a URI.  This
708     * is like {@link #openAssetFileDescriptor(Uri, String)}, but uses the
709     * underlying {@link ContentProvider#openFile}
710     * ContentProvider.openFile()} method, so will <em>not</em> work with
711     * providers that return sub-sections of files.  If at all possible,
712     * you should use {@link #openAssetFileDescriptor(Uri, String)}.  You
713     * will receive a FileNotFoundException exception if the provider returns a
714     * sub-section of a file.
715     *
716     * <h5>Accepts the following URI schemes:</h5>
717     * <ul>
718     * <li>content ({@link #SCHEME_CONTENT})</li>
719     * <li>file ({@link #SCHEME_FILE})</li>
720     * </ul>
721     *
722     * <p>See {@link #openAssetFileDescriptor(Uri, String)} for more information
723     * on these schemes.
724     * <p>
725     * If opening with the exclusive "r" or "w" modes, the returned
726     * ParcelFileDescriptor could be a pipe or socket pair to enable streaming
727     * of data. Opening with the "rw" mode implies a file on disk that supports
728     * seeking. If possible, always use an exclusive mode to give the underlying
729     * {@link ContentProvider} the most flexibility.
730     * <p>
731     * If you are writing a file, and need to communicate an error to the
732     * provider, use {@link ParcelFileDescriptor#closeWithError(String)}.
733     *
734     * @param uri The desired URI to open.
735     * @param mode The file mode to use, as per {@link ContentProvider#openFile
736     * ContentProvider.openFile}.
737     * @param cancellationSignal A signal to cancel the operation in progress,
738     *         or null if none. If the operation is canceled, then
739     *         {@link OperationCanceledException} will be thrown.
740     * @return Returns a new ParcelFileDescriptor pointing to the file.  You
741     * own this descriptor and are responsible for closing it when done.
742     * @throws FileNotFoundException Throws FileNotFoundException if no
743     * file exists under the URI or the mode is invalid.
744     * @see #openAssetFileDescriptor(Uri, String)
745     */
746    public final ParcelFileDescriptor openFileDescriptor(Uri uri,
747            String mode, CancellationSignal cancellationSignal) throws FileNotFoundException {
748        AssetFileDescriptor afd = openAssetFileDescriptor(uri, mode, cancellationSignal);
749        if (afd == null) {
750            return null;
751        }
752
753        if (afd.getDeclaredLength() < 0) {
754            // This is a full file!
755            return afd.getParcelFileDescriptor();
756        }
757
758        // Client can't handle a sub-section of a file, so close what
759        // we got and bail with an exception.
760        try {
761            afd.close();
762        } catch (IOException e) {
763        }
764
765        throw new FileNotFoundException("Not a whole file");
766    }
767
768    /**
769     * Open a raw file descriptor to access data under a URI.  This
770     * interacts with the underlying {@link ContentProvider#openAssetFile}
771     * method of the provider associated with the given URI, to retrieve any file stored there.
772     *
773     * <h5>Accepts the following URI schemes:</h5>
774     * <ul>
775     * <li>content ({@link #SCHEME_CONTENT})</li>
776     * <li>android.resource ({@link #SCHEME_ANDROID_RESOURCE})</li>
777     * <li>file ({@link #SCHEME_FILE})</li>
778     * </ul>
779     * <h5>The android.resource ({@link #SCHEME_ANDROID_RESOURCE}) Scheme</h5>
780     * <p>
781     * A Uri object can be used to reference a resource in an APK file.  The
782     * Uri should be one of the following formats:
783     * <ul>
784     * <li><code>android.resource://package_name/id_number</code><br/>
785     * <code>package_name</code> is your package name as listed in your AndroidManifest.xml.
786     * For example <code>com.example.myapp</code><br/>
787     * <code>id_number</code> is the int form of the ID.<br/>
788     * The easiest way to construct this form is
789     * <pre>Uri uri = Uri.parse("android.resource://com.example.myapp/" + R.raw.my_resource");</pre>
790     * </li>
791     * <li><code>android.resource://package_name/type/name</code><br/>
792     * <code>package_name</code> is your package name as listed in your AndroidManifest.xml.
793     * For example <code>com.example.myapp</code><br/>
794     * <code>type</code> is the string form of the resource type.  For example, <code>raw</code>
795     * or <code>drawable</code>.
796     * <code>name</code> is the string form of the resource name.  That is, whatever the file
797     * name was in your res directory, without the type extension.
798     * The easiest way to construct this form is
799     * <pre>Uri uri = Uri.parse("android.resource://com.example.myapp/raw/my_resource");</pre>
800     * </li>
801     * </ul>
802     *
803     * <p>Note that if this function is called for read-only input (mode is "r")
804     * on a content: URI, it will instead call {@link #openTypedAssetFileDescriptor}
805     * for you with a MIME type of "*\/*".  This allows such callers to benefit
806     * from any built-in data conversion that a provider implements.
807     *
808     * @param uri The desired URI to open.
809     * @param mode The file mode to use, as per {@link ContentProvider#openAssetFile
810     * ContentProvider.openAssetFile}.
811     * @return Returns a new ParcelFileDescriptor pointing to the file.  You
812     * own this descriptor and are responsible for closing it when done.
813     * @throws FileNotFoundException Throws FileNotFoundException of no
814     * file exists under the URI or the mode is invalid.
815     */
816    public final AssetFileDescriptor openAssetFileDescriptor(Uri uri, String mode)
817            throws FileNotFoundException {
818        return openAssetFileDescriptor(uri, mode, null);
819    }
820
821    /**
822     * Open a raw file descriptor to access data under a URI.  This
823     * interacts with the underlying {@link ContentProvider#openAssetFile}
824     * method of the provider associated with the given URI, to retrieve any file stored there.
825     *
826     * <h5>Accepts the following URI schemes:</h5>
827     * <ul>
828     * <li>content ({@link #SCHEME_CONTENT})</li>
829     * <li>android.resource ({@link #SCHEME_ANDROID_RESOURCE})</li>
830     * <li>file ({@link #SCHEME_FILE})</li>
831     * </ul>
832     * <h5>The android.resource ({@link #SCHEME_ANDROID_RESOURCE}) Scheme</h5>
833     * <p>
834     * A Uri object can be used to reference a resource in an APK file.  The
835     * Uri should be one of the following formats:
836     * <ul>
837     * <li><code>android.resource://package_name/id_number</code><br/>
838     * <code>package_name</code> is your package name as listed in your AndroidManifest.xml.
839     * For example <code>com.example.myapp</code><br/>
840     * <code>id_number</code> is the int form of the ID.<br/>
841     * The easiest way to construct this form is
842     * <pre>Uri uri = Uri.parse("android.resource://com.example.myapp/" + R.raw.my_resource");</pre>
843     * </li>
844     * <li><code>android.resource://package_name/type/name</code><br/>
845     * <code>package_name</code> is your package name as listed in your AndroidManifest.xml.
846     * For example <code>com.example.myapp</code><br/>
847     * <code>type</code> is the string form of the resource type.  For example, <code>raw</code>
848     * or <code>drawable</code>.
849     * <code>name</code> is the string form of the resource name.  That is, whatever the file
850     * name was in your res directory, without the type extension.
851     * The easiest way to construct this form is
852     * <pre>Uri uri = Uri.parse("android.resource://com.example.myapp/raw/my_resource");</pre>
853     * </li>
854     * </ul>
855     *
856     * <p>Note that if this function is called for read-only input (mode is "r")
857     * on a content: URI, it will instead call {@link #openTypedAssetFileDescriptor}
858     * for you with a MIME type of "*\/*".  This allows such callers to benefit
859     * from any built-in data conversion that a provider implements.
860     *
861     * @param uri The desired URI to open.
862     * @param mode The file mode to use, as per {@link ContentProvider#openAssetFile
863     * ContentProvider.openAssetFile}.
864     * @param cancellationSignal A signal to cancel the operation in progress, or null if
865     *            none. If the operation is canceled, then
866     *            {@link OperationCanceledException} will be thrown.
867     * @return Returns a new ParcelFileDescriptor pointing to the file.  You
868     * own this descriptor and are responsible for closing it when done.
869     * @throws FileNotFoundException Throws FileNotFoundException of no
870     * file exists under the URI or the mode is invalid.
871     */
872    public final AssetFileDescriptor openAssetFileDescriptor(Uri uri,
873            String mode, CancellationSignal cancellationSignal) throws FileNotFoundException {
874        String scheme = uri.getScheme();
875        if (SCHEME_ANDROID_RESOURCE.equals(scheme)) {
876            if (!"r".equals(mode)) {
877                throw new FileNotFoundException("Can't write resources: " + uri);
878            }
879            OpenResourceIdResult r = getResourceId(uri);
880            try {
881                return r.r.openRawResourceFd(r.id);
882            } catch (Resources.NotFoundException ex) {
883                throw new FileNotFoundException("Resource does not exist: " + uri);
884            }
885        } else if (SCHEME_FILE.equals(scheme)) {
886            ParcelFileDescriptor pfd = ParcelFileDescriptor.open(
887                    new File(uri.getPath()), modeToMode(uri, mode));
888            return new AssetFileDescriptor(pfd, 0, -1);
889        } else {
890            if ("r".equals(mode)) {
891                return openTypedAssetFileDescriptor(uri, "*/*", null, cancellationSignal);
892            } else {
893                IContentProvider unstableProvider = acquireUnstableProvider(uri);
894                if (unstableProvider == null) {
895                    throw new FileNotFoundException("No content provider: " + uri);
896                }
897                IContentProvider stableProvider = null;
898                AssetFileDescriptor fd = null;
899
900                try {
901                    ICancellationSignal remoteCancellationSignal = null;
902                    if (cancellationSignal != null) {
903                        cancellationSignal.throwIfCanceled();
904                        remoteCancellationSignal = unstableProvider.createCancellationSignal();
905                        cancellationSignal.setRemote(remoteCancellationSignal);
906                    }
907
908                    try {
909                        fd = unstableProvider.openAssetFile(
910                                mPackageName, uri, mode, remoteCancellationSignal);
911                        if (fd == null) {
912                            // The provider will be released by the finally{} clause
913                            return null;
914                        }
915                    } catch (DeadObjectException e) {
916                        // The remote process has died...  but we only hold an unstable
917                        // reference though, so we might recover!!!  Let's try!!!!
918                        // This is exciting!!1!!1!!!!1
919                        unstableProviderDied(unstableProvider);
920                        stableProvider = acquireProvider(uri);
921                        if (stableProvider == null) {
922                            throw new FileNotFoundException("No content provider: " + uri);
923                        }
924                        fd = stableProvider.openAssetFile(
925                                mPackageName, uri, mode, remoteCancellationSignal);
926                        if (fd == null) {
927                            // The provider will be released by the finally{} clause
928                            return null;
929                        }
930                    }
931
932                    if (stableProvider == null) {
933                        stableProvider = acquireProvider(uri);
934                    }
935                    releaseUnstableProvider(unstableProvider);
936                    ParcelFileDescriptor pfd = new ParcelFileDescriptorInner(
937                            fd.getParcelFileDescriptor(), stableProvider);
938
939                    // Success!  Don't release the provider when exiting, let
940                    // ParcelFileDescriptorInner do that when it is closed.
941                    stableProvider = null;
942
943                    return new AssetFileDescriptor(pfd, fd.getStartOffset(),
944                            fd.getDeclaredLength());
945
946                } catch (RemoteException e) {
947                    // Whatever, whatever, we'll go away.
948                    throw new FileNotFoundException(
949                            "Failed opening content provider: " + uri);
950                } catch (FileNotFoundException e) {
951                    throw e;
952                } finally {
953                    if (cancellationSignal != null) {
954                        cancellationSignal.setRemote(null);
955                    }
956                    if (stableProvider != null) {
957                        releaseProvider(stableProvider);
958                    }
959                    if (unstableProvider != null) {
960                        releaseUnstableProvider(unstableProvider);
961                    }
962                }
963            }
964        }
965    }
966
967    /**
968     * Open a raw file descriptor to access (potentially type transformed)
969     * data from a "content:" URI.  This interacts with the underlying
970     * {@link ContentProvider#openTypedAssetFile} method of the provider
971     * associated with the given URI, to retrieve retrieve any appropriate
972     * data stream for the data stored there.
973     *
974     * <p>Unlike {@link #openAssetFileDescriptor}, this function only works
975     * with "content:" URIs, because content providers are the only facility
976     * with an associated MIME type to ensure that the returned data stream
977     * is of the desired type.
978     *
979     * <p>All text/* streams are encoded in UTF-8.
980     *
981     * @param uri The desired URI to open.
982     * @param mimeType The desired MIME type of the returned data.  This can
983     * be a pattern such as *\/*, which will allow the content provider to
984     * select a type, though there is no way for you to determine what type
985     * it is returning.
986     * @param opts Additional provider-dependent options.
987     * @return Returns a new ParcelFileDescriptor from which you can read the
988     * data stream from the provider.  Note that this may be a pipe, meaning
989     * you can't seek in it.  The only seek you should do is if the
990     * AssetFileDescriptor contains an offset, to move to that offset before
991     * reading.  You own this descriptor and are responsible for closing it when done.
992     * @throws FileNotFoundException Throws FileNotFoundException of no
993     * data of the desired type exists under the URI.
994     */
995    public final AssetFileDescriptor openTypedAssetFileDescriptor(
996            Uri uri, String mimeType, Bundle opts) throws FileNotFoundException {
997        return openTypedAssetFileDescriptor(uri, mimeType, opts, null);
998    }
999
1000    /**
1001     * Open a raw file descriptor to access (potentially type transformed)
1002     * data from a "content:" URI.  This interacts with the underlying
1003     * {@link ContentProvider#openTypedAssetFile} method of the provider
1004     * associated with the given URI, to retrieve retrieve any appropriate
1005     * data stream for the data stored there.
1006     *
1007     * <p>Unlike {@link #openAssetFileDescriptor}, this function only works
1008     * with "content:" URIs, because content providers are the only facility
1009     * with an associated MIME type to ensure that the returned data stream
1010     * is of the desired type.
1011     *
1012     * <p>All text/* streams are encoded in UTF-8.
1013     *
1014     * @param uri The desired URI to open.
1015     * @param mimeType The desired MIME type of the returned data.  This can
1016     * be a pattern such as *\/*, which will allow the content provider to
1017     * select a type, though there is no way for you to determine what type
1018     * it is returning.
1019     * @param opts Additional provider-dependent options.
1020     * @param cancellationSignal A signal to cancel the operation in progress,
1021     *         or null if none. If the operation is canceled, then
1022     *         {@link OperationCanceledException} will be thrown.
1023     * @return Returns a new ParcelFileDescriptor from which you can read the
1024     * data stream from the provider.  Note that this may be a pipe, meaning
1025     * you can't seek in it.  The only seek you should do is if the
1026     * AssetFileDescriptor contains an offset, to move to that offset before
1027     * reading.  You own this descriptor and are responsible for closing it when done.
1028     * @throws FileNotFoundException Throws FileNotFoundException of no
1029     * data of the desired type exists under the URI.
1030     */
1031    public final AssetFileDescriptor openTypedAssetFileDescriptor(Uri uri,
1032            String mimeType, Bundle opts, CancellationSignal cancellationSignal)
1033            throws FileNotFoundException {
1034        IContentProvider unstableProvider = acquireUnstableProvider(uri);
1035        if (unstableProvider == null) {
1036            throw new FileNotFoundException("No content provider: " + uri);
1037        }
1038        IContentProvider stableProvider = null;
1039        AssetFileDescriptor fd = null;
1040
1041        try {
1042            ICancellationSignal remoteCancellationSignal = null;
1043            if (cancellationSignal != null) {
1044                cancellationSignal.throwIfCanceled();
1045                remoteCancellationSignal = unstableProvider.createCancellationSignal();
1046                cancellationSignal.setRemote(remoteCancellationSignal);
1047            }
1048
1049            try {
1050                fd = unstableProvider.openTypedAssetFile(
1051                        mPackageName, uri, mimeType, opts, remoteCancellationSignal);
1052                if (fd == null) {
1053                    // The provider will be released by the finally{} clause
1054                    return null;
1055                }
1056            } catch (DeadObjectException e) {
1057                // The remote process has died...  but we only hold an unstable
1058                // reference though, so we might recover!!!  Let's try!!!!
1059                // This is exciting!!1!!1!!!!1
1060                unstableProviderDied(unstableProvider);
1061                stableProvider = acquireProvider(uri);
1062                if (stableProvider == null) {
1063                    throw new FileNotFoundException("No content provider: " + uri);
1064                }
1065                fd = stableProvider.openTypedAssetFile(
1066                        mPackageName, uri, mimeType, opts, remoteCancellationSignal);
1067                if (fd == null) {
1068                    // The provider will be released by the finally{} clause
1069                    return null;
1070                }
1071            }
1072
1073            if (stableProvider == null) {
1074                stableProvider = acquireProvider(uri);
1075            }
1076            releaseUnstableProvider(unstableProvider);
1077            ParcelFileDescriptor pfd = new ParcelFileDescriptorInner(
1078                    fd.getParcelFileDescriptor(), stableProvider);
1079
1080            // Success!  Don't release the provider when exiting, let
1081            // ParcelFileDescriptorInner do that when it is closed.
1082            stableProvider = null;
1083
1084            return new AssetFileDescriptor(pfd, fd.getStartOffset(),
1085                    fd.getDeclaredLength());
1086
1087        } catch (RemoteException e) {
1088            // Whatever, whatever, we'll go away.
1089            throw new FileNotFoundException(
1090                    "Failed opening content provider: " + uri);
1091        } catch (FileNotFoundException e) {
1092            throw e;
1093        } finally {
1094            if (cancellationSignal != null) {
1095                cancellationSignal.setRemote(null);
1096            }
1097            if (stableProvider != null) {
1098                releaseProvider(stableProvider);
1099            }
1100            if (unstableProvider != null) {
1101                releaseUnstableProvider(unstableProvider);
1102            }
1103        }
1104    }
1105
1106    /**
1107     * A resource identified by the {@link Resources} that contains it, and a resource id.
1108     *
1109     * @hide
1110     */
1111    public class OpenResourceIdResult {
1112        public Resources r;
1113        public int id;
1114    }
1115
1116    /**
1117     * Resolves an android.resource URI to a {@link Resources} and a resource id.
1118     *
1119     * @hide
1120     */
1121    public OpenResourceIdResult getResourceId(Uri uri) throws FileNotFoundException {
1122        String authority = uri.getAuthority();
1123        Resources r;
1124        if (TextUtils.isEmpty(authority)) {
1125            throw new FileNotFoundException("No authority: " + uri);
1126        } else {
1127            try {
1128                r = mContext.getPackageManager().getResourcesForApplication(authority);
1129            } catch (NameNotFoundException ex) {
1130                throw new FileNotFoundException("No package found for authority: " + uri);
1131            }
1132        }
1133        List<String> path = uri.getPathSegments();
1134        if (path == null) {
1135            throw new FileNotFoundException("No path: " + uri);
1136        }
1137        int len = path.size();
1138        int id;
1139        if (len == 1) {
1140            try {
1141                id = Integer.parseInt(path.get(0));
1142            } catch (NumberFormatException e) {
1143                throw new FileNotFoundException("Single path segment is not a resource ID: " + uri);
1144            }
1145        } else if (len == 2) {
1146            id = r.getIdentifier(path.get(1), path.get(0), authority);
1147        } else {
1148            throw new FileNotFoundException("More than two path segments: " + uri);
1149        }
1150        if (id == 0) {
1151            throw new FileNotFoundException("No resource found for: " + uri);
1152        }
1153        OpenResourceIdResult res = new OpenResourceIdResult();
1154        res.r = r;
1155        res.id = id;
1156        return res;
1157    }
1158
1159    /** @hide */
1160    static public int modeToMode(Uri uri, String mode) throws FileNotFoundException {
1161        int modeBits;
1162        if ("r".equals(mode)) {
1163            modeBits = ParcelFileDescriptor.MODE_READ_ONLY;
1164        } else if ("w".equals(mode) || "wt".equals(mode)) {
1165            modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
1166                    | ParcelFileDescriptor.MODE_CREATE
1167                    | ParcelFileDescriptor.MODE_TRUNCATE;
1168        } else if ("wa".equals(mode)) {
1169            modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY
1170                    | ParcelFileDescriptor.MODE_CREATE
1171                    | ParcelFileDescriptor.MODE_APPEND;
1172        } else if ("rw".equals(mode)) {
1173            modeBits = ParcelFileDescriptor.MODE_READ_WRITE
1174                    | ParcelFileDescriptor.MODE_CREATE;
1175        } else if ("rwt".equals(mode)) {
1176            modeBits = ParcelFileDescriptor.MODE_READ_WRITE
1177                    | ParcelFileDescriptor.MODE_CREATE
1178                    | ParcelFileDescriptor.MODE_TRUNCATE;
1179        } else {
1180            throw new FileNotFoundException("Bad mode for " + uri + ": "
1181                    + mode);
1182        }
1183        return modeBits;
1184    }
1185
1186    /**
1187     * Inserts a row into a table at the given URL.
1188     *
1189     * If the content provider supports transactions the insertion will be atomic.
1190     *
1191     * @param url The URL of the table to insert into.
1192     * @param values The initial values for the newly inserted row. The key is the column name for
1193     *               the field. Passing an empty ContentValues will create an empty row.
1194     * @return the URL of the newly created row.
1195     */
1196    public final Uri insert(Uri url, ContentValues values)
1197    {
1198        IContentProvider provider = acquireProvider(url);
1199        if (provider == null) {
1200            throw new IllegalArgumentException("Unknown URL " + url);
1201        }
1202        try {
1203            long startTime = SystemClock.uptimeMillis();
1204            Uri createdRow = provider.insert(mPackageName, url, values);
1205            long durationMillis = SystemClock.uptimeMillis() - startTime;
1206            maybeLogUpdateToEventLog(durationMillis, url, "insert", null /* where */);
1207            return createdRow;
1208        } catch (RemoteException e) {
1209            // Arbitrary and not worth documenting, as Activity
1210            // Manager will kill this process shortly anyway.
1211            return null;
1212        } finally {
1213            releaseProvider(provider);
1214        }
1215    }
1216
1217    /**
1218     * Applies each of the {@link ContentProviderOperation} objects and returns an array
1219     * of their results. Passes through OperationApplicationException, which may be thrown
1220     * by the call to {@link ContentProviderOperation#apply}.
1221     * If all the applications succeed then a {@link ContentProviderResult} array with the
1222     * same number of elements as the operations will be returned. It is implementation-specific
1223     * how many, if any, operations will have been successfully applied if a call to
1224     * apply results in a {@link OperationApplicationException}.
1225     * @param authority the authority of the ContentProvider to which this batch should be applied
1226     * @param operations the operations to apply
1227     * @return the results of the applications
1228     * @throws OperationApplicationException thrown if an application fails.
1229     * See {@link ContentProviderOperation#apply} for more information.
1230     * @throws RemoteException thrown if a RemoteException is encountered while attempting
1231     *   to communicate with a remote provider.
1232     */
1233    public ContentProviderResult[] applyBatch(String authority,
1234            ArrayList<ContentProviderOperation> operations)
1235            throws RemoteException, OperationApplicationException {
1236        ContentProviderClient provider = acquireContentProviderClient(authority);
1237        if (provider == null) {
1238            throw new IllegalArgumentException("Unknown authority " + authority);
1239        }
1240        try {
1241            return provider.applyBatch(operations);
1242        } finally {
1243            provider.release();
1244        }
1245    }
1246
1247    /**
1248     * Inserts multiple rows into a table at the given URL.
1249     *
1250     * This function make no guarantees about the atomicity of the insertions.
1251     *
1252     * @param url The URL of the table to insert into.
1253     * @param values The initial values for the newly inserted rows. The key is the column name for
1254     *               the field. Passing null will create an empty row.
1255     * @return the number of newly created rows.
1256     */
1257    public final int bulkInsert(Uri url, ContentValues[] values)
1258    {
1259        IContentProvider provider = acquireProvider(url);
1260        if (provider == null) {
1261            throw new IllegalArgumentException("Unknown URL " + url);
1262        }
1263        try {
1264            long startTime = SystemClock.uptimeMillis();
1265            int rowsCreated = provider.bulkInsert(mPackageName, url, values);
1266            long durationMillis = SystemClock.uptimeMillis() - startTime;
1267            maybeLogUpdateToEventLog(durationMillis, url, "bulkinsert", null /* where */);
1268            return rowsCreated;
1269        } catch (RemoteException e) {
1270            // Arbitrary and not worth documenting, as Activity
1271            // Manager will kill this process shortly anyway.
1272            return 0;
1273        } finally {
1274            releaseProvider(provider);
1275        }
1276    }
1277
1278    /**
1279     * Deletes row(s) specified by a content URI.
1280     *
1281     * If the content provider supports transactions, the deletion will be atomic.
1282     *
1283     * @param url The URL of the row to delete.
1284     * @param where A filter to apply to rows before deleting, formatted as an SQL WHERE clause
1285                    (excluding the WHERE itself).
1286     * @return The number of rows deleted.
1287     */
1288    public final int delete(Uri url, String where, String[] selectionArgs)
1289    {
1290        IContentProvider provider = acquireProvider(url);
1291        if (provider == null) {
1292            throw new IllegalArgumentException("Unknown URL " + url);
1293        }
1294        try {
1295            long startTime = SystemClock.uptimeMillis();
1296            int rowsDeleted = provider.delete(mPackageName, url, where, selectionArgs);
1297            long durationMillis = SystemClock.uptimeMillis() - startTime;
1298            maybeLogUpdateToEventLog(durationMillis, url, "delete", where);
1299            return rowsDeleted;
1300        } catch (RemoteException e) {
1301            // Arbitrary and not worth documenting, as Activity
1302            // Manager will kill this process shortly anyway.
1303            return -1;
1304        } finally {
1305            releaseProvider(provider);
1306        }
1307    }
1308
1309    /**
1310     * Update row(s) in a content URI.
1311     *
1312     * If the content provider supports transactions the update will be atomic.
1313     *
1314     * @param uri The URI to modify.
1315     * @param values The new field values. The key is the column name for the field.
1316                     A null value will remove an existing field value.
1317     * @param where A filter to apply to rows before updating, formatted as an SQL WHERE clause
1318                    (excluding the WHERE itself).
1319     * @return the number of rows updated.
1320     * @throws NullPointerException if uri or values are null
1321     */
1322    public final int update(Uri uri, ContentValues values, String where,
1323            String[] selectionArgs) {
1324        IContentProvider provider = acquireProvider(uri);
1325        if (provider == null) {
1326            throw new IllegalArgumentException("Unknown URI " + uri);
1327        }
1328        try {
1329            long startTime = SystemClock.uptimeMillis();
1330            int rowsUpdated = provider.update(mPackageName, uri, values, where, selectionArgs);
1331            long durationMillis = SystemClock.uptimeMillis() - startTime;
1332            maybeLogUpdateToEventLog(durationMillis, uri, "update", where);
1333            return rowsUpdated;
1334        } catch (RemoteException e) {
1335            // Arbitrary and not worth documenting, as Activity
1336            // Manager will kill this process shortly anyway.
1337            return -1;
1338        } finally {
1339            releaseProvider(provider);
1340        }
1341    }
1342
1343    /**
1344     * Call a provider-defined method.  This can be used to implement
1345     * read or write interfaces which are cheaper than using a Cursor and/or
1346     * do not fit into the traditional table model.
1347     *
1348     * @param method provider-defined method name to call.  Opaque to
1349     *   framework, but must be non-null.
1350     * @param arg provider-defined String argument.  May be null.
1351     * @param extras provider-defined Bundle argument.  May be null.
1352     * @return a result Bundle, possibly null.  Will be null if the ContentProvider
1353     *   does not implement call.
1354     * @throws NullPointerException if uri or method is null
1355     * @throws IllegalArgumentException if uri is not known
1356     */
1357    public final Bundle call(Uri uri, String method, String arg, Bundle extras) {
1358        if (uri == null) {
1359            throw new NullPointerException("uri == null");
1360        }
1361        if (method == null) {
1362            throw new NullPointerException("method == null");
1363        }
1364        IContentProvider provider = acquireProvider(uri);
1365        if (provider == null) {
1366            throw new IllegalArgumentException("Unknown URI " + uri);
1367        }
1368        try {
1369            return provider.call(mPackageName, method, arg, extras);
1370        } catch (RemoteException e) {
1371            // Arbitrary and not worth documenting, as Activity
1372            // Manager will kill this process shortly anyway.
1373            return null;
1374        } finally {
1375            releaseProvider(provider);
1376        }
1377    }
1378
1379    /**
1380     * Returns the content provider for the given content URI.
1381     *
1382     * @param uri The URI to a content provider
1383     * @return The ContentProvider for the given URI, or null if no content provider is found.
1384     * @hide
1385     */
1386    public final IContentProvider acquireProvider(Uri uri) {
1387        if (!SCHEME_CONTENT.equals(uri.getScheme())) {
1388            return null;
1389        }
1390        final String auth = uri.getAuthority();
1391        if (auth != null) {
1392            return acquireProvider(mContext, auth);
1393        }
1394        return null;
1395    }
1396
1397    /**
1398     * Returns the content provider for the given content URI if the process
1399     * already has a reference on it.
1400     *
1401     * @param uri The URI to a content provider
1402     * @return The ContentProvider for the given URI, or null if no content provider is found.
1403     * @hide
1404     */
1405    public final IContentProvider acquireExistingProvider(Uri uri) {
1406        if (!SCHEME_CONTENT.equals(uri.getScheme())) {
1407            return null;
1408        }
1409        final String auth = uri.getAuthority();
1410        if (auth != null) {
1411            return acquireExistingProvider(mContext, auth);
1412        }
1413        return null;
1414    }
1415
1416    /**
1417     * @hide
1418     */
1419    public final IContentProvider acquireProvider(String name) {
1420        if (name == null) {
1421            return null;
1422        }
1423        return acquireProvider(mContext, name);
1424    }
1425
1426    /**
1427     * Returns the content provider for the given content URI.
1428     *
1429     * @param uri The URI to a content provider
1430     * @return The ContentProvider for the given URI, or null if no content provider is found.
1431     * @hide
1432     */
1433    public final IContentProvider acquireUnstableProvider(Uri uri) {
1434        if (!SCHEME_CONTENT.equals(uri.getScheme())) {
1435            return null;
1436        }
1437        String auth = uri.getAuthority();
1438        if (auth != null) {
1439            return acquireUnstableProvider(mContext, uri.getAuthority());
1440        }
1441        return null;
1442    }
1443
1444    /**
1445     * @hide
1446     */
1447    public final IContentProvider acquireUnstableProvider(String name) {
1448        if (name == null) {
1449            return null;
1450        }
1451        return acquireUnstableProvider(mContext, name);
1452    }
1453
1454    /**
1455     * Returns a {@link ContentProviderClient} that is associated with the {@link ContentProvider}
1456     * that services the content at uri, starting the provider if necessary. Returns
1457     * null if there is no provider associated wih the uri. The caller must indicate that they are
1458     * done with the provider by calling {@link ContentProviderClient#release} which will allow
1459     * the system to release the provider it it determines that there is no other reason for
1460     * keeping it active.
1461     * @param uri specifies which provider should be acquired
1462     * @return a {@link ContentProviderClient} that is associated with the {@link ContentProvider}
1463     * that services the content at uri or null if there isn't one.
1464     */
1465    public final ContentProviderClient acquireContentProviderClient(Uri uri) {
1466        IContentProvider provider = acquireProvider(uri);
1467        if (provider != null) {
1468            return new ContentProviderClient(this, provider, true);
1469        }
1470
1471        return null;
1472    }
1473
1474    /**
1475     * Returns a {@link ContentProviderClient} that is associated with the {@link ContentProvider}
1476     * with the authority of name, starting the provider if necessary. Returns
1477     * null if there is no provider associated wih the uri. The caller must indicate that they are
1478     * done with the provider by calling {@link ContentProviderClient#release} which will allow
1479     * the system to release the provider it it determines that there is no other reason for
1480     * keeping it active.
1481     * @param name specifies which provider should be acquired
1482     * @return a {@link ContentProviderClient} that is associated with the {@link ContentProvider}
1483     * with the authority of name or null if there isn't one.
1484     */
1485    public final ContentProviderClient acquireContentProviderClient(String name) {
1486        IContentProvider provider = acquireProvider(name);
1487        if (provider != null) {
1488            return new ContentProviderClient(this, provider, true);
1489        }
1490
1491        return null;
1492    }
1493
1494    /**
1495     * Like {@link #acquireContentProviderClient(Uri)}, but for use when you do
1496     * not trust the stability of the target content provider.  This turns off
1497     * the mechanism in the platform clean up processes that are dependent on
1498     * a content provider if that content provider's process goes away.  Normally
1499     * you can safely assume that once you have acquired a provider, you can freely
1500     * use it as needed and it won't disappear, even if your process is in the
1501     * background.  If using this method, you need to take care to deal with any
1502     * failures when communicating with the provider, and be sure to close it
1503     * so that it can be re-opened later.  In particular, catching a
1504     * {@link android.os.DeadObjectException} from the calls there will let you
1505     * know that the content provider has gone away; at that point the current
1506     * ContentProviderClient object is invalid, and you should release it.  You
1507     * can acquire a new one if you would like to try to restart the provider
1508     * and perform new operations on it.
1509     */
1510    public final ContentProviderClient acquireUnstableContentProviderClient(Uri uri) {
1511        IContentProvider provider = acquireUnstableProvider(uri);
1512        if (provider != null) {
1513            return new ContentProviderClient(this, provider, false);
1514        }
1515
1516        return null;
1517    }
1518
1519    /**
1520     * Like {@link #acquireContentProviderClient(String)}, but for use when you do
1521     * not trust the stability of the target content provider.  This turns off
1522     * the mechanism in the platform clean up processes that are dependent on
1523     * a content provider if that content provider's process goes away.  Normally
1524     * you can safely assume that once you have acquired a provider, you can freely
1525     * use it as needed and it won't disappear, even if your process is in the
1526     * background.  If using this method, you need to take care to deal with any
1527     * failures when communicating with the provider, and be sure to close it
1528     * so that it can be re-opened later.  In particular, catching a
1529     * {@link android.os.DeadObjectException} from the calls there will let you
1530     * know that the content provider has gone away; at that point the current
1531     * ContentProviderClient object is invalid, and you should release it.  You
1532     * can acquire a new one if you would like to try to restart the provider
1533     * and perform new operations on it.
1534     */
1535    public final ContentProviderClient acquireUnstableContentProviderClient(String name) {
1536        IContentProvider provider = acquireUnstableProvider(name);
1537        if (provider != null) {
1538            return new ContentProviderClient(this, provider, false);
1539        }
1540
1541        return null;
1542    }
1543
1544    /**
1545     * Register an observer class that gets callbacks when data identified by a
1546     * given content URI changes.
1547     *
1548     * @param uri The URI to watch for changes. This can be a specific row URI, or a base URI
1549     * for a whole class of content.
1550     * @param notifyForDescendents If <code>true</code> changes to URIs beginning with <code>uri</code>
1551     * will also cause notifications to be sent. If <code>false</code> only changes to the exact URI
1552     * specified by <em>uri</em> will cause notifications to be sent. If true, than any URI values
1553     * at or below the specified URI will also trigger a match.
1554     * @param observer The object that receives callbacks when changes occur.
1555     * @see #unregisterContentObserver
1556     */
1557    public final void registerContentObserver(Uri uri, boolean notifyForDescendents,
1558            ContentObserver observer)
1559    {
1560        registerContentObserver(uri, notifyForDescendents, observer, UserHandle.myUserId());
1561    }
1562
1563    /** @hide - designated user version */
1564    public final void registerContentObserver(Uri uri, boolean notifyForDescendents,
1565            ContentObserver observer, int userHandle)
1566    {
1567        try {
1568            getContentService().registerContentObserver(uri, notifyForDescendents,
1569                    observer.getContentObserver(), userHandle);
1570        } catch (RemoteException e) {
1571        }
1572    }
1573
1574    /**
1575     * Unregisters a change observer.
1576     *
1577     * @param observer The previously registered observer that is no longer needed.
1578     * @see #registerContentObserver
1579     */
1580    public final void unregisterContentObserver(ContentObserver observer) {
1581        try {
1582            IContentObserver contentObserver = observer.releaseContentObserver();
1583            if (contentObserver != null) {
1584                getContentService().unregisterContentObserver(
1585                        contentObserver);
1586            }
1587        } catch (RemoteException e) {
1588        }
1589    }
1590
1591    /**
1592     * Notify registered observers that a row was updated and attempt to sync changes
1593     * to the network.
1594     * To register, call {@link #registerContentObserver(android.net.Uri , boolean, android.database.ContentObserver) registerContentObserver()}.
1595     * By default, CursorAdapter objects will get this notification.
1596     *
1597     * @param uri The uri of the content that was changed.
1598     * @param observer The observer that originated the change, may be <code>null</null>.
1599     * The observer that originated the change will only receive the notification if it
1600     * has requested to receive self-change notifications by implementing
1601     * {@link ContentObserver#deliverSelfNotifications()} to return true.
1602     */
1603    public void notifyChange(Uri uri, ContentObserver observer) {
1604        notifyChange(uri, observer, true /* sync to network */);
1605    }
1606
1607    /**
1608     * Notify registered observers that a row was updated.
1609     * To register, call {@link #registerContentObserver(android.net.Uri , boolean, android.database.ContentObserver) registerContentObserver()}.
1610     * By default, CursorAdapter objects will get this notification.
1611     * If syncToNetwork is true, this will attempt to schedule a local sync using the sync
1612     * adapter that's registered for the authority of the provided uri. No account will be
1613     * passed to the sync adapter, so all matching accounts will be synchronized.
1614     *
1615     * @param uri The uri of the content that was changed.
1616     * @param observer The observer that originated the change, may be <code>null</null>.
1617     * The observer that originated the change will only receive the notification if it
1618     * has requested to receive self-change notifications by implementing
1619     * {@link ContentObserver#deliverSelfNotifications()} to return true.
1620     * @param syncToNetwork If true, attempt to sync the change to the network.
1621     * @see #requestSync(android.accounts.Account, String, android.os.Bundle)
1622     */
1623    public void notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork) {
1624        notifyChange(uri, observer, syncToNetwork, UserHandle.getCallingUserId());
1625    }
1626
1627    /**
1628     * Notify registered observers within the designated user(s) that a row was updated.
1629     *
1630     * @hide
1631     */
1632    public void notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork,
1633            int userHandle) {
1634        try {
1635            getContentService().notifyChange(
1636                    uri, observer == null ? null : observer.getContentObserver(),
1637                    observer != null && observer.deliverSelfNotifications(), syncToNetwork,
1638                    userHandle);
1639        } catch (RemoteException e) {
1640        }
1641    }
1642
1643    /**
1644     * Return list of all Uri permissions that have been granted <em>to</em> the
1645     * calling package, and which exactly match the requested flags. For
1646     * example, to return all Uris that the calling application has
1647     * <em>non-persistent</em> read access to:
1648     *
1649     * <pre class="prettyprint">
1650     * getIncomingUriPermissionGrants(Intent.FLAG_GRANT_READ_URI_PERMISSION,
1651     *         Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_PERSIST_GRANT_URI_PERMISSION);
1652     * </pre>
1653     *
1654     * @param modeFlags any combination of
1655     *            {@link Intent#FLAG_GRANT_READ_URI_PERMISSION},
1656     *            {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}, or
1657     *            {@link Intent#FLAG_PERSIST_GRANT_URI_PERMISSION}.
1658     * @param modeMask mask indicating which flags must match.
1659     */
1660    public Uri[] getIncomingUriPermissionGrants(int modeFlags, int modeMask) {
1661        try {
1662            return ActivityManagerNative.getDefault()
1663                    .getGrantedUriPermissions(null, getPackageName(), modeFlags, modeMask);
1664        } catch (RemoteException e) {
1665            return new Uri[0];
1666        }
1667    }
1668
1669    /**
1670     * Return list of all Uri permissions that have been granted <em>from</em> the
1671     * calling package, and which exactly match the requested flags. For
1672     * example, to return all Uris that the calling application has granted
1673     * <em>non-persistent</em> read access to:
1674     *
1675     * <pre class="prettyprint">
1676     * getOutgoingUriPermissionGrants(Intent.FLAG_GRANT_READ_URI_PERMISSION,
1677     *         Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_PERSIST_GRANT_URI_PERMISSION);
1678     * </pre>
1679     *
1680     * @param modeFlags any combination of
1681     *            {@link Intent#FLAG_GRANT_READ_URI_PERMISSION},
1682     *            {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION}, or
1683     *            {@link Intent#FLAG_PERSIST_GRANT_URI_PERMISSION}.
1684     * @param modeMask mask indicating which flags must match.
1685     */
1686    public Uri[] getOutgoingUriPermissionGrants(int modeFlags, int modeMask) {
1687        try {
1688            return ActivityManagerNative.getDefault()
1689                    .getGrantedUriPermissions(getPackageName(), null, modeFlags, modeMask);
1690        } catch (RemoteException e) {
1691            return new Uri[0];
1692        }
1693    }
1694
1695    /**
1696     * Start an asynchronous sync operation. If you want to monitor the progress
1697     * of the sync you may register a SyncObserver. Only values of the following
1698     * types may be used in the extras bundle:
1699     * <ul>
1700     * <li>Integer</li>
1701     * <li>Long</li>
1702     * <li>Boolean</li>
1703     * <li>Float</li>
1704     * <li>Double</li>
1705     * <li>String</li>
1706     * <li>Account</li>
1707     * <li>null</li>
1708     * </ul>
1709     *
1710     * @param uri the uri of the provider to sync or null to sync all providers.
1711     * @param extras any extras to pass to the SyncAdapter.
1712     * @deprecated instead use
1713     * {@link #requestSync(android.accounts.Account, String, android.os.Bundle)}
1714     */
1715    @Deprecated
1716    public void startSync(Uri uri, Bundle extras) {
1717        Account account = null;
1718        if (extras != null) {
1719            String accountName = extras.getString(SYNC_EXTRAS_ACCOUNT);
1720            if (!TextUtils.isEmpty(accountName)) {
1721                account = new Account(accountName, "com.google");
1722            }
1723            extras.remove(SYNC_EXTRAS_ACCOUNT);
1724        }
1725        requestSync(account, uri != null ? uri.getAuthority() : null, extras);
1726    }
1727
1728    /**
1729     * Start an asynchronous sync operation. If you want to monitor the progress
1730     * of the sync you may register a SyncObserver. Only values of the following
1731     * types may be used in the extras bundle:
1732     * <ul>
1733     * <li>Integer</li>
1734     * <li>Long</li>
1735     * <li>Boolean</li>
1736     * <li>Float</li>
1737     * <li>Double</li>
1738     * <li>String</li>
1739     * <li>Account</li>
1740     * <li>null</li>
1741     * </ul>
1742     *
1743     * @param account which account should be synced
1744     * @param authority which authority should be synced
1745     * @param extras any extras to pass to the SyncAdapter.
1746     */
1747    public static void requestSync(Account account, String authority, Bundle extras) {
1748        SyncRequest request =
1749            new SyncRequest.Builder()
1750                .setSyncAdapter(account, authority)
1751                .setExtras(extras)
1752                .syncOnce()
1753                .build();
1754        requestSync(request);
1755    }
1756
1757    /**
1758     * Register a sync with the SyncManager. These requests are built using the
1759     * {@link SyncRequest.Builder}.
1760     *
1761     * @param request The immutable SyncRequest object containing the sync parameters. Use
1762     * {@link SyncRequest.Builder} to construct these.
1763     */
1764    public static void requestSync(SyncRequest request) {
1765        try {
1766            getContentService().sync(request);
1767        } catch(RemoteException e) {
1768            // Shouldn't happen.
1769        }
1770    }
1771
1772    /**
1773     * Check that only values of the following types are in the Bundle:
1774     * <ul>
1775     * <li>Integer</li>
1776     * <li>Long</li>
1777     * <li>Boolean</li>
1778     * <li>Float</li>
1779     * <li>Double</li>
1780     * <li>String</li>
1781     * <li>Account</li>
1782     * <li>null</li>
1783     * </ul>
1784     * @param extras the Bundle to check
1785     */
1786    public static void validateSyncExtrasBundle(Bundle extras) {
1787        try {
1788            for (String key : extras.keySet()) {
1789                Object value = extras.get(key);
1790                if (value == null) continue;
1791                if (value instanceof Long) continue;
1792                if (value instanceof Integer) continue;
1793                if (value instanceof Boolean) continue;
1794                if (value instanceof Float) continue;
1795                if (value instanceof Double) continue;
1796                if (value instanceof String) continue;
1797                if (value instanceof Account) continue;
1798                throw new IllegalArgumentException("unexpected value type: "
1799                        + value.getClass().getName());
1800            }
1801        } catch (IllegalArgumentException e) {
1802            throw e;
1803        } catch (RuntimeException exc) {
1804            throw new IllegalArgumentException("error unparceling Bundle", exc);
1805        }
1806    }
1807
1808    /**
1809     * Cancel any active or pending syncs that match the Uri. If the uri is null then
1810     * all syncs will be canceled.
1811     *
1812     * @param uri the uri of the provider to sync or null to sync all providers.
1813     * @deprecated instead use {@link #cancelSync(android.accounts.Account, String)}
1814     */
1815    @Deprecated
1816    public void cancelSync(Uri uri) {
1817        cancelSync(null /* all accounts */, uri != null ? uri.getAuthority() : null);
1818    }
1819
1820    /**
1821     * Cancel any active or pending syncs that match account and authority. The account and
1822     * authority can each independently be set to null, which means that syncs with any account
1823     * or authority, respectively, will match.
1824     *
1825     * @param account filters the syncs that match by this account
1826     * @param authority filters the syncs that match by this authority
1827     */
1828    public static void cancelSync(Account account, String authority) {
1829        try {
1830            getContentService().cancelSync(account, authority);
1831        } catch (RemoteException e) {
1832        }
1833    }
1834
1835    /**
1836     * Get information about the SyncAdapters that are known to the system.
1837     * @return an array of SyncAdapters that have registered with the system
1838     */
1839    public static SyncAdapterType[] getSyncAdapterTypes() {
1840        try {
1841            return getContentService().getSyncAdapterTypes();
1842        } catch (RemoteException e) {
1843            throw new RuntimeException("the ContentService should always be reachable", e);
1844        }
1845    }
1846
1847    /**
1848     * Check if the provider should be synced when a network tickle is received
1849     * <p>This method requires the caller to hold the permission
1850     * {@link android.Manifest.permission#READ_SYNC_SETTINGS}.
1851     *
1852     * @param account the account whose setting we are querying
1853     * @param authority the provider whose setting we are querying
1854     * @return true if the provider should be synced when a network tickle is received
1855     */
1856    public static boolean getSyncAutomatically(Account account, String authority) {
1857        try {
1858            return getContentService().getSyncAutomatically(account, authority);
1859        } catch (RemoteException e) {
1860            throw new RuntimeException("the ContentService should always be reachable", e);
1861        }
1862    }
1863
1864    /**
1865     * Set whether or not the provider is synced when it receives a network tickle.
1866     * <p>This method requires the caller to hold the permission
1867     * {@link android.Manifest.permission#WRITE_SYNC_SETTINGS}.
1868     *
1869     * @param account the account whose setting we are querying
1870     * @param authority the provider whose behavior is being controlled
1871     * @param sync true if the provider should be synced when tickles are received for it
1872     */
1873    public static void setSyncAutomatically(Account account, String authority, boolean sync) {
1874        try {
1875            getContentService().setSyncAutomatically(account, authority, sync);
1876        } catch (RemoteException e) {
1877            // exception ignored; if this is thrown then it means the runtime is in the midst of
1878            // being restarted
1879        }
1880    }
1881
1882    /**
1883     * Specifies that a sync should be requested with the specified the account, authority,
1884     * and extras at the given frequency. If there is already another periodic sync scheduled
1885     * with the account, authority and extras then a new periodic sync won't be added, instead
1886     * the frequency of the previous one will be updated.
1887     * <p>
1888     * These periodic syncs honor the "syncAutomatically" and "masterSyncAutomatically" settings.
1889     * Although these sync are scheduled at the specified frequency, it may take longer for it to
1890     * actually be started if other syncs are ahead of it in the sync operation queue. This means
1891     * that the actual start time may drift.
1892     * <p>
1893     * Periodic syncs are not allowed to have any of {@link #SYNC_EXTRAS_DO_NOT_RETRY},
1894     * {@link #SYNC_EXTRAS_IGNORE_BACKOFF}, {@link #SYNC_EXTRAS_IGNORE_SETTINGS},
1895     * {@link #SYNC_EXTRAS_INITIALIZE}, {@link #SYNC_EXTRAS_FORCE},
1896     * {@link #SYNC_EXTRAS_EXPEDITED}, {@link #SYNC_EXTRAS_MANUAL} set to true.
1897     * If any are supplied then an {@link IllegalArgumentException} will be thrown.
1898     * <p>As of API level 19 this function introduces a default flexibility of ~4% (up to a maximum
1899     * of one hour in the day) into the requested period. Use
1900     * {@link SyncRequest.Builder#syncPeriodic(long, long)} to set this flexibility manually.
1901     *
1902     * <p>This method requires the caller to hold the permission
1903     * {@link android.Manifest.permission#WRITE_SYNC_SETTINGS}.
1904     *
1905     * @param account the account to specify in the sync
1906     * @param authority the provider to specify in the sync request
1907     * @param extras extra parameters to go along with the sync request
1908     * @param pollFrequency how frequently the sync should be performed, in seconds.
1909     * @throws IllegalArgumentException if an illegal extra was set or if any of the parameters
1910     * are null.
1911     */
1912    public static void addPeriodicSync(Account account, String authority, Bundle extras,
1913            long pollFrequency) {
1914        validateSyncExtrasBundle(extras);
1915        if (account == null) {
1916            throw new IllegalArgumentException("account must not be null");
1917        }
1918        if (authority == null) {
1919            throw new IllegalArgumentException("authority must not be null");
1920        }
1921        if (extras.getBoolean(SYNC_EXTRAS_MANUAL, false)
1922                || extras.getBoolean(SYNC_EXTRAS_DO_NOT_RETRY, false)
1923                || extras.getBoolean(SYNC_EXTRAS_IGNORE_BACKOFF, false)
1924                || extras.getBoolean(SYNC_EXTRAS_IGNORE_SETTINGS, false)
1925                || extras.getBoolean(SYNC_EXTRAS_INITIALIZE, false)
1926                || extras.getBoolean(SYNC_EXTRAS_FORCE, false)
1927                || extras.getBoolean(SYNC_EXTRAS_EXPEDITED, false)) {
1928            throw new IllegalArgumentException("illegal extras were set");
1929        }
1930        try {
1931             getContentService().addPeriodicSync(account, authority, extras, pollFrequency);
1932        } catch (RemoteException e) {
1933            // exception ignored; if this is thrown then it means the runtime is in the midst of
1934            // being restarted
1935        }
1936    }
1937
1938    /**
1939     * Remove a periodic sync. Has no affect if account, authority and extras don't match
1940     * an existing periodic sync.
1941     * <p>This method requires the caller to hold the permission
1942     * {@link android.Manifest.permission#WRITE_SYNC_SETTINGS}.
1943     *
1944     * @param account the account of the periodic sync to remove
1945     * @param authority the provider of the periodic sync to remove
1946     * @param extras the extras of the periodic sync to remove
1947     */
1948    public static void removePeriodicSync(Account account, String authority, Bundle extras) {
1949        validateSyncExtrasBundle(extras);
1950        if (account == null) {
1951            throw new IllegalArgumentException("account must not be null");
1952        }
1953        if (authority == null) {
1954            throw new IllegalArgumentException("authority must not be null");
1955        }
1956        try {
1957            getContentService().removePeriodicSync(account, authority, extras);
1958        } catch (RemoteException e) {
1959            throw new RuntimeException("the ContentService should always be reachable", e);
1960        }
1961    }
1962
1963    /**
1964     * Get the list of information about the periodic syncs for the given account and authority.
1965     * <p>This method requires the caller to hold the permission
1966     * {@link android.Manifest.permission#READ_SYNC_SETTINGS}.
1967     *
1968     * @param account the account whose periodic syncs we are querying
1969     * @param authority the provider whose periodic syncs we are querying
1970     * @return a list of PeriodicSync objects. This list may be empty but will never be null.
1971     */
1972    public static List<PeriodicSync> getPeriodicSyncs(Account account, String authority) {
1973        if (account == null) {
1974            throw new IllegalArgumentException("account must not be null");
1975        }
1976        if (authority == null) {
1977            throw new IllegalArgumentException("authority must not be null");
1978        }
1979        try {
1980            return getContentService().getPeriodicSyncs(account, authority);
1981        } catch (RemoteException e) {
1982            throw new RuntimeException("the ContentService should always be reachable", e);
1983        }
1984    }
1985
1986    /**
1987     * Check if this account/provider is syncable.
1988     * <p>This method requires the caller to hold the permission
1989     * {@link android.Manifest.permission#READ_SYNC_SETTINGS}.
1990     * @return >0 if it is syncable, 0 if not, and <0 if the state isn't known yet.
1991     */
1992    public static int getIsSyncable(Account account, String authority) {
1993        try {
1994            return getContentService().getIsSyncable(account, authority);
1995        } catch (RemoteException e) {
1996            throw new RuntimeException("the ContentService should always be reachable", e);
1997        }
1998    }
1999
2000    /**
2001     * Set whether this account/provider is syncable.
2002     * <p>This method requires the caller to hold the permission
2003     * {@link android.Manifest.permission#WRITE_SYNC_SETTINGS}.
2004     * @param syncable >0 denotes syncable, 0 means not syncable, <0 means unknown
2005     */
2006    public static void setIsSyncable(Account account, String authority, int syncable) {
2007        try {
2008            getContentService().setIsSyncable(account, authority, syncable);
2009        } catch (RemoteException e) {
2010            // exception ignored; if this is thrown then it means the runtime is in the midst of
2011            // being restarted
2012        }
2013    }
2014
2015    /**
2016     * Gets the master auto-sync setting that applies to all the providers and accounts.
2017     * If this is false then the per-provider auto-sync setting is ignored.
2018     * <p>This method requires the caller to hold the permission
2019     * {@link android.Manifest.permission#READ_SYNC_SETTINGS}.
2020     *
2021     * @return the master auto-sync setting that applies to all the providers and accounts
2022     */
2023    public static boolean getMasterSyncAutomatically() {
2024        try {
2025            return getContentService().getMasterSyncAutomatically();
2026        } catch (RemoteException e) {
2027            throw new RuntimeException("the ContentService should always be reachable", e);
2028        }
2029    }
2030
2031    /**
2032     * Sets the master auto-sync setting that applies to all the providers and accounts.
2033     * If this is false then the per-provider auto-sync setting is ignored.
2034     * <p>This method requires the caller to hold the permission
2035     * {@link android.Manifest.permission#WRITE_SYNC_SETTINGS}.
2036     *
2037     * @param sync the master auto-sync setting that applies to all the providers and accounts
2038     */
2039    public static void setMasterSyncAutomatically(boolean sync) {
2040        try {
2041            getContentService().setMasterSyncAutomatically(sync);
2042        } catch (RemoteException e) {
2043            // exception ignored; if this is thrown then it means the runtime is in the midst of
2044            // being restarted
2045        }
2046    }
2047
2048    /**
2049     * Returns true if there is currently a sync operation for the given
2050     * account or authority in the pending list, or actively being processed.
2051     * <p>This method requires the caller to hold the permission
2052     * {@link android.Manifest.permission#READ_SYNC_STATS}.
2053     * @param account the account whose setting we are querying
2054     * @param authority the provider whose behavior is being queried
2055     * @return true if a sync is active for the given account or authority.
2056     */
2057    public static boolean isSyncActive(Account account, String authority) {
2058        try {
2059            return getContentService().isSyncActive(account, authority);
2060        } catch (RemoteException e) {
2061            throw new RuntimeException("the ContentService should always be reachable", e);
2062        }
2063    }
2064
2065    /**
2066     * If a sync is active returns the information about it, otherwise returns null.
2067     * <p>
2068     * This method requires the caller to hold the permission
2069     * {@link android.Manifest.permission#READ_SYNC_STATS}.
2070     * <p>
2071     * @return the SyncInfo for the currently active sync or null if one is not active.
2072     * @deprecated
2073     * Since multiple concurrent syncs are now supported you should use
2074     * {@link #getCurrentSyncs()} to get the accurate list of current syncs.
2075     * This method returns the first item from the list of current syncs
2076     * or null if there are none.
2077     */
2078    @Deprecated
2079    public static SyncInfo getCurrentSync() {
2080        try {
2081            final List<SyncInfo> syncs = getContentService().getCurrentSyncs();
2082            if (syncs.isEmpty()) {
2083                return null;
2084            }
2085            return syncs.get(0);
2086        } catch (RemoteException e) {
2087            throw new RuntimeException("the ContentService should always be reachable", e);
2088        }
2089    }
2090
2091    /**
2092     * Returns a list with information about all the active syncs. This list will be empty
2093     * if there are no active syncs.
2094     * <p>
2095     * This method requires the caller to hold the permission
2096     * {@link android.Manifest.permission#READ_SYNC_STATS}.
2097     * <p>
2098     * @return a List of SyncInfo objects for the currently active syncs.
2099     */
2100    public static List<SyncInfo> getCurrentSyncs() {
2101        try {
2102            return getContentService().getCurrentSyncs();
2103        } catch (RemoteException e) {
2104            throw new RuntimeException("the ContentService should always be reachable", e);
2105        }
2106    }
2107
2108    /**
2109     * Returns the status that matches the authority.
2110     * @param account the account whose setting we are querying
2111     * @param authority the provider whose behavior is being queried
2112     * @return the SyncStatusInfo for the authority, or null if none exists
2113     * @hide
2114     */
2115    public static SyncStatusInfo getSyncStatus(Account account, String authority) {
2116        try {
2117            return getContentService().getSyncStatus(account, authority);
2118        } catch (RemoteException e) {
2119            throw new RuntimeException("the ContentService should always be reachable", e);
2120        }
2121    }
2122
2123    /**
2124     * Return true if the pending status is true of any matching authorities.
2125     * <p>This method requires the caller to hold the permission
2126     * {@link android.Manifest.permission#READ_SYNC_STATS}.
2127     * @param account the account whose setting we are querying
2128     * @param authority the provider whose behavior is being queried
2129     * @return true if there is a pending sync with the matching account and authority
2130     */
2131    public static boolean isSyncPending(Account account, String authority) {
2132        try {
2133            return getContentService().isSyncPending(account, authority);
2134        } catch (RemoteException e) {
2135            throw new RuntimeException("the ContentService should always be reachable", e);
2136        }
2137    }
2138
2139    /**
2140     * Request notifications when the different aspects of the SyncManager change. The
2141     * different items that can be requested are:
2142     * <ul>
2143     * <li> {@link #SYNC_OBSERVER_TYPE_PENDING}
2144     * <li> {@link #SYNC_OBSERVER_TYPE_ACTIVE}
2145     * <li> {@link #SYNC_OBSERVER_TYPE_SETTINGS}
2146     * </ul>
2147     * The caller can set one or more of the status types in the mask for any
2148     * given listener registration.
2149     * @param mask the status change types that will cause the callback to be invoked
2150     * @param callback observer to be invoked when the status changes
2151     * @return a handle that can be used to remove the listener at a later time
2152     */
2153    public static Object addStatusChangeListener(int mask, final SyncStatusObserver callback) {
2154        if (callback == null) {
2155            throw new IllegalArgumentException("you passed in a null callback");
2156        }
2157        try {
2158            ISyncStatusObserver.Stub observer = new ISyncStatusObserver.Stub() {
2159                public void onStatusChanged(int which) throws RemoteException {
2160                    callback.onStatusChanged(which);
2161                }
2162            };
2163            getContentService().addStatusChangeListener(mask, observer);
2164            return observer;
2165        } catch (RemoteException e) {
2166            throw new RuntimeException("the ContentService should always be reachable", e);
2167        }
2168    }
2169
2170    /**
2171     * Remove a previously registered status change listener.
2172     * @param handle the handle that was returned by {@link #addStatusChangeListener}
2173     */
2174    public static void removeStatusChangeListener(Object handle) {
2175        if (handle == null) {
2176            throw new IllegalArgumentException("you passed in a null handle");
2177        }
2178        try {
2179            getContentService().removeStatusChangeListener((ISyncStatusObserver.Stub) handle);
2180        } catch (RemoteException e) {
2181            // exception ignored; if this is thrown then it means the runtime is in the midst of
2182            // being restarted
2183        }
2184    }
2185
2186    /**
2187     * Returns sampling percentage for a given duration.
2188     *
2189     * Always returns at least 1%.
2190     */
2191    private int samplePercentForDuration(long durationMillis) {
2192        if (durationMillis >= SLOW_THRESHOLD_MILLIS) {
2193            return 100;
2194        }
2195        return (int) (100 * durationMillis / SLOW_THRESHOLD_MILLIS) + 1;
2196    }
2197
2198    private void maybeLogQueryToEventLog(long durationMillis,
2199                                         Uri uri, String[] projection,
2200                                         String selection, String sortOrder) {
2201        if (!ENABLE_CONTENT_SAMPLE) return;
2202        int samplePercent = samplePercentForDuration(durationMillis);
2203        if (samplePercent < 100) {
2204            synchronized (mRandom) {
2205                if (mRandom.nextInt(100) >= samplePercent) {
2206                    return;
2207                }
2208            }
2209        }
2210
2211        StringBuilder projectionBuffer = new StringBuilder(100);
2212        if (projection != null) {
2213            for (int i = 0; i < projection.length; ++i) {
2214                // Note: not using a comma delimiter here, as the
2215                // multiple arguments to EventLog.writeEvent later
2216                // stringify with a comma delimiter, which would make
2217                // parsing uglier later.
2218                if (i != 0) projectionBuffer.append('/');
2219                projectionBuffer.append(projection[i]);
2220            }
2221        }
2222
2223        // ActivityThread.currentPackageName() only returns non-null if the
2224        // current thread is an application main thread.  This parameter tells
2225        // us whether an event loop is blocked, and if so, which app it is.
2226        String blockingPackage = AppGlobals.getInitialPackage();
2227
2228        EventLog.writeEvent(
2229            EventLogTags.CONTENT_QUERY_SAMPLE,
2230            uri.toString(),
2231            projectionBuffer.toString(),
2232            selection != null ? selection : "",
2233            sortOrder != null ? sortOrder : "",
2234            durationMillis,
2235            blockingPackage != null ? blockingPackage : "",
2236            samplePercent);
2237    }
2238
2239    private void maybeLogUpdateToEventLog(
2240        long durationMillis, Uri uri, String operation, String selection) {
2241        if (!ENABLE_CONTENT_SAMPLE) return;
2242        int samplePercent = samplePercentForDuration(durationMillis);
2243        if (samplePercent < 100) {
2244            synchronized (mRandom) {
2245                if (mRandom.nextInt(100) >= samplePercent) {
2246                    return;
2247                }
2248            }
2249        }
2250        String blockingPackage = AppGlobals.getInitialPackage();
2251        EventLog.writeEvent(
2252            EventLogTags.CONTENT_UPDATE_SAMPLE,
2253            uri.toString(),
2254            operation,
2255            selection != null ? selection : "",
2256            durationMillis,
2257            blockingPackage != null ? blockingPackage : "",
2258            samplePercent);
2259    }
2260
2261    private final class CursorWrapperInner extends CrossProcessCursorWrapper {
2262        private final IContentProvider mContentProvider;
2263        public static final String TAG="CursorWrapperInner";
2264
2265        private final CloseGuard mCloseGuard = CloseGuard.get();
2266        private boolean mProviderReleased;
2267
2268        CursorWrapperInner(Cursor cursor, IContentProvider icp) {
2269            super(cursor);
2270            mContentProvider = icp;
2271            mCloseGuard.open("close");
2272        }
2273
2274        @Override
2275        public void close() {
2276            super.close();
2277            ContentResolver.this.releaseProvider(mContentProvider);
2278            mProviderReleased = true;
2279
2280            if (mCloseGuard != null) {
2281                mCloseGuard.close();
2282            }
2283        }
2284
2285        @Override
2286        protected void finalize() throws Throwable {
2287            try {
2288                if (mCloseGuard != null) {
2289                    mCloseGuard.warnIfOpen();
2290                }
2291
2292                if (!mProviderReleased && mContentProvider != null) {
2293                    // Even though we are using CloseGuard, log this anyway so that
2294                    // application developers always see the message in the log.
2295                    Log.w(TAG, "Cursor finalized without prior close()");
2296                    ContentResolver.this.releaseProvider(mContentProvider);
2297                }
2298            } finally {
2299                super.finalize();
2300            }
2301        }
2302    }
2303
2304    private final class ParcelFileDescriptorInner extends ParcelFileDescriptor {
2305        private final IContentProvider mContentProvider;
2306        private boolean mProviderReleased;
2307
2308        ParcelFileDescriptorInner(ParcelFileDescriptor pfd, IContentProvider icp) {
2309            super(pfd);
2310            mContentProvider = icp;
2311        }
2312
2313        @Override
2314        public void close() throws IOException {
2315            super.close();
2316            if (!mProviderReleased) {
2317                ContentResolver.this.releaseProvider(mContentProvider);
2318                mProviderReleased = true;
2319            }
2320        }
2321    }
2322
2323    /** @hide */
2324    public static final String CONTENT_SERVICE_NAME = "content";
2325
2326    /** @hide */
2327    public static IContentService getContentService() {
2328        if (sContentService != null) {
2329            return sContentService;
2330        }
2331        IBinder b = ServiceManager.getService(CONTENT_SERVICE_NAME);
2332        if (false) Log.v("ContentService", "default service binder = " + b);
2333        sContentService = IContentService.Stub.asInterface(b);
2334        if (false) Log.v("ContentService", "default service = " + sContentService);
2335        return sContentService;
2336    }
2337
2338    /** @hide */
2339    public String getPackageName() {
2340        return mPackageName;
2341    }
2342
2343    private static IContentService sContentService;
2344    private final Context mContext;
2345    final String mPackageName;
2346    private static final String TAG = "ContentResolver";
2347}
2348