ContentProvider source code analysis (original)

Keywords: Database Android Java SQLite

Reprint address: http://blog.csdn.net/u010961631/article/details/14227421


I. Preface


ContentProvider, as one of the four components of Android, plays the role of data storage. This paper uses the most typical delete operation, according to Android source code, starting from the application layer getContentResolver(), step by step analysis to the content Provider, and finally to the operation of SQLite.
  1. getContentResolver().delete();  
This simple operation actually involves two steps:
1. Get the required ContentProvider object through getContentResolver();
2. Delete the data in ContentProvider by delete().

Next we will embark on this long journey.


getContentResolver

Look at the title, we want to get an object of ContentResolver, which raises two questions:
1. What is the relationship between ContentResolver object and ContentProvider?
2. How do we get the content in ContentProvider?

To answer these two questions, we need to start from the source of the code.


2.1. Relationship between ContentResolver and ContentProvider

Let's first look at the process of getting ContentResolver:
  1. @ContextImpl.java  
  2. public ContentResolver getContentResolver() {  
  3.     return mContentResolver;  
  4. }  
The mContentResolver here is initialized in the init of ContextImpl:
  1. final void init(Resources resources, ActivityThread mainThread, UserHandle user) {  
  2.     mPackageInfo = null;  
  3.     mBasePackageName = null;  
  4.     mResources = resources;  
  5.     mMainThread = mainThread;  
  6.     //mContentResolver is initialized as ApplicationContentResolver object  
  7.     mContentResolver = new ApplicationContentResolver(this, mainThread, user);  
  8.     mUser = user;  
  9. }  
mContentResolver is initialized as an ApplicationContentResolver object. Let's look at the class ApplicationContentResolver, which is the internal class of ContextImpl:
  1. private static final class ApplicationContentResolver extends ContentResolver {  
  2.     public ApplicationContentResolver( Context context, ActivityThread mainThread, UserHandle user) { }  
  3.     protected IContentProvider acquireProvider(Context context, String auth) { }  
  4.     protected IContentProvider acquireExistingProvider(Context context, String auth) { }  
  5.     public boolean releaseProvider(IContentProvider provider) { }  
  6.     protected IContentProvider acquireUnstableProvider(Context c, String auth) { }  
  7.     public boolean releaseUnstableProvider(IContentProvider icp) { }  
  8.     public void unstableProviderDied(IContentProvider icp) { }  
  9. }  
He provides various ways to get IContentProvider and inherits from the ContentResolver class. Let's look at the properties of this class:
  1. @ContentResolver.java  
  2. public abstract class ContentResolver { }  
As you can see, ContentResolver does not inherit any classes or interfaces, so we can assume that ContentResolver has nothing to do with ContentProvider in terms of inheritance.

How did we finally get the ContentProvider?


2.2. How to get ContentProvider through ContentResolver

Next, let's answer the second question, how do we query the content in the Content Provider through the Content Resolver?
Although we know that there is no connection between the two in terms of inheritance, there are some familiar methods within ContentResolver, including:
  1. public final Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {}  
  2. public final int delete(Uri url, String where, String[] selectionArgs){}  
  3. public final int update(Uri uri, ContentValues values, String where, String[] selectionArgs) {}  
  4. public final Uri insert(Uri url, ContentValues values){}  
This shows that there must be a functional connection between the two. Let's start with the delete operation and see what the relationship is.
Back to the original invocation location, when we need to delete a data through ContentProvider, we call the getContentResolver().delete() method. The above analysis shows that getContentResolver() gets the object of Application ContentResolver, and Application ContentResolver inherits from ContentResol. Ver. Therefore, the delete operation falls into ContentResolver:
  1. @ContentResolver.java  
  2. public final int delete(Uri url, String where, String[] selectionArgs)  
  3. {  
  4.     IContentProvider provider = acquireProvider(url);  
  5.     try {  
  6.         int rowsDeleted = provider.delete(url, where, selectionArgs);  
  7.     } catch (RemoteException e) {  
  8.     } finally {  
  9.     }  
  10. }  
In this step, we first get the IContentProvider object through acquireProvider(), and then call the delete method of the IContentProvider object for operation. So how do I get the IContentProvider object through acquireProvider()?
  1. public final IContentProvider acquireProvider(Uri uri) {  
  2.     //Safety confirmation  
  3.     if (!SCHEME_CONTENT.equals(uri.getScheme())) {  
  4.         return null;  
  5.     }  
  6.     final String auth = uri.getAuthority();  
  7.     if (auth != null) {  
  8.         //Continue calling  
  9.         return acquireProvider(mContext, auth);  
  10.     }  
  11.     return null;  
  12. }  
Continue to see:
  1. protected abstract IContentProvider acquireProvider(Context c, String name);  
The Abstract acquireProvider is encountered here, which indicates that this method needs to be implemented in subclasses, so let's go to Application Content Resolver and see:
  1. @ContextImpl.java  
  2. private static final class ApplicationContentResolver extends ContentResolver {  
  3.     //Sure enough, the acquireProvider method was found.  
  4.     protected IContentProvider acquireProvider(Context context, String auth) {  
  5.         return mMainThread.acquireProvider(context, auth, mUser.getIdentifier(), true);  
  6.     }  
  7. }  
We did find the acquireProvider() method in Application Content Resolver, and found that the return value provided by the acquireProvider method was from the acquireProvider method of the mMainThread object.
So where did this mMainThread come from?

The process described in the following section is rather complicated, you have a good look.


2.3. Looking for the origin of mMainThread object

After creating an Activity in ActivityThread, the createBaseContextForActivity() method in ActivityThread is invoked to create Context objects and mMainThread objects for the current Activity:
  1. @ActivityThread.java  
  2. private Context createBaseContextForActivity(ActivityClientRecord r, final Activity activity) {  
  3.     //This is where the Context object is created.  
  4.     ContextImpl appContext = new ContextImpl();  
  5.     //And pass the current ActivityThread object to the init method of ContextImpl  
  6.     appContext.init(r.packageInfo, r.token, this);  
  7. }  
