Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright (C) 2006 The Android Open Source Project
    *
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    *
    *      http://www.apache.org/licenses/LICENSE-2.0
    *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  package android.content;
  
  import android.net.Uri;
  import android.os.Bundle;
  import android.util.Log;
  
  import java.io.File;
  import java.util.List;
  import java.util.Random;
This class provides applications access to the content model.
  
  public abstract class ContentResolver {
    
  
      @Deprecated
      public static final String SYNC_EXTRAS_ACCOUNT = "account";
      public static final String SYNC_EXTRAS_EXPEDITED = "expedited";
    

Deprecated:
instead use SYNC_EXTRAS_MANUAL
  
      @Deprecated
      public static final String SYNC_EXTRAS_FORCE = "force";

    
If this extra is set to true then the sync settings (like getSyncAutomatically()) are ignored by the sync scheduler.
  
      public static final String SYNC_EXTRAS_IGNORE_SETTINGS = "ignore_settings";

    
If this extra is set to true then any backoffs for the initial attempt (e.g. due to retries) are ignored by the sync scheduler. If this request fails and gets rescheduled then the retries will still honor the backoff.
  
      public static final String SYNC_EXTRAS_IGNORE_BACKOFF = "ignore_backoff";

    
If this extra is set to true then the request will not be retried if it fails.
  
      public static final String SYNC_EXTRAS_DO_NOT_RETRY = "do_not_retry";

    
Setting this extra is the equivalent of setting both SYNC_EXTRAS_IGNORE_SETTINGS and SYNC_EXTRAS_IGNORE_BACKOFF
  
      public static final String SYNC_EXTRAS_MANUAL = "force";
  
      public static final String SYNC_EXTRAS_UPLOAD = "upload";
      public static final String SYNC_EXTRAS_OVERRIDE_TOO_MANY_DELETIONS = "deletions_override";
      public static final String SYNC_EXTRAS_DISCARD_LOCAL_DELETIONS = "discard_deletions";

    
Set by the SyncManager to request that the SyncAdapter initialize itself for the given account/authority pair. One required initialization step is to ensure that setIsSyncable(android.accounts.Account,java.lang.String,int) has been called with a >= 0 value. When this flag is set the SyncAdapter does not need to do a full sync, though it is allowed to do so.
 
     public static final String SYNC_EXTRAS_INITIALIZE = "initialize";
 
     public static final String SCHEME_CONTENT = "content";
     public static final String SCHEME_ANDROID_RESOURCE = "android.resource";
     public static final String SCHEME_FILE = "file";

    
This is the Android platform's base MIME type for a content: URI containing a Cursor of a single item. Applications should use this as the base type along with their own sub-type of their content: URIs that represent a particular item. For example, hypothetical IMAP email client may have a URI content://com.company.provider.imap/inbox/1 for a particular message in the inbox, whose MIME type would be reported as CURSOR_ITEM_BASE_TYPE + "/vnd.company.imap-msg"

Compare with CURSOR_DIR_BASE_TYPE.

 
     public static final String CURSOR_ITEM_BASE_TYPE = "vnd.android.cursor.item";

    
This is the Android platform's base MIME type for a content: URI containing a Cursor of zero or more items. Applications should use this as the base type along with their own sub-type of their content: URIs that represent a directory of items. For example, hypothetical IMAP email client may have a URI content://com.company.provider.imap/inbox for all of the messages in its inbox, whose MIME type would be reported as CURSOR_DIR_BASE_TYPE + "/vnd.company.imap-msg"

Note how the base MIME type varies between this and CURSOR_ITEM_BASE_TYPE depending on whether there is one single item or multiple items in the data set, while the sub-type remains the same because in either case the data structure contained in the cursor is the same.

 
     public static final String CURSOR_DIR_BASE_TYPE = "vnd.android.cursor.dir";

    

Hide:
 
     public static final int SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS = 1;
    

Hide:
 
     public static final int SYNC_ERROR_AUTHENTICATION = 2;
    

Hide:
 
     public static final int SYNC_ERROR_IO = 3;
    

Hide:
 
     public static final int SYNC_ERROR_PARSE = 4;
    

Hide:
 
     public static final int SYNC_ERROR_CONFLICT = 5;
    

Hide:
 
     public static final int SYNC_ERROR_TOO_MANY_DELETIONS = 6;
    

Hide:
 
     public static final int SYNC_ERROR_TOO_MANY_RETRIES = 7;
    

Hide:
 
     public static final int SYNC_ERROR_INTERNAL = 8;
 
     public static final int SYNC_OBSERVER_TYPE_SETTINGS = 1<<0;
     public static final int SYNC_OBSERVER_TYPE_PENDING = 1<<1;
     public static final int SYNC_OBSERVER_TYPE_ACTIVE = 1<<2;
    

Hide:
 
     public static final int SYNC_OBSERVER_TYPE_STATUS = 1<<3;
    

Hide:
 
     public static final int SYNC_OBSERVER_TYPE_ALL = 0x7fffffff;
 
     // Always log queries which take 500ms+; shorter queries are
     // sampled accordingly.
     private static final int SLOW_THRESHOLD_MILLIS = 500;
     private final Random mRandom = new Random();  // guarded by itself
 
     public ContentResolver(Context context) {
          = context;
     }

    

Hide:
 
     protected abstract IContentProvider acquireProvider(Context cString name);
    
Providing a default implementation of this, to avoid having to change a lot of other things, but implementations of ContentResolver should implement it.

Hide:
 
     protected IContentProvider acquireExistingProvider(Context cString name) {
         return acquireProvider(cname);
     }
    

Hide:
 
     public abstract boolean releaseProvider(IContentProvider icp);

    
Return the MIME type of the given content URL.

Parameters:
url A Uri identifying content (either a list or specific type), using the content:// scheme.
Returns:
A MIME type for the content, or null if the URL is invalid or the type is unknown
 
     public final String getType(Uri url) {
         IContentProvider provider = acquireExistingProvider(url);
         if (provider != null) {
             try {
                 return provider.getType(url);
             } catch (RemoteException e) {
                 return null;
             } catch (java.lang.Exception e) {
                 return null;
             } finally {
                 releaseProvider(provider);
             }
         }
 
         if (!.equals(url.getScheme())) {
             return null;
         }
 
         try {
             String type = ActivityManagerNative.getDefault().getProviderMimeType(url);
             return type;
         } catch (RemoteException e) {
             return null;
         }
     }

    

Query the given URI, returning a android.database.Cursor over the result set.

For best performance, the caller should follow these guidelines:

  • Provide an explicit projection, to prevent reading data from storage that aren't going to be used.
  • Use question mark parameter markers such as 'phone=?' instead of explicit values in the selection parameter, so that queries that differ only by those values will be recognized as the same for caching purposes.

Parameters:
uri The URI, using the content:// scheme, for the content to retrieve.
projection A list of which columns to return. Passing null will return all columns, which is inefficient.
selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given URI.
selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection. The values will be bound as Strings.
sortOrder How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
Returns:
A Cursor object, which is positioned before the first entry, or null
See also:
android.database.Cursor
 
     public final Cursor query(Uri uriString[] projection,
             String selectionString[] selectionArgsString sortOrder) {
         IContentProvider provider = acquireProvider(uri);
         if (provider == null) {
             return null;
         }
         try {
             long startTime = SystemClock.uptimeMillis();
             Cursor qCursor = provider.query(uriprojectionselectionselectionArgssortOrder);
             if (qCursor == null) {
                 releaseProvider(provider);
                 return null;
             }
             // force query execution
             qCursor.getCount();
             long durationMillis = SystemClock.uptimeMillis() - startTime;
             maybeLogQueryToEventLog(durationMillisuriprojectionselectionsortOrder);
             // Wrap the cursor object into CursorWrapperInner object
             return new CursorWrapperInner(qCursorprovider);
         } catch (RemoteException e) {
             releaseProvider(provider);
             return null;
         } catch(RuntimeException e) {
             releaseProvider(provider);
             throw e;
         }
     }

    
Open a stream on to the content associated with a content URI. If there is no data associated with the URI, FileNotFoundException is thrown.
Accepts the following URI schemes:

See openAssetFileDescriptor(android.net.Uri,java.lang.String) for more information on these schemes.

Parameters:
uri The desired URI.
Returns:
InputStream
Throws:
java.io.FileNotFoundException if the provided URI could not be opened.
See also:
openAssetFileDescriptor(android.net.Uri,java.lang.String)
 
     public final InputStream openInputStream(Uri uri)
             throws FileNotFoundException {
         String scheme = uri.getScheme();
         if (.equals(scheme)) {
             // Note: left here to avoid breaking compatibility.  May be removed
             // with sufficient testing.
             OpenResourceIdResult r = getResourceId(uri);
             try {
                 InputStream stream = r.r.openRawResource(r.id);
                 return stream;
             } catch (Resources.NotFoundException ex) {
                 throw new FileNotFoundException("Resource does not exist: " + uri);
             }
         } else if (.equals(scheme)) {
             // Note: left here to avoid breaking compatibility.  May be removed
             // with sufficient testing.
             return new FileInputStream(uri.getPath());
         } else {
             AssetFileDescriptor fd = openAssetFileDescriptor(uri"r");
             try {
                 return fd != null ? fd.createInputStream() : null;
             } catch (IOException e) {
                 throw new FileNotFoundException("Unable to create stream");
             }
         }
     }

    
Synonym for openOutputStream(uri, "w").

Throws:
java.io.FileNotFoundException if the provided URI could not be opened.
 
     public final OutputStream openOutputStream(Uri uri)
             throws FileNotFoundException {
         return openOutputStream(uri"w");
     }

    
Open a stream on to the content associated with a content URI. If there is no data associated with the URI, FileNotFoundException is thrown.
Accepts the following URI schemes:

See openAssetFileDescriptor(android.net.Uri,java.lang.String) for more information on these schemes.

Parameters:
uri The desired URI.
mode May be "w", "wa", "rw", or "rwt".
Returns:
OutputStream
Throws:
java.io.FileNotFoundException if the provided URI could not be opened.
See also:
openAssetFileDescriptor(android.net.Uri,java.lang.String)
 
     public final OutputStream openOutputStream(Uri uriString mode)
             throws FileNotFoundException {
         AssetFileDescriptor fd = openAssetFileDescriptor(urimode);
         try {
             return fd != null ? fd.createOutputStream() : null;
         } catch (IOException e) {
             throw new FileNotFoundException("Unable to create stream");
         }
     }

    
Open a raw file descriptor to access data under a "content:" URI. This is like openAssetFileDescriptor(android.net.Uri,java.lang.String), but uses the underlying ContentProvider.openFile(android.net.Uri,java.lang.String) ContentProvider.openFile()} method, so will not work with providers that return sub-sections of files. If at all possible, you should use openAssetFileDescriptor(android.net.Uri,java.lang.String). You will receive a FileNotFoundException exception if the provider returns a sub-section of a file.
Accepts the following URI schemes:

