Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Content Provider 跨應用共享資料的原理剖析

編輯:關於 Android 程式設計

本文參考羅升陽先生的〈Android 應用程序組件 Content Provider 在應用程序之間共享數據的原理分析〉一文與《Android 系統源代碼情景分析》,並以自己的方式重新梳理流程。

零、整體流程

總體類圖:

整個過程可以拆成八個步驟,其中兩端分別是 MainActivity 進程與 ArticlesProvider 進程,中間透過 Binder 與匿名共享內存協作。

一、第一步:客戶端發起查詢

相關程式碼位於 frameworks/base/core/java/android/content/ContentProviderNative.java:

final class ContentProviderProxy implements IContentProvider {
    ......
    public Cursor query(Uri url, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder)
            throws RemoteException {
        // TODO make a pool of windows so we can reuse memory dealers
        CursorWindow window = new CursorWindow(false /* window will be used remotely */);
        BulkCursorToCursorAdaptor adaptor = new BulkCursorToCursorAdaptor();
        IBulkCursor bulkCursor = bulkQueryInternal(url, projection, selection,
                selectionArgs, sortOrder, adaptor.getObserver(), window, adaptor);
        if (bulkCursor == null) {
            return null;
        }
        return adaptor;
    }
    ......
}

這一段做了三件事:

(1)建立 CursorWindow 物件——這是後續傳輸查詢結果的匿名共享內存載體。

(2)建立 BulkCursorToCursorAdaptor 物件,作為客戶端看到的 Cursor 實作。

(3)呼叫 bulkQueryInternal 展開真正的跨進程請求。

二、第二步:把參數寫進 Parcel

final class ContentProviderProxy implements IContentProvider {
    ......
    private IBulkCursor bulkQueryInternal(Uri url, String[] projection,
            String selection, String[] selectionArgs, String sortOrder,
            IContentObserver observer, CursorWindow window,
            BulkCursorToCursorAdaptor adaptor) throws RemoteException {

        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IContentProvider.descriptor);
        url.writeToParcel(data, 0);

        int length = 0;
        if (projection != null) length = projection.length;
        data.writeInt(length);
        for (int i = 0; i < length; i++) data.writeString(projection[i]);

        data.writeString(selection);
        if (selectionArgs != null) length = selectionArgs.length;
        else length = 0;
        data.writeInt(length);
        for (int i = 0; i < length; i++) data.writeString(selectionArgs[i]);

        data.writeString(sortOrder);
        data.writeStrongBinder(observer.asBinder());
        window.writeToParcel(data, 0);

        // 是否希望回傳 rowCount 與 _id 欄位位置
        final boolean wantsCursorMetadata = (adaptor != null);
        data.writeInt(wantsCursorMetadata ? 1 : 0);

        mRemote.transact(IContentProvider.QUERY_TRANSACTION, data, reply, 0);
        DatabaseUtils.readExceptionFromParcel(reply);

        IBulkCursor bulkCursor = null;
        IBinder bulkCursorBinder = reply.readStrongBinder();
        if (bulkCursorBinder != null) {
            bulkCursor = BulkCursorNative.asInterface(bulkCursorBinder);
            if (wantsCursorMetadata) {
                int rowCount = reply.readInt();
                int idColumnPosition = reply.readInt();
                if (bulkCursor != null) {
                    adaptor.set(bulkCursor, rowCount, idColumnPosition);
                }
            }
        }
        data.recycle();
        reply.recycle();
        return bulkCursor;
    }
    ......
}

這裡我們只關注 window.writeToParcel(data, 0)。這一行是理解 Content Provider 效能設計的鑰匙:CursorWindow 並不是把資料內容寫進 Parcel,而是把 ashmem 匿名共享內存的 fd 寫進去。fd 可以跨進程傳遞,於是雙方得以對同一片記憶體進行讀寫,而不必把整批資料在 Binder 上序列化傳輸一遍。