At this point, the init method in ContextImpl will be invoked:
  1. @ContextImpl.java  
  2. //Here mainThread is the ActivityThread object  
  3. final void init(LoadedApk packageInfo, IBinder activityToken, ActivityThread mainThread) {  
  4.     init(packageInfo, activityToken, mainThread, nullnull, Process.myUserHandle());  
  5. }  
  6. final void init(LoadedApk packageInfo, IBinder activityToken, ActivityThread mainThread, Resources container, String basePackageName, UserHandle user){  
  7.     //mMainThread is the ActivityThread object  
  8.     mMainThread = mainThread;  
  9.     mContentResolver = new ApplicationContentResolver(this, mainThread, user);  
  10. }  
In this process, we find that mMainThread is an ActivityThread object, so the mMainThread.acquireProvider() we introduced in 2.2 is equivalent to:
  1. ActivityThread.acquireProvider();  
Let's continue to see:
  1. @ActivityThread.java  
  2. public final IContentProvider acquireProvider( Context c, String auth, int userId, boolean stable) {  
  3.     final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);  
  4.     if (provider != null) {  
  5.         return provider;  
  6.     }  
  7.   
  8.     IActivityManager.ContentProviderHolder holder = null;  
  9.     try {  
  10.         holder = ActivityManagerNative.getDefault().getContentProvider( getApplicationThread(), auth, userId, stable);  
  11.     } catch (RemoteException ex) {  
  12.     }  
  13.   
  14.     holder = installProvider(c, holder, holder.info, true , holder.noReleaseNeeded, stable);  
  15.     return holder.provider;  
  16. }  
As you can see here, there is a HashMap in ActivityThread that caches all providers. Each request to a provider will first query whether it has been cached by acquireExistingProvider(), and if there is no caching, create the ContentProvider Holder object of the provider, and cache it to facilitate the next call.

Assuming that there is no ContactsProvider cache at present, the provider will be created through ActivityManager Native. getDefault (). getContentProvider (). Let's analyze the process of creating this provider.


2.4. ActivityThread's process of creating ContentProvider.

As mentioned earlier, ActivityThread creates ContentProvider by:
  1. ActivityManagerNative.getDefault().getContentProvider( getApplicationThread(), auth, userId, stable);  

The process can be divided into two steps:

1. Let's look at the objects obtained through ActivityManagerNative.getDefault().

2. Let's analyze the getContentProvider method of this object.

2.4.1, ActivityManagerNative object.

Let's first introduce the Activity Manager Service service.
When the system is started, some important Servers will be started in System Server, including Activity Manager Service:
  1. @SystemServer.java  
  2. public void run() {  
  3.     //Start Activity Manager Service  
  4.     context = ActivityManagerService.main(factoryTest);  
  5.     //Register Activity Manager Service  
  6.     ActivityManagerService.setSystemProcess();  
  7. }  
The result of the above call to the ActivityManagerService.main method is to start the ActivityManagerService and then call setSystemProcess to register the ActivityManagerService to the system:
  1. @ActivityManagerService.java  
  2. public static void setSystemProcess() {  
  3.     try {  
  4.         ActivityManagerService m = mSelf;  
  5.         //Server that registers itself as an "activity"  
  6.         ServiceManager.addService("activity", m, true);  
  7.         ServiceManager.addService("meminfo"new MemBinder(m));  
  8.         ServiceManager.addService("gfxinfo"new GraphicsBinder(m));  
  9.         ServiceManager.addService("dbinfo"new DbBinder(m));  
  10.     } catch (PackageManager.NameNotFoundException e) {  
  11.     }  
  12. }  
Let's look at the inheritance relationship of Activity Manager Service:
  1. public final class ActivityManagerService extends ActivityManagerNative implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {}   
Explain that the Server inherits from Activity Manager Native, and that the parent class mainly performs some Binder operations.
In this way, we have a general understanding of the structure of Activity Manager Native. According to the Binder communication mechanism, if we request the service of Activity Manager Service across processes, we will call his asBinder() method and return his IBinder object to the client for use.
Next, in our analysis above, we divide the creation of ContentProvider into two steps in Section 2.4. The first step is to get the ActivityManager Native. getDefault () object. Now let's look at the source code:
  1. @ActivityManagerNative.java  
  2. static public IActivityManager getDefault() {  
  3.     return gDefault.get();  
  4. }  
Let's see, the result of calling the getDefault() method of ActivityManager Native is to get the data in the gDefault object, so what kind of data is there in the gDefault? Let's look at his definition:
  1. private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {  
  2.     protected IActivityManager create() {  
  3.         IBinder b = ServiceManager.getService("activity");  
  4.         IActivityManager am = asInterface(b);  
  5.         return am;  
  6.     }  
  7. };  
Originally, in the process of initializing gDefault variables (create), two important operations were completed:
1. Get the remote Binder of Activity Manager Service through getService("activity");
2. The remote proxy of the service is obtained by using the obtained Biner object through the asInterface() method.
For getting Binder objects, this is determined by the Binder system. We don't need to look at it much. Let's see how to get a remote agent for services through Binder:
  1. static public IActivityManager asInterface(IBinder obj) {  
  2.     if (obj == null) {  
  3.         return null;  
  4.     }  
  5.     IActivityManager in = (IActivityManager)obj.queryLocalInterface(descriptor);  
  6.     if (in != null) {  
  7.         return in;  
  8.     }  
  9.     return new ActivityManagerProxy(obj);  
  10. }  
Through the details of asInterface(), we find that the remote proxy object we get is the ActivityManagerProxy object. That is to say, we originally:
  1. ActivityManagerNative.getDefault().getContentProvider( getApplicationThread(), auth, userId, stable);  
In fact, it is equivalent to:
  1. ActivityManagerProxy.getContentProvider(getApplicationThread(), auth, userId, stable);;  
Now that we have figured out the first step mentioned in 2.4, let's analyze the second one.

2.4.2. getContentProvider operation of proxy object

