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

基於 Android 4.2.2 的同步框架源碼學習(一):同步發起端

編輯:關於 Android 程式設計

本文以 Android 4.2.2 原始碼為基礎,追蹤一次同步請求從 App 層一路走到 SyncAdapter 的完整路徑。

牽涉到的關鍵組件:

ContentResolver
ContentService
SyncManager
SyncManager.ActiveSyncContext
SyncManager.SyncOperation
SyncManager.SyncHandler

一、ContentResolver:對外暴露的入口

外部應用程式透過呼叫 ContentResolver.requestSync() 這個靜態方法發起同步:

/**
 * @param account   要同步的帳號
 * @param authority 要同步的 authority
 * @param extras    傳遞給 SyncAdapter 的附加資料
 */
public static void requestSync(Account account, String authority, Bundle extras) {
    validateSyncExtrasBundle(extras);
    try {
        getContentService().requestSync(account, authority, extras);
    } catch (RemoteException e) {
    }
}

三個參數分別是帳號、authority、以及附加資料。getContentService() 會回傳系統服務 ContentService 的代理物件,接著透過 Binder 遠程呼叫 ContentService.requestSync()。

注意 validateSyncExtrasBundle(extras) 會檢查 extras 中的鍵值是否合法——Volley 式的「傳什麼進去就拿什麼出來」在這裡並不成立,只有系統預先定義過的 key 才會被接受。

二、ContentService:系統服務層

ContentService 是 Android 的系統服務,提供一系列數據同步與數據訪問相關的操作,其行為定義在 IContentService.aidl 中。

public void requestSync(Account account, String authority, Bundle extras) {
    // ... 權限與參數檢查省略 ...
    try {
        SyncManager syncManager = getSyncManager();
        if (syncManager != null) {
            syncManager.scheduleSync(account, userId, authority, extras,
                    0 /* no delay */,
                    false /* onlyThoseWithUnkownSyncableState */);
        }
    }
    // ...
}

這一層基本上就是權限把關加上轉發。真正的調度邏輯都在 SyncManager 裡。

三、SyncManager:調度核心

public void scheduleSync(Account requestedAccount, int userId, String requestedAuthority,
                        Bundle extras, long delay,
                        boolean onlyThoseWithUnkownSyncableState) {
    // ...

    final boolean backgroundDataUsageAllowed = !mBootCompleted ||
            getConnectivityManager().getBackgroundDataSetting();

    // 產生一組待同步帳戶。手動同步時只有一個 AccountAndUser 元素,
    // 它封裝了要同步的帳號與對應的 userId
    AccountAndUser[] accounts;
    if (requestedAccount != null && userId != UserHandle.USER_ALL) {
        accounts = new AccountAndUser[] { new AccountAndUser(requestedAccount, userId) };
    }
    // ...

    for (AccountAndUser account : accounts) {

        // 掃描系統中所有提供了 sync adapter 的 service:依 intent-filter 找出來,
        // 再從 service info 取得各自的 authority。service info 是從對應服務的
        // meta-data 標籤所指定的 sync adapter 描述檔中解析出來的
        final HashSet<String> syncableAuthorities = new HashSet<String>();
        for (RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapter :
                mSyncAdapters.getAllServices(account.userId)) {
            syncableAuthorities.add(syncAdapter.type.authority);
        }

        for (String authority : syncableAuthorities) {

            // 檢查帳戶是否能夠同步
            int isSyncable = mSyncStorageEngine.getIsSyncable(
                    account.account, account.userId, authority);
            if (isSyncable == 0) {
                continue;      // 明確標記為不可同步,跳過
            }

            final RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo;
            syncAdapterInfo = mSyncAdapters.getServiceInfo(
                    SyncAdapterType.newKey(authority, account.account.type),
                    account.userId);
            // ...

            if (isSyncable < 0) {
                // 狀態未知,先送一個初始化用的 extras
                Bundle newExtras = new Bundle();
                newExtras.putBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, true);
                // ...
            }

            // 部署同步操作
            scheduleSyncOperation(
                    new SyncOperation(account.account, account.userId, source,
                            authority, newExtras, 0, backoffTime, delayUntil,
                            allowParallelSyncs));
        }
    }
}

這段程式碼做了三件事:

  1. 篩選出所有提供 sync adapter 的 service,並收集它們的 authority。
  2. 逐一檢查 isSyncable 狀態。這裡有三種值:0 表示明確不可同步(跳過)、正數表示可同步、-1 表示狀態未知(補送 SYNC_EXTRAS_INITIALIZE 讓 adapter 自行決定)。
  3. 為每個通過檢查的項目建立 SyncOperation 並排入佇列。

四、SyncOperation:同步任務的資料載體

