AbstractThreadedSyncAdapter抽象类上。对照官方文档中的描述,在应用开发中提供一个自定义的sync adapter,只需要完成下面的几个步骤:
详细步骤可见AbstractThreadedSyncAdapter类的参考文档。
这里主要分析一下AbstractThreadedSyncAdapter类本身,也即是sync adapter的共性部分。
看看参与sync adapter调用的类簇:
下面是启动一次同步的序列图:
简要描述一下:
首先,sync adapter的行为通过ISyncAdapter接口来描述:
/** * Interface used to control the sync activity on a SyncAdapter * @hide */ oneway interface ISyncAdapter { /** * Initiate a sync for this account. SyncAdapter-specific parameters may * be specified in extras, which is guaranteed to not be null. * * @param syncContext the ISyncContext used to indicate the progress of the sync. When * the sync is finished (successfully or not) ISyncContext.onFinished() must be called. * @param authority the authority that should be synced * @param account the account that should be synced * @param extras SyncAdapter-specific parameters */ void startSync(ISyncContext syncContext, String authority, in Account account, in Bundle extras); /** * Cancel the most recently initiated sync. Due to race conditions, this may arrive * after the ISyncContext.onFinished() for that sync was called. * @param syncContext the ISyncContext that was passed to {@link #startSync} */ void cancelSync(ISyncContext syncContext); /** * Initialize the SyncAdapter for this account and authority. * * @param account the account that should be synced * @param authority the authority that should be synced */ void initialize(in Account account, String authority); }
private class ISyncAdapterImpl extends ISyncAdapter.Stub { public void startSync(ISyncContext syncContext, String authority, Account account, Bundle extras) { ... } public void cancelSync(ISyncContext syncContext) { ... } public void initialize(Account account, String authority) throws RemoteException { ... } }
/** * @return a reference to the IBinder of the SyncAdapter service. */ public final IBinder getSyncAdapterBinder() { return mISyncAdapterImpl.asBinder(); }
public void startSync(ISyncContext syncContext, String authority, Account account, Bundle extras) { ... synchronized (mSyncThreadLock) { if (!mSyncThreads.containsKey(threadsKey)) { ... SyncThread syncThread = new SyncThread( "SyncAdapterThread-" + mNumSyncStarts.incrementAndGet(), syncContextClient, authority, account, extras); mSyncThreads.put(threadsKey, syncThread); syncThread.start(); ... } ... } ... }
private class SyncThread extends Thread { private final SyncContext mSyncContext; private final String mAuthority; private final Account mAccount; private final Bundle mExtras; private final Account mThreadsKey; ... @Override public void run() { ... try { ... provider = mContext.getContentResolver().acquireContentProviderClient(mAuthority); if (provider != null) { AbstractThreadedSyncAdapter.this.onPerformSync(mAccount, mExtras, mAuthority, provider, syncResult); } else { syncResult.databaseError = true; } } ... } ... }
这样,总而言之,外界通过从系统中查找得到特定的Sync adapter service,然后通过绑定到这个service来获取ISyncAdapter服务的代理对象。然后调用代理对象来启动/终止同步操作。代理对象与提供同步实现的应用程序进程进行IPC来发起真正的同步过程。