This step, of course, occurs in the ActivityManagerProxy class:
  1. @ActivityManagerNative.java  
  2. class ActivityManagerProxy implements IActivityManager{  
  3.     public ContentProviderHolder getContentProvider(IApplicationThread caller,  
  4.             String name, int userId, boolean stable) throws RemoteException {  
  5.         Parcel data = Parcel.obtain();  
  6.         Parcel reply = Parcel.obtain();  
  7.         data.writeInterfaceToken(IActivityManager.descriptor);  
  8.         data.writeStrongBinder(caller != null ? caller.asBinder() : null);  
  9.         data.writeString(name);  
  10.         data.writeInt(userId);  
  11.         data.writeInt(stable ? 1 : 0);  
  12.         //Send a request to Activity Manager Native  
  13.         mRemote.transact(GET_CONTENT_PROVIDER_TRANSACTION, data, reply, 0);  
  14.         reply.readException();  
  15.         int res = reply.readInt();  
  16.         ContentProviderHolder cph = null;  
  17.         if (res != 0) {  
  18.             cph = ContentProviderHolder.CREATOR.createFromParcel(reply);  
  19.         }  
  20.         data.recycle();  
  21.         reply.recycle();  
  22.         return cph;  
  23.     }  
  24. }  
We see that in the process of getContentProvider, Activity Manager Proxy sends requests to ActiveyManager Native at the far end through mRemote, and the request code is GET_CONTENT_PROVIDER_TRANSACTION.
Activity Manager Native needs to receive requests in onTransact():
  1. @ActivityManagerNative.java  
  2. public abstract class ActivityManagerNative extends Binder implements IActivityManager{  
  3.     //Processing various requests  
  4.     public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {  
  5.         switch (code) {  
  6.             case GET_CONTENT_PROVIDER_TRANSACTION: {  
  7.                    data.enforceInterface(IActivityManager.descriptor);  
  8.                    IBinder b = data.readStrongBinder();  
  9.                    IApplicationThread app = ApplicationThreadNative.asInterface(b);  
  10.                    String name = data.readString();  
  11.                    int userId = data.readInt();  
  12.                    boolean stable = data.readInt() != 0;  
  13.                    //Call the getContentProvider method of ActivityManagerService  
  14.                    ContentProviderHolder cph = getContentProvider(app, name, userId, stable);  
  15.                    reply.writeNoException();  
  16.                    if (cph != null) {  
  17.                        reply.writeInt(1);  
  18.                        cph.writeToParcel(reply, 0);  
  19.                    } else {  
  20.                        reply.writeInt(0);  
  21.                    }  
  22.                    return true;  
  23.             }  
  24.         }  
  25.     }  
  26. }  
In onTransact, the request is sent to the real server-side ActivityManagerService.getContentProvider():
  1. @ActivityManagerService.java  
  2. public final ContentProviderHolder getContentProvider( IApplicationThread caller, String name, int userId, boolean stable) {  
  3.     return getContentProviderImpl(caller, name, null, stable, userId);  
  4. }  
Continue to see how the server operates:
  1. private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller, String name, IBinder token, boolean stable, int userId) {  
  2.     ContentProviderRecord cpr;  
  3.     ContentProviderConnection conn = null;  
  4.     ProviderInfo cpi = null;  
  5.   
  6.     synchronized(this) {  
  7.         //Query whether the ContentProvider Record already exists in the cache  
  8.         cpr = mProviderMap.getProviderByName(name, userId);  
  9.         boolean providerRunning = cpr != null;  
  10.         if (providerRunning) {  
  11.             //If the provider has been run  
  12.             //ProviderInfo to get the ContentProviderRecord  
  13.             cpi = cpr.info;  
  14.             if (r != null && cpr.canRunHere(r)) {  
  15.                 //Pass the ContentProvider Holder directly to the client  
  16.                 ContentProviderHolder holder = cpr.newHolder(null);  
  17.                 //Empty its provider and initialize the provider's object by the client itself  
  18.                 holder.provider = null;  
  19.                 return holder;  
  20.             }  
  21.         }  
  22.   
  23.         if (!providerRunning) {  
  24.             //Currently not running  
  25.             //Load the provider's package to get ProviderInfo  
  26.             cpi = AppGlobals.getPackageManager().resolveContentProvider(name, STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);  
  27.   
  28.             //Create ContentProviderRecord for the current provider  
  29.             ComponentName comp = new ComponentName(cpi.packageName, cpi.name);  
  30.             cpr = mProviderMap.getProviderByClass(comp, userId);  
  31.   
  32.             //Caching the current ContentProvider Record  
  33.             mProviderMap.putProviderByName(name, cpr);  
  34.             conn = incProviderCountLocked(r, cpr, token, stable);  
  35.         }  
  36.     }  
  37.     //Pass ContentProvider Holder to the client  
  38.     return cpr != null ? cpr.newHolder(conn) : null;  
  39. }  
In the above process, we found that there is a mProviderMap variable in the Activity Manager Service to save all the provider s in the current system, each of which is a ContentProviderRecord-type data, through which two important functions can be accomplished:
1. Details of the current provider can be obtained through ContentProviderRecord.info, including the authority, readPermission, writePermission, uriPermission Patterns and other important information of the provider.
2. ContentProviderRecord.newHolder() method can be used to generate a detailed information for the current provider, which we need to package as Holder and pass to ActivityThread for use.
Let's go back to acquireProvider() in ActivityThread:
  1. public final IContentProvider acquireProvider( Context c, String auth, int userId, boolean stable) {  
  2.     final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);  
  3.   
  4.     IActivityManager.ContentProviderHolder holder = null;  
  5.     try {  
  6.         //Get the ContentProviderHolder object  
  7.         holder = ActivityManagerNative.getDefault().getContentProvider( getApplicationThread(), auth, userId, stable);  
  8.     } catch (RemoteException ex) {  
  9.     }  
  10.   
  11.     //Initialize the current provider with provider information  
  12.     holder = installProvider(c, holder, holder.info, true , holder.noReleaseNeeded, stable);  
  13.     //Get the provider object  
  14.     return holder.provider;  
  15. }  