See openAssetFileDescriptor(android.net.Uri,java.lang.String) for more information on these schemes.

Parameters:
uri The desired URI to open.
mode The file mode to use, as per ContentProvider.openFile.
Returns:
Returns a new ParcelFileDescriptor pointing to the file. You own this descriptor and are responsible for closing it when done.
Throws:
java.io.FileNotFoundException Throws FileNotFoundException of no file exists under the URI or the mode is invalid.
See also:
openAssetFileDescriptor(android.net.Uri,java.lang.String)
 
     public final ParcelFileDescriptor openFileDescriptor(Uri uri,
             String modethrows FileNotFoundException {
         AssetFileDescriptor afd = openAssetFileDescriptor(urimode);
         if (afd == null) {
             return null;
         }
 
         if (afd.getDeclaredLength() < 0) {
             // This is a full file!
             return afd.getParcelFileDescriptor();
         }
 
         // Client can't handle a sub-section of a file, so close what
         // we got and bail with an exception.
         try {
             afd.close();
         } catch (IOException e) {
         }
 
         throw new FileNotFoundException("Not a whole file");
     }

    
Open a raw file descriptor to access data under a "content:" URI. This interacts with the underlying ContentProvider.openAssetFile(android.net.Uri,java.lang.String) ContentProvider.openAssetFile()} method of the provider associated with the given URI, to retrieve any file stored there.
Accepts the following URI schemes:
The android.resource (SCHEME_ANDROID_RESOURCE) Scheme