第二步之後省略 Binder 驅動的傳輸過程(前面已分析過)。

三、第三步:服務端 onTransact 分派

abstract public class ContentProviderNative extends Binder
        implements IContentProvider {
    ......
    @Override
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {
        try {
            switch (code) {
            case QUERY_TRANSACTION: {
                data.enforceInterface(IContentProvider.descriptor);
                Uri url = Uri.CREATOR.createFromParcel(data);

                int num = data.readInt();
                String[] projection = null;
                if (num > 0) {
                    projection = new String[num];
                    for (int i = 0; i < num; i++) projection[i] = data.readString();
                }

                String selection = data.readString();
                num = data.readInt();
                String[] selectionArgs = null;
                if (num > 0) {
                    selectionArgs = new String[num];
                    for (int i = 0; i < num; i++) selectionArgs[i] = data.readString();
                }

                String sortOrder = data.readString();
                IContentObserver observer = IContentObserver.Stub
                        .asInterface(data.readStrongBinder());
                CursorWindow window = CursorWindow.CREATOR.createFromParcel(data);
                boolean wantsCursorMetadata = data.readInt() != 0;

                IBulkCursor bulkCursor = bulkQuery(url, projection, selection,
                        selectionArgs, sortOrder, observer, window);
                reply.writeNoException();
                if (bulkCursor != null) {
                    reply.writeStrongBinder(bulkCursor.asBinder());
                    if (wantsCursorMetadata) {
                        reply.writeInt(bulkCursor.count());
                        reply.writeInt(BulkCursorToCursorAdaptor
                                .findRowIdColumnIndex(bulkCursor.getColumnNames()));
                    }
                } else {
                    reply.writeStrongBinder(null);
                }
                return true;
            }
            ......
            }
        } catch (Exception e) {
            DatabaseUtils.writeExceptionToParcel(reply, e);
            return true;
        }
        return super.onTransact(code, data, reply, flags);
    }
    ......
}

關鍵那一行是 CursorWindow window = CursorWindow.CREATOR.createFromParcel(data)——服務端從 Parcel 中還原出 CursorWindow,此時它已經指向客戶端建立的那片共享內存。

四、第四步:Transport 轉入真正的 Provider

程式碼在 ContentProvider.java:

public abstract class ContentProvider implements ComponentCallbacks {
    ......
    class Transport extends ContentProviderNative {
        ......
        public IBulkCursor bulkQuery(Uri uri, String[] projection,
                String selection, String[] selectionArgs, String sortOrder,
                IContentObserver observer, CursorWindow window) {
            ......
            Cursor cursor = ContentProvider.this.query(uri, projection,
                    selection, selectionArgs, sortOrder);
            ......
            return new CursorToBulkCursorAdaptor(cursor, observer,
                    ContentProvider.this.getClass().getName(),
                    hasWritePermission(uri), window);
        }
        ......
    }
    ......
}

這裡做了兩件事:

(1)呼叫 ArticlesProvider 的 query 方法,取得 SQLiteCursor 物件。

(2)用 cursor 與 window 組出 CursorToBulkCursorAdaptor。這個 adaptor 就是服務端那一側的「資料搬運工」:客戶端每次要求一批資料,最終都會落到它身上,由它把資料填進 window 指向的共享內存。

五、第五步:把回指標寫回 reply

if (bulkCursor != null) {
    reply.writeStrongBinder(bulkCursor.asBinder());
    if (wantsCursorMetadata) {
        reply.writeInt(bulkCursor.count());
        reply.writeInt(BulkCursorToCursorAdaptor.findRowIdColumnIndex(
                bulkCursor.getColumnNames()));
    }
}

這裡傳遞的是 CursorToBulkCursorAdaptor 這個跨進程物件的 Binder 參照。

六、第六步:驅動傳輸

一樣省略 Binder 驅動的細節。

七、第七步:客戶端還原代理