In the previous process, we obtained the ContentProvider Holder object through Activity Manager Service, which is a detailed description of the provider. Next, we need to use these descriptions to open the provider in the installProvider() method and obtain the proxy object of the provider.
  1. private IActivityManager.ContentProviderHolder installProvider(Context context, IActivityManager.ContentProviderHolder holder, ProviderInfo info, boolean noisy, boolean noReleaseNeeded, boolean stable) {  
  2.     ContentProvider localProvider = null;  
  3.     IContentProvider provider;  
  4.     if (holder == null || holder.provider == null) {  
  5.         //The current client has not received the provider, so you need to obtain the provider remote proxy  
  6.         Context c = null;  
  7.         ApplicationInfo ai = info.applicationInfo;  
  8.         if (context.getPackageName().equals(ai.packageName)) {  
  9.             //If the provider is to be obtained, it is on the client that is currently issuing the request.  
  10.             c = context;  
  11.         } else if (mInitialApplication != null && mInitialApplication.getPackageName().equals(ai.packageName)) {  
  12.             c = mInitialApplication;  
  13.         } else {  
  14.             try {  
  15.                 //Create Context objects for provider s to be created  
  16.                 c = context.createPackageContext(ai.packageName, Context.CONTEXT_INCLUDE_CODE);  
  17.             } catch (PackageManager.NameNotFoundException e) {  
  18.             }  
  19.         }  
  20.         try {  
  21.             final java.lang.ClassLoader cl = c.getClassLoader();  
  22.             //Classes loaded with provider  
  23.             localProvider = (ContentProvider)cl.loadClass(info.name).newInstance();  
  24.             //Get the IContentProvider object of the provider  
  25.             provider = localProvider.getIContentProvider();  
  26.             localProvider.attachInfo(c, info);  
  27.         } catch (java.lang.Exception e) {  
  28.         }  
  29.     } else {  
  30.         //If the corresponding provider has been created for the client, it can be returned directly.  
  31.         provider = holder.provider;  
  32.     }  
  33.   
  34.     IActivityManager.ContentProviderHolder retHolder;  
  35.     synchronized (mProviderMap) {  
  36.         IBinder jBinder = provider.asBinder();  
  37.         //Rebuilding retHolder of ContentProvider Holder Type  
  38.         if (localProvider != null) {  
  39.             ComponentName cname = new ComponentName(info.packageName, info.name);  
  40.             ProviderClientRecord pr = mLocalProvidersByName.get(cname);  
  41.             if (pr != null) {  
  42.                 provider = pr.mProvider;  
  43.             } else {  
  44.                 //Get the remote proxy object of ContentProvider  
  45.                 holder = new IActivityManager.ContentProviderHolder(info);  
  46.                 holder.provider = provider;  
  47.                 holder.noReleaseNeeded = true;  
  48.                 pr = installProviderAuthoritiesLocked(provider, localProvider, holder);  
  49.                 mLocalProviders.put(jBinder, pr);  
  50.                 mLocalProvidersByName.put(cname, pr);  
  51.             }  
  52.             retHolder = pr.mHolder;  
  53.         } else {  
  54.             ProviderRefCount prc = mProviderRefCountMap.get(jBinder);  
  55.             if (prc != null) {  
  56.                 if (!noReleaseNeeded) {  
  57.                     incProviderRefLocked(prc, stable);  
  58.                     try {  
  59.                         ActivityManagerNative.getDefault().removeContentProvider( holder.connection, stable);  
  60.                     } catch (RemoteException e) {  
  61.                     }  
  62.                 }  
  63.             } else {  
  64.                 ProviderClientRecord client = installProviderAuthoritiesLocked(provider, localProvider, holder);  
  65.                 if (noReleaseNeeded) {  
  66.                     prc = new ProviderRefCount(holder, client, 10001000);  
  67.                 } else {  
  68.                     prc = stable  
  69.                         ? new ProviderRefCount(holder, client, 10)  
  70.                         : new ProviderRefCount(holder, client, 01);  
  71.                 }  
  72.                 mProviderRefCountMap.put(jBinder, prc);  
  73.             }  
  74.             retHolder = prc.holder;  
  75.         }  
  76.     }  
  77.     return retHolder;  
  78. }  
We clearly see that in the installProvider method, we use the ContentProvider information obtained in the Activity Manager Service to load the ContentProvider (local Provider) and call his getIContentProvider() method to get the proxy object of the provider.
Then we go back to acquireProvider in ActivityThread ():
  1. public final IContentProvider acquireProvider( Context c, String auth, int userId, boolean stable) {  
  2.     final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);  
  3.     IActivityManager.ContentProviderHolder holder = null;  
  4.     try {  
  5.         //Get the ContentProviderHolder object  
  6.         holder = ActivityManagerNative.getDefault().getContentProvider( getApplicationThread(), auth, userId, stable);  
  7.     } catch (RemoteException ex) {  
  8.     }  
  9.     //Initialize the current provider with provider information  
  10.     holder = installProvider(c, holder, holder.info, true , holder.noReleaseNeeded, stable);  
  11.     //Return the provider proxy object to the client call  
  12.     return holder.provider;  
  13. }  

After the above analysis, we get the proxy object of ContentProvider from the initial getContentResolver() step by step analysis, through ContextImpl, Activity Thread, Activity Manager Native, Activity Manager Service.


3. ContentProvider Call Analysis

In the previous section, we analyzed the process of getContentResolver() and found that the result of this operation can not only load the required ContentProvider (if the current ContentProvider has not been loaded), but also call the getIContentProvider() method of the ContentProvider. In this section, we will start with this method to see how to get the ContentProvider object through this method, and how to pass the operation of the database through this object.
Let's first look at what objects we get from the getIContentProvider() method.
  1. @ContentProvider.java  
  2. public IContentProvider getIContentProvider() {  
  3.     return mTransport;  
  4. }  
What we get here is the mTransport variable of IContentProvider type, and the origin of this variable?
  1. private Transport mTransport = new Transport();  
This means that only the Transport object is obtained through the getIContentProvider() method, which is the internal class of ContentProvider:
  1. class Transport extends ContentProviderNative {  
  2.     ContentProvider getContentProvider() { }  
  3.     public String getProviderName() { }  
  4.     public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, ICancellationSignal cancellationSignal) { }  
  5.     public Uri insert(Uri uri, ContentValues initialValues) { }  
  6.     public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { }  
  7.     public int delete(Uri uri, String selection, String[] selectionArgs) { }  
  8.     public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { }  
  9. }  
Furthermore, we find that this internal class provides various operations for querying the database. What about when we delete?
  1. public int delete(Uri uri, String selection, String[] selectionArgs) {  
  2.     enforceWritePermission(uri);  
  3.     return ContentProvider.this.delete(uri, selection, selectionArgs);  
  4. }  
Since within Transport the delete operation is passed to the ContentProvider to operate, let's look at the content Provider's own handling of delete():
  1. public abstract int delete(Uri uri, String selection, String[] selectionArgs);  
Here we encounter Abstract methods, that is to say, the details of delete operations need to be implemented in the subclasses of ContentProvider, which also conforms to the design concept of ContentProvider framework, that is, ContentProvider is responsible for the expression of abstract parts, and the specific operations need to be implemented by their own private.
Let's take a look at the important ways that ContentProvider itself provides:
  1. public abstract class ContentProvider implements ComponentCallbacks2 {  
  2.     private Transport mTransport = new Transport();  
  3.     //Constructor  
  4.     public ContentProvider() { }  
  5.   
  6.     //Permission-related operations  
  7.     protected final void setReadPermission(String permission) { }  
  8.     public final String getReadPermission() { }  
  9.     protected final void setWritePermission(String permission) { }  
  10.     public final String getWritePermission() { }  
  11.   
  12.     //Add, delete, change, check operation.  
  13.     public abstract Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder);  
  14.     public abstract Uri insert(Uri uri, ContentValues values);  
  15.     public abstract int delete(Uri uri, String selection, String[] selectionArgs);  
  16.     public abstract int update(Uri uri, ContentValues values, String selection, String[] selectionArgs);  
  17.   
  18.     public IContentProvider getIContentProvider() { }  
  19.     public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { }  
  20. }  
From the methods provided by ContentProvider, we find that in addition to the methods of privilege management classes, there are some abstract methods similar to delete and related to database processing.
At this point, it is not difficult to find that this Transport object, acting as a proxy for ContentProvider, can initiate various requests for this object. When the agent receives the request, it "forwards" the request to the ContentProvider itself.
In conjunction with our analysis in the previous section, we can summarize as follows:

When we call the operation getContentResolver().delete() at the application layer, we call the delete operation of the ContentResolver object, which is equivalent to the Transport object obtained through getIContentProvider(), and the Transport object as the proxy of the ContentProvider will transfer the requests. To the ContentProvider, you call the delete method of the ContentProvider.

        getContentResolver==>ContentResolver==>Transport==>ContentProvider


IV. ContentProvider to Contacts Provider

4.1. Contacts Provider Overview

After the above process, we transferred the operation to Content provider. Next, we need to use specific providers to continue the analysis. We choose Contacts provider as an example to study.
Contact database source code is located in packages providers Contacts Provider. Let's first look at his Android Manifest. XML file:
  1. @AndroidManifest.xml  
  2. <provider android:name="ContactsProvider2"  
  3.     android:authorities="contacts;com.android.contacts"  
  4.     android:label="@string/provider_label"  
  5.     android:multiprocess="false"  
  6.     android:exported="true"  
  7.     android:readPermission="android.permission.READ_CONTACTS"  
  8.     android:writePermission="android.permission.WRITE_CONTACTS">  
  9. <path-permission  
  10.     android:pathPrefix="/search_suggest_query"  
  11.     android:readPermission="android.permission.GLOBAL_SEARCH" />  
  12. <path-permission  
  13.     android:pathPrefix="/search_suggest_shortcut"  
  14.     android:readPermission="android.permission.GLOBAL_SEARCH" />  
  15. <path-permission  
  16.     android:pathPattern="/contacts/.*/photo"  
  17.     android:readPermission="android.permission.GLOBAL_SEARCH" />  
  18. <grant-uri-permission android:pathPattern=".*" />  
  19. </provider>  
This statement tells the system the name, authorities, permission and other information of the provider. Simply put, the name of the database is Contacts Provider 2, which can be matched by contacts or the prefix of com.android.contacts, and access to the database requires the corresponding permissions READ_CONTACTS, WRITE_CONT. ACTS, etc.

4.2. Contacts Provider Structure

ContactsProvider structure involves five important classes: ContentProvider, SQLiteTransactionListener, AbstractContactsProvider, ContactsProvider 2, ProfileProvider. Let's briefly talk about their relationship.
ContactsProvider combines the ContentProvider with the SQLiteTransactionListener to compose AbstractContactsProvider, which is the most basic class of ContactsProvider. On the basis of AbstractContactsProvider, ContactsProvider 2 and ProfileProvider are extended, as shown below. Show:
        
Next, we will introduce the roles of these five categories.

4.2.1,ContactsProvider

Needless to say, this is the Contacts Provider architecture provided by the system, which leaves the interface for database operation and needs subclasses to implement.

4.2.2,SQLiteTransactionListener

This is an interface, and the content is relatively simple. There are only three ways:
  1. public interface SQLiteTransactionListener {  
  2.     /** 
  3.      * Called immediately after the transaction begins. 
  4.      */  
  5.     void onBegin();  
  6.   
  7.     /** 
  8.      * Called immediately before commiting the transaction. 
  9.      */  
  10.     void onCommit();  
  11.   
  12.     /** 
  13.      * Called if the transaction is about to be rolled back. 
  14.      */  
  15.     void onRollback();  
  16. }  
As can be seen from the annotations, he mainly provides callback methods related to transaction processing, in which onBegin is a callback function called after transaction start processing, onCommit is a callback function after transaction commit, and onRollback is a callback function when transaction rollback, so it can be inferred that onBegin is used in ContactsProvider. Transaction operates on the database.

4.2.3,AbstractContactsProvider

This is the lowest class in the ContactsProvider structure. Let's take a look at his main internal methods:
  1. public abstract class AbstractContactsProvider extends ContentProvider implements SQLiteTransactionListener {  
  2.     public SQLiteOpenHelper getDatabaseHelper() { }  
  3.     public Uri insert(Uri uri, ContentValues values) { }  
  4.     public int delete(Uri uri, String selection, String[] selectionArgs) { }  
  5.     public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { }  
  6.     public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) { }  
  7.     private ContactsTransaction startTransaction(boolean callerIsBatch) { }  
  8.     private void endTransaction(boolean callerIsBatch) { }  
  9.     protected abstract SQLiteOpenHelper getDatabaseHelper(Context context);  
  10.     protected abstract ThreadLocal<ContactsTransaction> getTransactionHolder();  
  11.     protected abstract Uri insertInTransaction(Uri uri, ContentValues values);  
  12.     protected abstract int deleteInTransaction(Uri uri, String selection, String[] selectionArgs);  
  13.     protected abstract int updateInTransaction(Uri uri, ContentValues values, String selection, String[] selectionArgs);  
  14.     protected abstract void notifyChange();  
  15. }  
These methods are well understood and are all database operations. Remember when we analyzed the delete operation of ContentProvider, we mentioned that ContentProvider handles all operations of the database in subclasses. For the current environment, it needs to be handled in AbstractContacts Provider, so the delete operation should be called here:
  1. public int delete(Uri uri, String selection, String[] selectionArgs) {  
  2.     //Start Transaction Operation  
  3.     ContactsTransaction transaction = startTransaction(false);  
  4.     try {  
  5.         //delete operations with transactions  
  6.         int deleted = deleteInTransaction(uri, selection, selectionArgs);  
  7.         if (deleted > 0) {  
  8.             transaction.markDirty();  
  9.         }  
  10.         transaction.markSuccessful(false);  
  11.         return deleted;  
  12.     } finally {  
  13.         endTransaction(false);  
  14.     }  
  15. }  
Continue to look at the implementation of deleteInTransaction:
  1. protected abstract int deleteInTransaction(Uri uri, String selection, String[] selectionArgs);  
This is still a virtual function, and specific definitions need to be left to subclasses to implement.
Here we find that in AbstractContacts Provider, insert, delete and update operations are transformed into transaction processing mode XXXInTransaction, and the specific implementation is left to subclasses, where the subclasses are Contacts Provider 2 and ProfileProvider. That is to say, the function of AbstractContacts Provider is to transform the operation of database into the way of transaction processing. As for the specific transaction operation, it needs to be implemented in its subclasses.
In addition, we noticed that only insert, delete, update operations were transformed, and there was no query operation, that is to say, query operations in ContentProvider were left directly to subclasses of subclasses to implement, and the transformation across AbstractContactsProvider was crossed. This means that query operations do not need to be translated into transaction processing.

4.2.4,ProfileProvider

Now let's look at the structure of ProfileProvider:
  1. public class ProfileProvider extends AbstractContactsProvider {  
  2.     public Cursor query(Uri uri,String[] projection,String selection,String[] selectionArgs,String sortOrder){}  
  3.     protected Uri insertInTransaction(Uri uri, ContentValues values){}  
  4.     protected int updateInTransaction(Uri uri, ContentValues values, String selection, String[] selectionArgs) {}  
  5.     protected int deleteInTransaction(Uri uri, String selection, String[] selectionArgs){}  
  6.     public void onBegin() { }  
  7.     public void onCommit() { }  
  8.     public void onRollback() { }  
  9. }  
From the structure of ProfileProvider, we can see that ProfileProvider has independent query operations, insert, delete, update transaction operations, and transaction-related callback functions. It can be said that he has complete data access and modification capabilities. But what about his role?
We'll see that later.

4.2.5,ContactsProvider2

This is the most important and top-level class in ContactsProvider, and we only registered him in Android Manifest.
Let's take a look at some of his important ways:
  1. public class ContactsProvider2 extends AbstractContactsProvider implements OnAccountsUpdateListener {  
  2.     public Cursor query(Uri uri,String[] projection,String selection,String[] selectionArgs,String sortOrder) {}  
  3.     public int delete(Uri uri, String selection, String[] selectionArgs) {}  
  4.     public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {}  
  5.     public Uri insert(Uri uri, ContentValues values) {}  
  6.     protected Uri insertInTransaction(Uri uri, ContentValues values) {}  
  7.     protected int updateInTransaction(Uri uri, ContentValues values, String selection, String[] selectionArgs) {}  
  8.     protected int deleteInTransaction(Uri uri, String selection, String[] selectionArgs) {}  
  9. }  

Similar to ProfileProvider, it also provides complete data access and modification capabilities.


Contacts Provider and SQLite


We need to understand that the bottom layer of ContentProvider is still implemented by SQLite, which only encapsulates the operation of SQLite, making it easier to operate and understand.
On the bottom design of ContactsProvider, ContactsDatabaseHelper plays the role of communicating directly with SQLite, and on this basis, it differentiates and extends the class ProfileDatabaseHelper. So you can think of two helper classes with SQLite at the bottom of ContactsProvider. Let's first look at their structure:

  1. public class ProfileDatabaseHelper extends ContactsDatabaseHelper {}  
  2. public class ContactsDatabaseHelper extends SQLiteOpenHelper {}  
Inheritance relationships are as follows:
         
Both SQLiteOpenHelper classes are initialized at onCreate() of ContactsProvider2:
  1. public boolean onCreate() {  
  2.     super.onCreate();  
  3.     return initialize();  
  4. }  
  5. private boolean initialize() {  
  6.     //Initialize Contacts Database Helper  
  7.     mContactsHelper = getDatabaseHelper(getContext());  
  8.     mDbHelper.set(mContactsHelper);  
  9.     //Initialize Profile Database Helper  
  10.     mProfileHelper = mProfileProvider.getDatabaseHelper(getContext());  
  11.     return true;  
  12. }  
Let's first look at the Contacts Database Helper initialization process:
  1. protected ContactsDatabaseHelper getDatabaseHelper(final Context context) {  
  2.     return ContactsDatabaseHelper.getInstance(context);  
  3. }  
  4. @ContactsDatabaseHelper.java  
  5. public static synchronized ContactsDatabaseHelper getInstance(Context context) {  
  6.     if (sSingleton == null) {  
  7.         //new out a Contacts Database Helper to complete initialization  
  8.         sSingleton = new ContactsDatabaseHelper(context, DATABASE_NAME, true);  
  9.     }  
  10.     return sSingleton;  
  11. }  
