关键组件:

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

ContentResolver

外部的应用程序通过调用ContentResolve.requestSync()静态方法发起同步:

    /**
* @param account which account should be synced
* @param authority which authority should be synced
* @param extras any extras to pass to the SyncAdapter.
*/
public static void requestSync(Account account, String authority, Bundle extras) {
validateSyncExtrasBundle(extras);
try {
getContentService().requestSync(account, authority, extras);
} catch (RemoteException e) {
}
}

方法接收三个参数:

- account:需要同步的帐号

- authority:需要进行同步的authority

- extras:需要传递给sync adapter的附加数据

在这里,getContentService()方法返回系统服务ContentService的代理对象,然后通过它远程调用ContentService.requestSync()。

ContentService

ContentService是Android的系统服务,它提供一系列数据同步及数据访问等相关的操作。它的行为在IContentService.aidl中描述。

这里,通过远程调用ContentService.requestSync()方法来启动针对指定帐号(account)的指定内容(authority)的同步:

    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管理与同步相关的处理。

SyncManager

    public void scheduleSync(Account requestedAccount, int userId, String requestedAuthority,
Bundle extras, long delay, boolean onlyThoseWithUnkownSyncableState) {
...
final boolean backgroundDataUsageAllowed = !mBootCompleted ||
getConnectivityManager().getBackgroundDataSetting();
... // 产生一个同步帐户列表。对于手动同步,列表中仅有一个AccountUser元素,它封装了需要同步的帐号以及对应的应用程序(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) {
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));
}
...
}
}
}

这里,首先从系统中筛选出符合限定条件的service的信息,然后发起对应的同步。

首先为每一个同步操作生成一个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;

然后调用scheduleSyncOperation方法:

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

首先将SyncOperation实例插入队列mSyncQueue然后向SyncManager中定义的SyncHandler发送消息,通知其队列发生变化:

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

随后,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;
}

接下来,将绑定到提供sync adapter的应用程序中对应的service:

        private boolean dispatchSyncOperation(SyncOperation op) {
...
// connect to the 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;
}

与前面的AccountManager非常的雷同,这里通过ActiveSyncContext类来完成service的绑定:

    class ActiveSyncContext extends ISyncContext.Stub
implements ServiceConnection, IBinder.DeathRecipient {
...
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()中创建相应的Intent,发起绑定。

然后,因为本类实现了ServiceConnection接口,所以当绑定成功时,将回调本类的onServiceConnected()方法。在这个回调中,向SyncHandler发送一条MESSAGE_SERVICE_CONNECTED消息。

紧接着,轮到SyncHandler来处理消息:

                    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);
}
// check that this isn't an old message
if (isSyncStillActive(msgData.activeSyncContext)) {
runBoundToSyncAdapter(msgData.activeSyncContext, msgData.syncAdapter);
}
break;
}

这里主要就是调用了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实例(实际上是AbstractThreadedSyncAdpter.ISyncAdapterImpl服务的代理对象)调用startSync()方法。这样,通过IPC即可调用对应的应用程序执行同步了。详见本系列上一篇文章。