public class SyncOperation implements Comparable {
    public final Account account;
    public final int userId;
    public int syncSource;
    public String authority;
    public final boolean allowParallelSyncs;
    public Bundle extras;
    public final String key;
    public long earliestRunTime;
    public boolean expedited;
    public SyncStorageEngine.PendingOperation pendingOperation;
    public Long backoff;
    public long delayUntil;
    public long effectiveRunTime;
}

幾個值得注意的字段:

  • key:由 account、authority、extras 等組成的唯一鍵,用來去重——同一組條件的重複請求會被合併而非排隊兩次。
  • earliestRunTime 與 delayUntil:控制何時可以執行。
  • expedited:是否插隊優先執行。
  • backoff:失敗後的退避時間,實作指數退避以避免伺服器被打爆。

五、排入佇列並通知 SyncHandler

public void scheduleSyncOperation(SyncOperation syncOperation) {
    boolean queueChanged;
    synchronized (mSyncQueue) {
        queueChanged = mSyncQueue.add(syncOperation);
    }

    if (queueChanged) {
        // ...
        sendCheckAlarmsMessage();
    }
    // ...
}

private void sendCheckAlarmsMessage() {
    // ...
    mSyncHandler.removeMessages(SyncHandler.MESSAGE_CHECK_ALARMS);
    mSyncHandler.sendEmptyMessage(SyncHandler.MESSAGE_CHECK_ALARMS);
}

把操作插入佇列 mSyncQueue 之後,向 SyncHandler 送出一則 MESSAGE_CHECK_ALARMS。送之前先 removeMessages 是為了合併通知:短時間內連續加入十個任務,只會觸發一次檢查。

SyncHandler 收到後:

public void handleMessage(Message msg) {
    // ...
    try {
        switch (msg.what) {
            case SyncHandler.MESSAGE_CHECK_ALARMS:
                nextPendingSyncTime = maybeStartNextSyncLocked();
                break;
        }
    }
    // ...
}

maybeStartNextSyncLocked() 會經過一連串檢查(網路是否可用、背景資料是否允許、帳戶狀態、退避時間是否已過等),確認所有條件都滿足後,才把 SyncOperation 分發出去:

private long maybeStartNextSyncLocked() {
    // ...
    dispatchSyncOperation(candidate);
    // ...
    return nextReadyToRunTime;
}

六、dispatchSyncOperation:綁定到 SyncAdapter

private boolean dispatchSyncOperation(SyncOperation op) {
    // ...

    // 連線到 sync adapter
    SyncAdapterType syncAdapterType = SyncAdapterType.newKey(op.authority, op.account.type);
    final RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo;
    syncAdapterInfo = mSyncAdapters.getServiceInfo(syncAdapterType, op.userId);
    // ...

    ActiveSyncContext activeSyncContext =
            new ActiveSyncContext(op, insertStartSyncEvent(op), syncAdapterInfo.uid);
    activeSyncContext.mSyncInfo = mSyncStorageEngine.addActiveSync(activeSyncContext);
    mActiveSyncContexts.add(activeSyncContext);
    // ...

    if (!activeSyncContext.bindToSyncAdapter(syncAdapterInfo, op.userId)) {
        Log.e(TAG, "Bind attempt failed to " + syncAdapterInfo);
        closeActiveSyncContext(activeSyncContext);
        return false;
    }

    return true;
}

這裡出現了兩個重要的資料結構:ActiveSyncContext 代表「一個正在進行中的同步」,而 insertStartSyncEvent 會寫入一筆統計事件,供後續分析同步耗時與失敗原因。

七、ActiveSyncContext:Service 綁定的載體

與 AccountManager 的設計非常相似,這裡同樣用一個內部類別完成 service 綁定:

class ActiveSyncContext extends ISyncContext.Stub
        implements ServiceConnection, IBinder.DeathRecipient {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Message msg = mSyncHandler.obtainMessage();
        msg.what = SyncHandler.MESSAGE_SERVICE_CONNECTED;
        msg.obj = new ServiceConnectionData(this, ISyncAdapter.Stub.asInterface(service));
        mSyncHandler.sendMessage(msg);
    }

    boolean bindToSyncAdapter(RegisteredServicesCache.ServiceInfo info, int userId) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.d(TAG, "bindToSyncAdapter: " + info.componentName + ", connection " + this);
        }
        Intent intent = new Intent();
        intent.setAction("android.content.SyncAdapter");
        intent.setComponent(info.componentName);
        intent.putExtra(Intent.EXTRA_CLIENT_LABEL,
                com.android.internal.R.string.sync_binding_label);
        intent.putExtra(Intent.EXTRA_CLIENT_INTENT,
                PendingIntent.getActivityAsUser(mContext, 0,
                        new Intent(Settings.ACTION_SYNC_SETTINGS), 0,
                        null, new UserHandle(userId)));

        mBound = true;
        final boolean bindResult = mContext.bindService(intent, this,
                Context.BIND_AUTO_CREATE | Context.BIND_NOT_FOREGROUND
                        | Context.BIND_ALLOW_OOM_MANAGEMENT,
                mSyncOperation.userId);
        if (!bindResult) {
            mBound = false;
        }
        return bindResult;
    }
}