Look again at the Profile Database Helper initialization process:
  1. protected ProfileDatabaseHelper getDatabaseHelper(Context context) {  
  2.     return ProfileDatabaseHelper.getInstance(context);  
  3. }  
  4. public static synchronized ProfileDatabaseHelper getInstance(Context context) {  
  5.     if (sSingleton == null) {  
  6.         //new out a Profile Database Helper to complete initialization  
  7.         sSingleton = new ProfileDatabaseHelper(context, DATABASE_NAME, true);  
  8.     }  
  9.     return sSingleton;  
  10. }  
Because there are two "different" SQLLiteOpenHelper in ContactsProvider, it is necessary to switch to different SQLite OpenHelper according to different needs when operating a specific database. We'll talk about the process of switching later.
Since there are two kinds of SQLiteOpenHelper, there should be two ContentProvider s to operate these two SQLiteOpenHelpers. Indeed, on top of these two kinds of SQLite operation classes, ProfileProvider and ContactsProvider 2 are built respectively, that is to say, this is the case. The corresponding relationship between the four is similar to that shown in the following figure:
        

Next let's look at these two pairs with the aid of a delete() operation data base Operational flow direction.


5.1. Continue delete()

Let's review again that when we do delete, we call getContentResolver, which will eventually call the delete method in ContentProvider, and then the delete method in ContactsProvider 2:
  1. @ContactsProvider2.java  
  2. public int delete(Uri uri, String selection, String[] selectionArgs) {  
  3.     waitForAccess(mWriteAccessLatch);  
  4.     //Authority Management  
  5.     enforceSocialStreamWritePermission(uri);  
  6.   
  7.     //Check to see if you need to be processed in ProfileProvider  
  8.     if (mapsToProfileDb(uri)) {  
  9.         switchToProfileMode();  
  10.         //Processing in ProfileProvider  
  11.         return mProfileProvider.delete(uri, selection, selectionArgs);  
  12.     } else {  
  13.         switchToContactMode();  
  14.         //Go back to the parent class to handle delete operations  
  15.         return super.delete(uri, selection, selectionArgs);  
  16.     }  
  17. }  
In the process of delete, according to the judgment of mapsToProfileDb(), two modes need to be switched: Profile and Contact mode, which is what we just mentioned. We need to switch different SQLiteOpenHelper to operate the database according to different situations. Now let's look at the basis for distinguishing the two modes.
  1. private boolean mapsToProfileDb(Uri uri) {  
  2.     return sUriMatcher.mapsToProfile(uri);  
  3. }  
This is based on the uri given to sUriMatcher to find whether there are matching items, if there are, that need to be converted to Profile mode to process, then what are the items in sUriMatcher?
  1. @ContactsProvider2.java  
  2. static {  
  3.     final UriMatcher matcher = sUriMatcher;  
  4.     matcher.addURI(ContactsContract.AUTHORITY, "contacts", CONTACTS);  
  5.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/#", CONTACTS_ID);  
  6.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/data", CONTACTS_ID_DATA);  
  7.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/entities", CONTACTS_ID_ENTITIES);  
  8.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/suggestions", AGGREGATION_SUGGESTIONS);  
  9.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/suggestions/*", AGGREGATION_SUGGESTIONS);  
  10.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/photo", CONTACTS_ID_PHOTO);  
  11.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/display_photo", CONTACTS_ID_DISPLAY_PHOTO);  
  12.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/#/stream_items", CONTACTS_ID_STREAM_ITEMS);  
  13.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/filter", CONTACTS_FILTER);  
  14.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/filter/*", CONTACTS_FILTER);  
  15.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*", CONTACTS_LOOKUP);  
  16.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/data", CONTACTS_LOOKUP_DATA);  
  17.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/photo", CONTACTS_LOOKUP_PHOTO);  
  18.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#", CONTACTS_LOOKUP_ID);  
  19.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#/data", CONTACTS_LOOKUP_ID_DATA);  
  20.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/#/photo", CONTACTS_LOOKUP_ID_PHOTO);  
  21.     matcher.addURI(ContactsContract.AUTHORITY, "contacts/lookup/*/display_photo", CONTACTS_LOOKUP_DISPLAY_PHOTO);  
  22.     //......  
  23. }  
We found that the URIs defined in Contacts Control are all in this MAP, that is to say, when we use the URIs in Contacts Control to operate the database, we should satisfy the conditions of mapsToProfileDb.

Next, let's look at the specific operation of these two situations.


5.2. Operation of Contacts Provider 2


Let's first analyze the data flow operation and then the ProfileProvider operation. That is to say, we need switchToContactMode():

  1. private void switchToContactMode() {  
  2.     //Switch mDbHelper to mContacts Helper, or Contacts Database Helper  
  3.     mDbHelper.set(mContactsHelper);  
  4.     mTransactionContext.set(mContactTransactionContext);  
  5.     mAggregator.set(mContactAggregator);  
  6.     mPhotoStore.set(mContactsPhotoStore);  
  7.     mInProfileMode.set(false);  
  8. }  
The most important operation here is to replace the content in mDbHelper with mContacts Helper, or Contacts Database Helper. Next is the operation of super.delete(), where super is AbstractContacts Provider for Contacts Provider 2:
  1. @AbstractContactsProvider.java  
  2. public int delete(Uri uri, String selection, String[] selectionArgs) {  
  3.     ContactsTransaction transaction = startTransaction(false);  
  4.     try {  
  5.         int deleted = deleteInTransaction(uri, selection, selectionArgs);  
  6.         transaction.markSuccessful(false);  
  7.         return deleted;  
  8.     } finally {  
  9.         endTransaction(false);  
  10.     }  
  11. }  
  12. protected abstract int deleteInTransaction(Uri uri, String selection, String[] selectionArgs);  