A Uri object can be used to reference a resource in an APK file. The Uri should be one of the following formats:

  • android.resource://package_name/id_number
    package_name is your package name as listed in your AndroidManifest.xml. For example com.example.myapp
    id_number is the int form of the ID.
    The easiest way to construct this form is
    Uri uri = Uri.parse("android.resource://com.example.myapp/" + R.raw.my_resource");
  • android.resource://package_name/type/name
    package_name is your package name as listed in your AndroidManifest.xml. For example com.example.myapp
    type is the string form of the resource type. For example, raw or drawable. name is the string form of the resource name. That is, whatever the file name was in your res directory, without the type extension. The easiest way to construct this form is
    Uri uri = Uri.parse("android.resource://com.example.myapp/raw/my_resource");

Parameters:
uri The desired URI to open.
mode The file mode to use, as per ContentProvider.openAssetFile.
Returns:
Returns a new ParcelFileDescriptor pointing to the file. You own this descriptor and are responsible for closing it when done.
Throws:
java.io.FileNotFoundException Throws FileNotFoundException of no file exists under the URI or the mode is invalid.
 
     public final AssetFileDescriptor openAssetFileDescriptor(Uri uri,
             String modethrows FileNotFoundException {
         String scheme = uri.getScheme();
         if (.equals(scheme)) {
             if (!"r".equals(mode)) {
                 throw new FileNotFoundException("Can't write resources: " + uri);
             }
             OpenResourceIdResult r = getResourceId(uri);
             try {
                 return r.r.openRawResourceFd(r.id);
             } catch (Resources.NotFoundException ex) {
                 throw new FileNotFoundException("Resource does not exist: " + uri);
             }
         } else if (.equals(scheme)) {
             ParcelFileDescriptor pfd = ParcelFileDescriptor.open(
                     new File(uri.getPath()), modeToMode(urimode));
             return new AssetFileDescriptor(pfd, 0, -1);
         } else {
             IContentProvider provider = acquireProvider(uri);
             if (provider == null) {
                 throw new FileNotFoundException("No content provider: " + uri);
             }
             try {
                 AssetFileDescriptor fd = provider.openAssetFile(urimode);
                 if(fd == null) {
                     releaseProvider(provider);
                     return null;
                 }
                 ParcelFileDescriptor pfd = new ParcelFileDescriptorInner(
                         fd.getParcelFileDescriptor(), provider);
                 return new AssetFileDescriptor(pfdfd.getStartOffset(),
                         fd.getDeclaredLength());
             } catch (RemoteException e) {
                 releaseProvider(provider);
                 throw new FileNotFoundException("Dead content provider: " + uri);
             } catch (FileNotFoundException e) {
                 releaseProvider(provider);
                 throw e;
             } catch (RuntimeException e) {
                 releaseProvider(provider);
                 throw e;
             }
         }
     }

    
A resource identified by the android.content.res.Resources that contains it, and a resource id.

Hide:
 
     public class OpenResourceIdResult {
         public Resources r;
         public int id;
     }

    
Resolves an android.resource URI to a android.content.res.Resources and a resource id.

Hide:
 
     public OpenResourceIdResult getResourceId(Uri urithrows FileNotFoundException {
         String authority = uri.getAuthority();
         Resources r;
         if (TextUtils.isEmpty(authority)) {
             throw new FileNotFoundException("No authority: " + uri);
         } else {
             try {
                 r = .getPackageManager().getResourcesForApplication(authority);
             } catch (NameNotFoundException ex) {
                 throw new FileNotFoundException("No package found for authority: " + uri);
             }
         }
         List<Stringpath = uri.getPathSegments();
         if (path == null) {
             throw new FileNotFoundException("No path: " + uri);
         }
         int len = path.size();
         int id;
         if (len == 1) {
             try {
                 id = Integer.parseInt(path.get(0));
             } catch (NumberFormatException e) {
                 throw new FileNotFoundException("Single path segment is not a resource ID: " + uri);
             }
         } else if (len == 2) {
             id = r.getIdentifier(path.get(1), path.get(0), authority);
         } else {
             throw new FileNotFoundException("More than two path segments: " + uri);
         }
         if (id == 0) {
             throw new FileNotFoundException("No resource found for: " + uri);
         }
         OpenResourceIdResult res = new OpenResourceIdResult();
         res.r = r;
         res.id = id;
         return res;
     }

    

Hide:
 
     static public int modeToMode(Uri uriString modethrows FileNotFoundException {
         int modeBits;
         if ("r".equals(mode)) {
             modeBits = .;
         } else if ("w".equals(mode) || "wt".equals(mode)) {
             modeBits = .
                     | .
                     | .;
         } else if ("wa".equals(mode)) {
             modeBits = .
                     | .
                     | .;
         } else if ("rw".equals(mode)) {
             modeBits = .
                     | .;
         } else if ("rwt".equals(mode)) {
             modeBits = .
                     | .
                     | .;
         } else {
             throw new FileNotFoundException("Bad mode for " + uri + ": "
                     + mode);
         }
         return modeBits;
     }

    
Inserts a row into a table at the given URL. If the content provider supports transactions the insertion will be atomic.

Parameters:
url The URL of the table to insert into.
values The initial values for the newly inserted row. The key is the column name for the field. Passing an empty ContentValues will create an empty row.
Returns:
the URL of the newly created row.
 
     public final Uri insert(Uri urlContentValues values)
     {
         IContentProvider provider = acquireProvider(url);
         if (provider == null) {
             throw new IllegalArgumentException("Unknown URL " + url);
         }
         try {
             long startTime = SystemClock.uptimeMillis();
             Uri createdRow = provider.insert(urlvalues);
             long durationMillis = SystemClock.uptimeMillis() - startTime;
             maybeLogUpdateToEventLog(durationMillisurl"insert"null /* where */);
             return createdRow;
         } catch (RemoteException e) {
             return null;
         } finally {
             releaseProvider(provider);
         }
     }

    
Applies each of the ContentProviderOperation objects and returns an array of their results. Passes through OperationApplicationException, which may be thrown by the call to ContentProviderOperation.apply(android.content.ContentProvider,android.content.ContentProviderResult[],int). If all the applications succeed then a ContentProviderResult array with the same number of elements as the operations will be returned. It is implementation-specific how many, if any, operations will have been successfully applied if a call to apply results in a OperationApplicationException.

Parameters:
authority the authority of the ContentProvider to which this batch should be applied
operations the operations to apply
Returns:
the results of the applications
Throws:
OperationApplicationException thrown if an application fails. See ContentProviderOperation.apply(android.content.ContentProvider,android.content.ContentProviderResult[],int) for more information.
android.os.RemoteException thrown if a RemoteException is encountered while attempting to communicate with a remote provider.
 
     public ContentProviderResult[] applyBatch(String authority,
             ArrayList<ContentProviderOperationoperations)
             throws RemoteExceptionOperationApplicationException {
         ContentProviderClient provider = acquireContentProviderClient(authority);
         if (provider == null) {
             throw new IllegalArgumentException("Unknown authority " + authority);
         }
         try {
             return provider.applyBatch(operations);
         } finally {
             provider.release();
         }
     }

    
Inserts multiple rows into a table at the given URL. This function make no guarantees about the atomicity of the insertions.

Parameters:
url The URL of the table to insert into.
values The initial values for the newly inserted rows. The key is the column name for the field. Passing null will create an empty row.
Returns:
the number of newly created rows.
 
     public final int bulkInsert(Uri urlContentValues[] values)
     {
         IContentProvider provider = acquireProvider(url);
         if (provider == null) {
             throw new IllegalArgumentException("Unknown URL " + url);
         }
         try {
             long startTime = SystemClock.uptimeMillis();
             int rowsCreated = provider.bulkInsert(urlvalues);
             long durationMillis = SystemClock.uptimeMillis() - startTime;
             maybeLogUpdateToEventLog(durationMillisurl"bulkinsert"null /* where */);
             return rowsCreated;
         } catch (RemoteException e) {
             return 0;
         } finally {
             releaseProvider(provider);
         }
     }

    
Deletes row(s) specified by a content URI. If the content provider supports transactions, the deletion will be atomic.

Parameters:
url The URL of the row to delete.
where A filter to apply to rows before deleting, formatted as an SQL WHERE clause (excluding the WHERE itself).
Returns:
The number of rows deleted.
 
     public final int delete(Uri urlString whereString[] selectionArgs)
     {
         IContentProvider provider = acquireProvider(url);
         if (provider == null) {
             throw new IllegalArgumentException("Unknown URL " + url);
         }
         try {
             long startTime = SystemClock.uptimeMillis();
             int rowsDeleted = provider.delete(urlwhereselectionArgs);
             long durationMillis = SystemClock.uptimeMillis() - startTime;
             maybeLogUpdateToEventLog(durationMillisurl"delete"where);
             return rowsDeleted;
         } catch (RemoteException e) {
             return -1;
         } finally {
             releaseProvider(provider);
         }
     }

    
Update row(s) in a content URI. If the content provider supports transactions the update will be atomic.

Parameters:
uri The URI to modify.
values The new field values. The key is the column name for the field. A null value will remove an existing field value.
where A filter to apply to rows before updating, formatted as an SQL WHERE clause (excluding the WHERE itself).
Returns:
The number of rows updated.
Throws:
java.lang.NullPointerException if uri or values are null
 
     public final int update(Uri uriContentValues valuesString where,
             String[] selectionArgs) {
         IContentProvider provider = acquireProvider(uri);
         if (provider == null) {
             throw new IllegalArgumentException("Unknown URI " + uri);
         }
         try {
             long startTime = SystemClock.uptimeMillis();
             int rowsUpdated = provider.update(urivalueswhereselectionArgs);
             long durationMillis = SystemClock.uptimeMillis() - startTime;
             maybeLogUpdateToEventLog(durationMillisuri"update"where);
             return rowsUpdated;
         } catch (RemoteException e) {
             return -1;
         } finally {
             releaseProvider(provider);
         }
     }

    
Returns the content provider for the given content URI.

Parameters:
uri The URI to a content provider
Returns:
The ContentProvider for the given URI, or null if no content provider is found.
Hide:
 
     public final IContentProvider acquireProvider(Uri uri) {
         if (!.equals(uri.getScheme())) {
             return null;
         }
         String auth = uri.getAuthority();
         if (auth != null) {
             return acquireProvider(uri.getAuthority());
         }
         return null;
     }

    
Returns the content provider for the given content URI if the process already has a reference on it.

Parameters:
uri The URI to a content provider
Returns:
The ContentProvider for the given URI, or null if no content provider is found.
Hide:
 
     public final IContentProvider acquireExistingProvider(Uri uri) {
         if (!.equals(uri.getScheme())) {
             return null;
         }
         String auth = uri.getAuthority();
         if (auth != null) {
             return acquireExistingProvider(uri.getAuthority());
         }
         return null;
     }

    

Hide:
 
     public final IContentProvider acquireProvider(String name) {
         if (name == null) {
             return null;
         }
         return acquireProvider(name);
     }

    
Returns a ContentProviderClient that is associated with the ContentProvider that services the content at uri, starting the provider if necessary. Returns null if there is no provider associated wih the uri. The caller must indicate that they are done with the provider by calling ContentProviderClient.release() which will allow the system to release the provider it it determines that there is no other reason for keeping it active.

Parameters:
uri specifies which provider should be acquired
Returns:
a ContentProviderClient that is associated with the ContentProvider that services the content at uri or null if there isn't one.
 
     public final ContentProviderClient acquireContentProviderClient(Uri uri) {
         IContentProvider provider = acquireProvider(uri);
         if (provider != null) {
             return new ContentProviderClient(thisprovider);
         }
 
         return null;
     }

    
Returns a ContentProviderClient that is associated with the ContentProvider with the authority of name, starting the provider if necessary. Returns null if there is no provider associated wih the uri. The caller must indicate that they are done with the provider by calling ContentProviderClient.release() which will allow the system to release the provider it it determines that there is no other reason for keeping it active.

Parameters:
name specifies which provider should be acquired
Returns:
a ContentProviderClient that is associated with the ContentProvider with the authority of name or null if there isn't one.
 
         IContentProvider provider = acquireProvider(name);
         if (provider != null) {
             return new ContentProviderClient(thisprovider);
         }
 
         return null;
     }

    
Register an observer class that gets callbacks when data identified by a given content URI changes.

Parameters:
uri The URI to watch for changes. This can be a specific row URI, or a base URI for a whole class of content.
notifyForDescendents If true changes to URIs beginning with uri will also cause notifications to be sent. If false only changes to the exact URI specified by uri will cause notifications to be sent. If true, than any URI values at or below the specified URI will also trigger a match.
observer The object that receives callbacks when changes occur.
See also:
unregisterContentObserver(android.database.ContentObserver)
 
     public final void registerContentObserver(Uri uriboolean notifyForDescendents,
             ContentObserver observer)
     {
         try {
             getContentService().registerContentObserver(urinotifyForDescendents,
                     observer.getContentObserver());
         } catch (RemoteException e) {
         }
     }

    
Unregisters a change observer.

Parameters:
observer The previously registered observer that is no longer needed.
See also:
registerContentObserver(android.net.Uri,boolean,android.database.ContentObserver)
 
     public final void unregisterContentObserver(ContentObserver observer) {
         try {
             IContentObserver contentObserver = observer.releaseContentObserver();
             if (contentObserver != null) {
                 getContentService().unregisterContentObserver(
                         contentObserver);
             }
         } catch (RemoteException e) {
         }
     }

    
Notify registered observers that a row was updated. To register, call registerContentObserver(). By default, CursorAdapter objects will get this notification.

Parameters:
uri
observer The observer that originated the change, may be null</null>
 
     public void notifyChange(Uri uriContentObserver observer) {
         notifyChange(uriobservertrue /* sync to network */);
     }

    
Notify registered observers that a row was updated. To register, call registerContentObserver(). By default, CursorAdapter objects will get this notification.

Parameters:
uri
observer The observer that originated the change, may be null</null>
syncToNetwork If true, attempt to sync the change to the network.
 
     public void notifyChange(Uri uriContentObserver observerboolean syncToNetwork) {
         try {
             getContentService().notifyChange(
                     uriobserver == null ? null : observer.getContentObserver(),
                     observer != null && observer.deliverSelfNotifications(), syncToNetwork);
         } catch (RemoteException e) {
         }
     }

    
Start an asynchronous sync operation. If you want to monitor the progress of the sync you may register a SyncObserver. Only values of the following types may be used in the extras bundle:
  • Integer
  • Long
  • Boolean
  • Float
  • Double
  • String

Deprecated:
instead use requestSync(android.accounts.Account,java.lang.String,android.os.Bundle)
Parameters:
uri the uri of the provider to sync or null to sync all providers.
extras any extras to pass to the SyncAdapter.
 
     @Deprecated
     public void startSync(Uri uriBundle extras) {
         Account account = null;
         if (extras != null) {
             String accountName = extras.getString();
             if (!TextUtils.isEmpty(accountName)) {
                 account = new Account(accountName"com.google");
             }
             extras.remove();
         }
         requestSync(accounturi != null ? uri.getAuthority() : nullextras);
     }

    
Start an asynchronous sync operation. If you want to monitor the progress of the sync you may register a SyncObserver. Only values of the following types may be used in the extras bundle:
  • Integer
  • Long
  • Boolean
  • Float
  • Double
  • String

Parameters:
account which account should be synced
authority which authority should be synced
extras any extras to pass to the SyncAdapter.
 
     public static void requestSync(Account accountString authorityBundle extras) {
         validateSyncExtrasBundle(extras);
         try {
             getContentService().requestSync(accountauthorityextras);
         } catch (RemoteException e) {
         }
     }

    
Check that only values of the following types are in the Bundle:
  • Integer
  • Long
  • Boolean
  • Float
  • Double
  • String
  • Account
  • null

Parameters:
extras the Bundle to check
 
     public static void validateSyncExtrasBundle(Bundle extras) {
         try {
             for (String key : extras.keySet()) {
                 Object value = extras.get(key);
                 if (value == nullcontinue;
                 if (value instanceof Longcontinue;
                 if (value instanceof Integercontinue;
                 if (value instanceof Booleancontinue;
                 if (value instanceof Floatcontinue;
                 if (value instanceof Doublecontinue;
                 if (value instanceof Stringcontinue;
                 if (value instanceof Accountcontinue;
                 throw new IllegalArgumentException("unexpected value type: "
                         + value.getClass().getName());
             }
         } catch (IllegalArgumentException e) {
             throw e;
         } catch (RuntimeException exc) {
             throw new IllegalArgumentException("error unparceling Bundle"exc);
         }
     }

    
Cancel any active or pending syncs that match the Uri. If the uri is null then all syncs will be canceled.

Deprecated:
instead use cancelSync(android.accounts.Account,java.lang.String)
Parameters:
uri the uri of the provider to sync or null to sync all providers.
 
     @Deprecated
     public void cancelSync(Uri uri) {
         cancelSync(null /* all accounts */uri != null ? uri.getAuthority() : null);
     }

    
Cancel any active or pending syncs that match account and authority. The account and authority can each independently be set to null, which means that syncs with any account or authority, respectively, will match.

Parameters:
account filters the syncs that match by this account
authority filters the syncs that match by this authority
    public static void cancelSync(Account accountString authority) {
        try {
            getContentService().cancelSync(accountauthority);
        } catch (RemoteException e) {
        }
    }

    
Get information about the SyncAdapters that are known to the system.

Returns:
an array of SyncAdapters that have registered with the system
    public static SyncAdapterType[] getSyncAdapterTypes() {
        try {
            return getContentService().getSyncAdapterTypes();
        } catch (RemoteException e) {
            throw new RuntimeException("the ContentService should always be reachable"e);
        }
    }

    
Check if the provider should be synced when a network tickle is received

Parameters:
account the account whose setting we are querying
authority the provider whose setting we are querying
Returns:
true if the provider should be synced when a network tickle is received
    public static boolean getSyncAutomatically(Account accountString authority) {
        try {
            return getContentService().getSyncAutomatically(accountauthority);
        } catch (RemoteException e) {
            throw new RuntimeException("the ContentService should always be reachable"e);
        }
    }

    
Set whether or not the provider is synced when it receives a network tickle.

Parameters:
account the account whose setting we are querying
authority the provider whose behavior is being controlled
sync true if the provider should be synced when tickles are received for it
    public static void setSyncAutomatically(Account accountString authorityboolean sync) {
        try {
            getContentService().setSyncAutomatically(accountauthoritysync);
        } catch (RemoteException e) {
            // exception ignored; if this is thrown then it means the runtime is in the midst of
            // being restarted
        }
    }

    
Specifies that a sync should be requested with the specified the account, authority, and extras at the given frequency. If there is already another periodic sync scheduled with the account, authority and extras then a new periodic sync won't be added, instead the frequency of the previous one will be updated.

These periodic syncs honor the "syncAutomatically" and "masterSyncAutomatically" settings. Although these sync are scheduled at the specified frequency, it may take longer for it to actually be started if other syncs are ahead of it in the sync operation queue. This means that the actual start time may drift.

Periodic syncs are not allowed to have any of SYNC_EXTRAS_DO_NOT_RETRY, SYNC_EXTRAS_IGNORE_BACKOFF, SYNC_EXTRAS_IGNORE_SETTINGS, SYNC_EXTRAS_INITIALIZE, SYNC_EXTRAS_FORCE, SYNC_EXTRAS_EXPEDITED, SYNC_EXTRAS_MANUAL set to true. If any are supplied then an java.lang.IllegalArgumentException will be thrown.

Parameters:
account the account to specify in the sync
authority the provider to specify in the sync request
extras extra parameters to go along with the sync request
pollFrequency how frequently the sync should be performed, in seconds.
Throws:
java.lang.IllegalArgumentException if an illegal extra was set or if any of the parameters are null.
    public static void addPeriodicSync(Account accountString authorityBundle extras,
            long pollFrequency) {
        validateSyncExtrasBundle(extras);
        if (account == null) {
            throw new IllegalArgumentException("account must not be null");
        }
        if (authority == null) {
            throw new IllegalArgumentException("authority must not be null");
        }
        if (extras.getBoolean(false)
                || extras.getBoolean(false)
                || extras.getBoolean(false)
                || extras.getBoolean(false)
                || extras.getBoolean(false)
                || extras.getBoolean(false)
                || extras.getBoolean(false)) {
            throw new IllegalArgumentException("illegal extras were set");
        }
        try {
            getContentService().addPeriodicSync(accountauthorityextraspollFrequency);
        } catch (RemoteException e) {
            // exception ignored; if this is thrown then it means the runtime is in the midst of
            // being restarted
        }
    }

    
Remove a periodic sync. Has no affect if account, authority and extras don't match an existing periodic sync.

Parameters:
account the account of the periodic sync to remove
authority the provider of the periodic sync to remove
extras the extras of the periodic sync to remove
    public static void removePeriodicSync(Account accountString authorityBundle extras) {
        validateSyncExtrasBundle(extras);
        if (account == null) {
            throw new IllegalArgumentException("account must not be null");
        }
        if (authority == null) {
            throw new IllegalArgumentException("authority must not be null");
        }
        try {
            getContentService().removePeriodicSync(accountauthorityextras);
        } catch (RemoteException e) {
            throw new RuntimeException("the ContentService should always be reachable"e);
        }
    }

    
Get the list of information about the periodic syncs for the given account and authority.

Parameters:
account the account whose periodic syncs we are querying
authority the provider whose periodic syncs we are querying
Returns:
a list of PeriodicSync objects. This list may be empty but will never be null.
    public static List<PeriodicSyncgetPeriodicSyncs(Account accountString authority) {
        if (account == null) {
            throw new IllegalArgumentException("account must not be null");
        }
        if (authority == null) {
            throw new IllegalArgumentException("authority must not be null");
        }
        try {
            return getContentService().getPeriodicSyncs(accountauthority);
        } catch (RemoteException e) {
            throw new RuntimeException("the ContentService should always be reachable"e);
        }
    }

    
Check if this account/provider is syncable.

Returns:
>0 if it is syncable, 0 if not, and <0 if the state isn't known yet.
    public static int getIsSyncable(Account accountString authority) {
        try {
            return getContentService().getIsSyncable(accountauthority);
        } catch (RemoteException e) {
            throw new RuntimeException("the ContentService should always be reachable"e);
        }
    }

    
Set whether this account/provider is syncable.

Parameters:
syncable >0 denotes syncable, 0 means not syncable, <0 means unknown
    public static void setIsSyncable(Account accountString authorityint syncable) {
        try {
            getContentService().setIsSyncable(accountauthoritysyncable);
        } catch (RemoteException e) {
            // exception ignored; if this is thrown then it means the runtime is in the midst of
            // being restarted
        }
    }

    
Gets the master auto-sync setting that applies to all the providers and accounts. If this is false then the per-provider auto-sync setting is ignored.

Returns:
the master auto-sync setting that applies to all the providers and accounts
    public static boolean getMasterSyncAutomatically() {
        try {
            return getContentService().getMasterSyncAutomatically();
        } catch (RemoteException e) {
            throw new RuntimeException("the ContentService should always be reachable"e);
        }
    }

    
Sets the master auto-sync setting that applies to all the providers and accounts. If this is false then the per-provider auto-sync setting is ignored.

Parameters:
sync the master auto-sync setting that applies to all the providers and accounts
    public static void setMasterSyncAutomatically(boolean sync) {
        try {
            getContentService().setMasterSyncAutomatically(sync);
        } catch (RemoteException e) {
            // exception ignored; if this is thrown then it means the runtime is in the midst of
            // being restarted
        }
    }

    
Returns true if there is currently a sync operation for the given account or authority in the pending list, or actively being processed.

Parameters:
account the account whose setting we are querying
authority the provider whose behavior is being queried
Returns:
true if a sync is active for the given account or authority.
    public static boolean isSyncActive(Account accountString authority) {
        try {
            return getContentService().isSyncActive(accountauthority);
        } catch (RemoteException e) {
            throw new RuntimeException("the ContentService should always be reachable"e);
        }
    }

    
If a sync is active returns the information about it, otherwise returns false.

Returns:
the SyncInfo for the currently active sync or null if one is not active.
    public static SyncInfo getCurrentSync() {
        try {
            return getContentService().getCurrentSync();
        } catch (RemoteException e) {
            throw new RuntimeException("the ContentService should always be reachable"e);
        }
    }

    
Returns the status that matches the authority.

Parameters:
account the account whose setting we are querying
authority the provider whose behavior is being queried
Returns:
the SyncStatusInfo for the authority, or null if none exists
Hide:
    public static SyncStatusInfo getSyncStatus(Account accountString authority) {
        try {
            return getContentService().getSyncStatus(accountauthority);
        } catch (RemoteException e) {
            throw new RuntimeException("the ContentService should always be reachable"e);
        }
    }

    
Return true if the pending status is true of any matching authorities.

Parameters:
account the account whose setting we are querying
authority the provider whose behavior is being queried
Returns:
true if there is a pending sync with the matching account and authority
    public static boolean isSyncPending(Account accountString authority) {
        try {
            return getContentService().isSyncPending(accountauthority);
        } catch (RemoteException e) {
            throw new RuntimeException("the ContentService should always be reachable"e);
        }
    }

    
Request notifications when the different aspects of the SyncManager change. The different items that can be requested are: The caller can set one or more of the status types in the mask for any given listener registration.

Parameters:
mask the status change types that will cause the callback to be invoked
callback observer to be invoked when the status changes
Returns:
a handle that can be used to remove the listener at a later time
    public static Object addStatusChangeListener(int maskfinal SyncStatusObserver callback) {
        if (callback == null) {
            throw new IllegalArgumentException("you passed in a null callback");
        }
        try {
            ISyncStatusObserver.Stub observer = new ISyncStatusObserver.Stub() {
                public void onStatusChanged(int whichthrows RemoteException {
                    callback.onStatusChanged(which);
                }
            };
            getContentService().addStatusChangeListener(maskobserver);
            return observer;
        } catch (RemoteException e) {
            throw new RuntimeException("the ContentService should always be reachable"e);
        }
    }

    
Remove a previously registered status change listener.

Parameters:
handle the handle that was returned by addStatusChangeListener(int,android.content.SyncStatusObserver)
    public static void removeStatusChangeListener(Object handle) {
        if (handle == null) {
            throw new IllegalArgumentException("you passed in a null handle");
        }
        try {
        } catch (RemoteException e) {
            // exception ignored; if this is thrown then it means the runtime is in the midst of
            // being restarted
        }
    }

    
Returns sampling percentage for a given duration. Always returns at least 1%.
    private int samplePercentForDuration(long durationMillis) {
        if (durationMillis >= ) {
            return 100;
        }
        return (int) (100 * durationMillis / ) + 1;
    }
    private void maybeLogQueryToEventLog(long durationMillis,
                                         Uri uriString[] projection,
                                         String selectionString sortOrder) {
        int samplePercent = samplePercentForDuration(durationMillis);
        if (samplePercent < 100) {
            synchronized () {
                if (.nextInt(100) >= samplePercent) {
                    return;
                }
            }
        }
        StringBuilder projectionBuffer = new StringBuilder(100);
        if (projection != null) {
            for (int i = 0; i < projection.length; ++i) {
                // Note: not using a comma delimiter here, as the
                // multiple arguments to EventLog.writeEvent later
                // stringify with a comma delimiter, which would make
                // parsing uglier later.
                if (i != 0) projectionBuffer.append('/');
                projectionBuffer.append(projection[i]);
            }
        }
        // ActivityThread.currentPackageName() only returns non-null if the
        // current thread is an application main thread.  This parameter tells
        // us whether an event loop is blocked, and if so, which app it is.
        String blockingPackage = AppGlobals.getInitialPackage();
        EventLog.writeEvent(
            .,
            uri.toString(),
            projectionBuffer.toString(),
            selection != null ? selection : "",
            sortOrder != null ? sortOrder : "",
            durationMillis,
            blockingPackage != null ? blockingPackage : "",
            samplePercent);
    }
    private void maybeLogUpdateToEventLog(
        long durationMillisUri uriString operationString selection) {
        int samplePercent = samplePercentForDuration(durationMillis);
        if (samplePercent < 100) {
            synchronized () {
                if (.nextInt(100) >= samplePercent) {
                    return;
                }
            }
        }
        String blockingPackage = AppGlobals.getInitialPackage();
        EventLog.writeEvent(
            .,
            uri.toString(),
            operation,
            selection != null ? selection : "",
            durationMillis,
            blockingPackage != null ? blockingPackage : "",
            samplePercent);
    }
    private final class CursorWrapperInner extends CursorWrapper {
        private IContentProvider mContentProvider;
        public static final String TAG="CursorWrapperInner";
        private boolean mCloseFlag = false;
        CursorWrapperInner(Cursor cursorIContentProvider icp) {
            super(cursor);
             = icp;
        }
        @Override
        public void close() {
            super.close();
             = true;
        }
        @Override
        protected void finalize() throws Throwable {
            try {
                if(!) {
                    ContentResolver.this.releaseProvider();
                }
            } finally {
                super.finalize();
            }
        }
    }
    private final class ParcelFileDescriptorInner extends ParcelFileDescriptor {
        private IContentProvider mContentProvider;
        public static final String TAG="ParcelFileDescriptorInner";
        private boolean mReleaseProviderFlag = false;
            super(pfd);
             = icp;
        }
        @Override
        public void close() throws IOException {
            if(!) {
                super.close();
                ContentResolver.this.releaseProvider();
                 = true;
            }
        }
        @Override
        protected void finalize() throws Throwable {
            if (!) {
                close();
            }
        }
    }

    

Hide:
    public static final String CONTENT_SERVICE_NAME = "content";

    

Hide:
    public static IContentService getContentService() {
        if ( != null) {
            return ;
        }
        IBinder b = ServiceManager.getService();
        if (.) Log.v("ContentService""default service binder = " + b);
         = IContentService.Stub.asInterface(b);
        if (.) Log.v("ContentService""default service = " + );
        return ;
    }
    private static IContentService sContentService;
    private final Context mContext;
    private static final String TAG = "ContentResolver";
New to GrepCode? Check out our FAQ X