幾個細節:

  • bindToSyncAdapter() 建立帶有 android.content.SyncAdapter action 的 Intent,指定明確的 component 後發起綁定。
  • 綁定旗標用了 BIND_NOT_FOREGROUND 與 BIND_ALLOW_OOM_MANAGEMENT——同步不該讓 Service 提升優先級,記憶體吃緊時也該允許被回收。
  • 本類別同時實作了 IBinder.DeathRecipient,這是為了在 SyncAdapter 所在的程序意外死亡時能收到通知並清理狀態。
  • EXTRA_CLIENT_INTENT 指向同步設定畫面,讓使用者能從通知直接跳去調整同步選項。

由於實作了 ServiceConnection,綁定成功後系統會回呼 onServiceConnected()。這個回呼裡做了一件關鍵的事:把 ISyncAdapter 介面包成訊息丟回 SyncHandler,而不是直接在 Binder 回呼 thread 上執行同步。這是 Android framework 中處理 Binder 回呼的標準手法——Binder thread 必須盡快釋放。

八、SyncHandler 處理 MESSAGE_SERVICE_CONNECTED

case SyncHandler.MESSAGE_SERVICE_CONNECTED: {
    ServiceConnectionData msgData = (ServiceConnectionData) msg.obj;
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.d(TAG, "handleSyncHandlerMessage: MESSAGE_SERVICE_CONNECTED: "
                + msgData.activeSyncContext);
    }
    // 確認這不是一則過時的訊息
    if (isSyncStillActive(msgData.activeSyncContext)) {
        runBoundToSyncAdapter(msgData.activeSyncContext, msgData.syncAdapter);
    }
    break;
}

isSyncStillActive() 這個檢查很重要:從發起綁定到綁定成功之間可能有延遲,若期間該同步已被取消,就不該繼續執行。

最後呼叫 runBoundToSyncAdapter():

private void runBoundToSyncAdapter(final ActiveSyncContext activeSyncContext,
                                   ISyncAdapter syncAdapter) {
    activeSyncContext.mSyncAdapter = syncAdapter;
    final SyncOperation syncOperation = activeSyncContext.mSyncOperation;
    try {
        // ...
        syncAdapter.startSync(activeSyncContext, syncOperation.authority,
                syncOperation.account, syncOperation.extras);
    }
    // ...
}

至此控制權正式交到 SyncAdapter 手上——也就是應用程式開發者實作同步邏輯的地方。

九、整條路徑回顧

App
 └─ ContentResolver.requestSync()          靜態方法,參數檢查
     └─ ContentService.requestSync()       系統服務,權限把關(Binder)
         └─ SyncManager.scheduleSync()     篩選 service、檢查 isSyncable
             └─ SyncOperation              封裝任務,含 key 去重與退避資訊
                 └─ mSyncQueue.add()       排入優先佇列
                     └─ MESSAGE_CHECK_ALARMS → SyncHandler
                         └─ maybeStartNextSyncLocked()   條件檢查
                             └─ dispatchSyncOperation()
                                 └─ ActiveSyncContext.bindToSyncAdapter()
                                     └─ onServiceConnected() → MESSAGE_SERVICE_CONNECTED
                                         └─ runBoundToSyncAdapter()
                                             └─ ISyncAdapter.startSync()  ← 交棒給 App

整條鏈路有兩個設計值得記住:

第一,所有的狀態轉換都集中在 SyncHandler 這一條 thread 上。SyncManager 雖然有多個資料結構,但透過 synchronized (mSyncQueue) 加上訊息傳遞,把並行問題收斂成單 thread 的序列問題,大幅簡化了同步邏輯的除錯難度。

第二,每一層都設有防禦性的有效性檢查:ContentResolver 檢查 extras、ContentService 檢查權限、SyncManager 檢查 isSyncable 與退避時間、SyncHandler 檢查 sync 是否仍然 active。同步框架要處理的是斷網、伺服器錯誤、程序被殺、使用者中途取消等各種不確定狀況,這種多層防禦是必要的成本。

下一篇接著看 SyncAdapter 端的實作,以及 SyncManager.SyncHandler 如何處理同步結果與退避重試。

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