This "transformation" operation, which we have analyzed before, is to transform delete operation into transaction processing. The specific operation needs to be implemented in subclasses, so we go back to deleteInTransaction in ContactsProvider 2:
  1. protected int deleteInTransaction(Uri uri, String selection, String[] selectionArgs) {  
  2.     //Get SQLiteOpenHelper, currently Contacts Database Helper  
  3.     final SQLiteDatabase db = mDbHelper.get().getWritableDatabase();  
  4.     //Matching results based on current uri  
  5.     final int match = sUriMatcher.match(uri);  
  6.     switch (match) {  
  7.         case CONTACTS: {  
  8.             invalidateFastScrollingIndexCache();  
  9.             return 0;  
  10.         }  
  11.         case CONTACTS_ID: {  
  12.             invalidateFastScrollingIndexCache();  
  13.             long contactId = ContentUris.parseId(uri);  
  14.             return deleteContact(contactId, callerIsSyncAdapter);  
  15.         }  
  16.         default: {  
  17.             mSyncToNetwork = true;  
  18.             return mLegacyApiSupport.delete(uri, selection, selectionArgs);  
  19.         }  
  20.     }  
  21. }  
Here we assume that the match is CONTACTS_ID:
  1. private int deleteContact(long contactId, boolean callerIsSyncAdapter) {  
  2.     //Get SQLiteOpenHelper  
  3.     final SQLiteDatabase db = mDbHelper.get().getWritableDatabase();  
  4.     mSelectionArgs1[0] = Long.toString(contactId);  
  5.     //Inquire about relevant information first  
  6.     Cursor c = db.query(Tables.RAW_CONTACTS, new String[]{RawContacts._ID}, RawContacts.CONTACT_ID + "=?", mSelectionArgs1, nullnullnull);  
  7.     try {  
  8.         while (c.moveToNext()) {  
  9.             long rawContactId = c.getLong(0);  
  10.             markRawContactAsDeleted(db, rawContactId, callerIsSyncAdapter);  
  11.         }  
  12.     } finally {  
  13.         c.close();  
  14.     }  
  15.   
  16.     mProviderStatusUpdateNeeded = true;  
  17.     //Delete SQLite  
  18.     return db.delete(Tables.CONTACTS, Contacts._ID + "=" + contactId, null);  
  19. }  
In the process of deleting the Contact, we need to get the available SQLLiteDatabase first. Currently, we need to get the SQLLiteDatabase of the Contacts Database Helper, then query the database to get the Cursor, and traverse each tag to delete it. Finally, we call the delete() method of the SQLiteDatabase to delete the record.
Let's look at the delete() process of SQLiteDatabase in detail:
  1. @SQLiteDatabase.java  
  2. public int delete(String table, String whereClause, String[] whereArgs) {  
  3.     acquireReference();  
  4.     try {  
  5.         //Constructing SQL Statements  
  6.         SQLiteStatement statement =  new SQLiteStatement(this"DELETE FROM " + table + (!TextUtils.isEmpty(whereClause) ? " WHERE " + whereClause : ""), whereArgs);  
  7.         try {  
  8.             //Execute Delete Command  
  9.             return statement.executeUpdateDelete();  
  10.         } finally {  
  11.             statement.close();  
  12.         }  
  13.     } finally {  
  14.         releaseReference();  
  15.     }  
  16. }  
We see that in the delete operation, we first generate the SQL statement (DELETE FROM XXX WHERE XXX) through the SQLiteStatement, and then apply the SQL operation through the executeUpdate Delete () method to complete the delete operation.

At this point, we have finally completed the "journey" from Content Provider to SQLite.


5.3. Operation of ProfileProvider

The first step is to switch the database to Profile Database Helper:
  1. private void switchToProfileMode() {  
  2.     //Setting Profile Database Helper for mDbHelper  
  3.     mDbHelper.set(mProfileHelper);  
  4.     mTransactionContext.set(mProfileTransactionContext);  
  5.     mAggregator.set(mProfileAggregator);  
  6.     mPhotoStore.set(mProfilePhotoStore);  
  7.     mInProfileMode.set(true);  
  8. }  
Then delete the action:
  1. mProfileProvider.delete(uri, selection, selectionArgs);  
The delete method in ProfileProvider is called, but the delete method is not found in ProfileProvider. We can only call delete() in its parent class AbstractContactsProvider:
  1. @AbstractContactsProvider.java  
  2. public int delete(Uri uri, String selection, String[] selectionArgs) {  
  3.     ContactsTransaction transaction = startTransaction(false);  
  4.     try {  
  5.         //Converting delete to transaction processing  
  6.         int deleted = deleteInTransaction(uri, selection, selectionArgs);  
  7.         if (deleted > 0) {  
  8.             transaction.markDirty();  
  9.         }  
  10.         transaction.markSuccessful(false);  
  11.         return deleted;  
  12.     } finally {  
  13.         endTransaction(false);  
  14.     }  
  15. }  
  16. protected abstract int deleteInTransaction(Uri uri, String selection, String[] selectionArgs);  
After the "transformation" of AbstractContacts Provider, the delete operation is converted to deleteInTransaction():
  1. @ProfileProvider.java  
  2. protected int deleteInTransaction(Uri uri, String selection, String[] selectionArgs) {  
  3.     enforceWritePermission();  
  4.     useProfileDbForTransaction();  
  5.     return mDelegate.deleteInTransaction(uri, selection, selectionArgs);  
  6. }  

mDelegate here is Contacts Provider 2 itself, so it disturbs the ProfileProvider and goes back to deleteInTransaction() in Contacts Provider 2, which we have described in detail in Section 5.2.


VI. SUMMARY


Now let's review the whole process:
1. When we call getContentResolver().delete(), we get the ContentResolver object through getContentResolver(), and then call the delete() method of the object.
2. In Content Resolver, the IContentProvider object is acquired by acquiProvider (), and the acquisition of this object first requires the ContentProvider Holder applied to the Activity Manager Service in ActivityThread, and then the Holder is used to obtain the IContentProvider object. TProvider) The remote proxy object (Transport object) of ContentProvider.
3. When you get this object, call its delete method, which will be passed by ContentProvider to its subclass (AbstractContacts Provider), and convert delete operation into transaction processing (deleteInTransaction) in the subclass, although in AbstractContacts Provider, the delete method will be transformed into a transaction. The way transactions are done, but there is no specific implementation. Instead, specific operations are left to their subclasses (ContactsProvider2).
4. ContactsProvider2 will use the corresponding SQLiteOpenHelper to translate operations into specific SQLite statements and execute them in the implementation process.
Next, let's finish the study with a picture.
        


Posted by hookit on Sun, 07 Jul 2019 15:50:41 -0700