基于Andoird 4.2.2的同步框架源代码学习——同步发起端的更多相关文章

  1. 基于Andoird 4.2.2的同步框架源代码学习——同步提供端

    Android同步框架 同步(synchronization)允许用户将远程数据下载到新的设备上,同时将设备上的帐户数据上传到远端.同步还保证用户能够看到最新的数据. 开发者自然可以通过自己的方式来设 ...

  2. 基于Andoird 4.2.2的Account Manager源代码分析学习:AccountManagerService系统服务的添加

    从启动说起 Android系统加载时,首先启动init进程,该进程会启动Zygote进程.Zygote进程执行/system/bin/app_process程序.app_process程序在执行中,通 ...

  3. 基于Andoird 4.2.2的Account Manager源代码分析学习:创建选定类型的系统帐号

    AccountManager.addAccount() public AccountManagerFuture<Bundle> addAccount(final String accoun ...

  4. 基于TILE-GX实现快速数据包处理框架-netlib实现分析【转】

    最近在研究suricata源码,在匹配模式的时候,有tilegx mpipe mode,转载下文,了解一下. 原文地址:http://blog.csdn.net/lhl_blog/article/de ...

  5. 分布式消息总线,基于.NET Socket Tcp的发布-订阅框架之离线支持,附代码下载

    一.分布式消息总线以及基于Socket的实现 在前面的分享一个分布式消息总线,基于.NET Socket Tcp的发布-订阅框架,附代码下载一文之中给大家分享和介绍了一个极其简单也非常容易上的基于.N ...

  6. 分享一个分布式消息总线,基于.NET Socket Tcp的发布-订阅框架,附代码下载

    一.分布式消息总线 在很多MIS项目之中都有这样的需求,需要一个及时.高效的的通知机制,即比如当使用者A完成了任务X,就需要立即告知使用者B任务X已经完成,在通常的情况下,开发人中都是在使用者B所使用 ...

  7. Entity Framework 实体框架的形成之旅--基于泛型的仓储模式的实体框架(1)

    很久没有写博客了,一些读者也经常问问一些问题,不过最近我确实也很忙,除了处理日常工作外,平常主要的时间也花在了继续研究微软的实体框架(EntityFramework)方面了.这个实体框架加入了很多特性 ...

  8. Pomelo:网易开源基于 Node.js 的游戏服务端框架

    Pomelo:网易开源基于 Node.js 的游戏服务端框架 https://github.com/NetEase/pomelo/wiki/Home-in-Chinese

  9. (转) 基于Theano的深度学习(Deep Learning)框架Keras学习随笔-01-FAQ

    特别棒的一篇文章,仍不住转一下,留着以后需要时阅读 基于Theano的深度学习(Deep Learning)框架Keras学习随笔-01-FAQ

随机推荐

  1. 嵌入式 GDB调试死锁示例

    死锁:一种情形,此时执行程序中两个或多个线程发生永久堵塞(等待),每个线程都在等待被 其他线程占用并堵塞了的资源.例如,如果线程A锁住了记录1并等待记录2,而线程B锁住了记录2并等待记录1,这样两个线 ...

  2. C/C++中static关键字详解-zz

    静态变量作用范围在一个文件内,程序开始时分配空间,结束时释放空间,默认初始化为0,使用时可以改变其值. 静态变量或静态函数只有本文件内的代码才能访问它,它的名字在其它文件中不可见.用法1:函数内部声明 ...

  3. VS 2013 EFSQLITE

    在 vs 2013 上用 1.NuGet程序包来获取,它也会自动下载EF6的包 :system.Data.sqlite 他会自动下载 其它几个需要的包. 2.在Sqlite官网上下载对应的版本:htt ...

  4. cocos2dx 2.x版本:简化提炼tolua++绑定自定义类到lua中使用

    cocos2dx的3.x版本已经提供了更好地绑定方式,网上有很多相关的教程,这里给一个链接:http://www.cocoachina.com/bbs/read.php?tid=196416. 由于目 ...

  5. 事务处理: databse jdbc mybatis spring

    事务的认识需要一个相当漫长的流程,慢慢在实践中理解,然后在强化相关理论基础. 数据库中的事务: 传统的本地事务处理都是依靠数据库自身事务处理能力,而事务本身是传统关系型数据库的基石.简单来说事务就是一 ...

  6. Arduino+RFID RC522 +继电器

    博客园的第一篇博文就献给Arduino了.不知道能不能坚持自己喜欢的并且记录下来. 起码是个好的开始. 想实现一卡通代替钥匙开启电动车. 简单的原理,通过RC522模块读取一卡通的序列号,在程序中进行 ...

  7. asp.net mvc下ckeditor使用

    资源下载:ckeditor 第一步,引入必须文件“~/ckeditor/ckeditor.js” 第二步,替换文本域 <%: Html.TextArea("Content", ...

  8. 神奇的linux发行版 tiny core linux

    首先官网在此 http://tinycorelinux.net/ 真正轻量级 名字里带有“tiny”又带有“core”,想必又是一个所谓的“轻量级”发行版. 轻量级我们见多了,debian号称是轻量级 ...

  9. 谷歌眼镜--UI指南

    1>使用玻璃HTML模板 不是所有的内容都在几行文字来表达.有时候你需要结构化的内容发送到用户的时间轴,或者你需要控制对格式.为了适应这种情况,镜像API提供了一个 HTML 时间表的项目,接受 ...

  10. android学习笔记---发送状态栏通知

    发送消息的代码如下: //获取通知管理器 NotificationManager mNotificationManager = (NotificationManager) getSystemServi ...