IBulkCursor bulkCursor = null;
IBinder bulkCursorBinder = reply.readStrongBinder();
if (bulkCursorBinder != null) {
    bulkCursor = BulkCursorNative.asInterface(bulkCursorBinder);
    if (wantsCursorMetadata) {
        int rowCount = reply.readInt();
        int idColumnPosition = reply.readInt();
        if (bulkCursor != null) {
            adaptor.set(bulkCursor, rowCount, idColumnPosition);
        }
    }
}

此時 bulkCursor 是 BulkCursorProxy 物件——服務端 CursorToBulkCursorAdaptor 在用戶端進程的代理。

最後 adaptor.set(...) 把這個 BulkCursorProxy 放進 BulkCursorToCursorAdaptor 的成員變數 mBulkCursor 中。

八、第八步:包裝成 Cursor 回傳

return new CursorWrapperInner(qCursor, provider);

最後回傳這個物件,其中 qCursor 是 BulkCursorToCursorAdaptor,provider 是 ContentProviderProxy。

至此物件關係成形:

九、資料究竟怎麼過來

進程間通信建立完成後,我們來看資料實際是怎麼傳輸的。

先回顧一下 Content Provider 啟動階段的分析結果:最終在客戶端取得的是 ContentProviderProxy 物件,後續所有資料請求都透過它進行。

public class ArticlesAdapter {
    ......
    private ContentResolver resolver = null;

    public ArticlesAdapter(Context context) {
        resolver = context.getContentResolver();
    }

    ......
    public Article getArticleByPos(int pos) {
        Uri uri = ContentUris.withAppendedId(Articles.CONTENT_POS_URI, pos);
        String[] projection = new String[] {
                Articles.ID, Articles.TITLE, Articles.ABSTRACT, Articles.URL
        };
        Cursor cursor = resolver.query(uri, projection, null, null,
                Articles.DEFAULT_SORT_ORDER);
        if (!cursor.moveToFirst()) {
            return null;
        }
        int id = cursor.getInt(0);
        String title = cursor.getString(1);
        String abs = cursor.getString(2);
        String url = cursor.getString(3);
        return new Article(id, title, abs, url);
    }
}

完整的資料流是這樣的:

1. BulkCursorToCursorAdaptor 內的成員變數 mBulkCursor(BulkCursorProxy)透過 Binder 跨進程呼叫,找到服務端的 CursorToBulkCursorAdaptor。

2. 服務端透過它內部的 mCursor 向 SQLite 查詢資料,把結果寫進 mWindow 所指向的匿名共享內存。

3. 客戶端的 BulkCursorToCursorAdaptor 持有同一片共享內存的參照(透過自己的 mWindow),因此可以直接從記憶體中讀出資料,完全不必再走一次 Binder。

這就是為什麼 Content Provider 查詢大量資料時,第一次 moveToFirst() 需要跨進程,而後續在同一個 window 內的隨機讀取幾乎沒有 IPC 開銷。

反過來看,如果是刪除這類操作,通常不需要讀寫匿名共享內存——只要透過 mBulkCursor 的跨進程呼叫下達指令,再讀取回傳的結果即可。共享內存機制是為「大量資料讀取」量身打造的,寫入類操作走傳統 Binder 呼叫反而更直接。

十、設計意圖小結

把整個機制串起來看,Content Provider 的跨進程設計其實是一層一層的代理堆疊:

客戶端:CursorWrapperInner → BulkCursorToCursorAdaptor → BulkCursorProxy

服務端:Transport → CursorToBulkCursorAdaptor → SQLiteCursor

每一層都只負責一件事:介面適配、生命週期管理或資料搬運。而真正的效能關鍵在於把「控制訊號」與「資料本體」分開傳——控制走 Binder,資料走 ashmem。這個思路在 Android 其他地方也能看到,例如 SurfaceFlinger 與 App 之間傳遞圖形緩衝區,用的同樣是「傳 fd 而非傳內容」的手法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved