在Android中,同步适配器(Sync Adapter)是一种用于处理应用程序数据与远程服务器数据同步的组件。同步适配器需要与操作系统的同步框架协同工作,以确保数据的一致性和准确性。在使用同步适配器时,需要完成一些必要的设置,以确保同步适配器能够正常工作。
前期基础配置
- 在AndroidManifest.xml文件中注册同步适配器。
<service android:name=".CameraSyncAdapter" android:exported="true">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data android:name="android.content.SyncAdapter" android:resource="@xml/syncadapter"/>
</service>
- 创建一个SyncAdapter.xml文件,定义同步适配器的属性和行为。
<?xml version="1.0" encoding="utf-8"?>
<sync-adapter xmlns:android="http://schemas.android.com/apk/res/android"
android:contentAuthority="com.example.provider"
android:accountType="com.example.account"
android:userVisible="true"
android:supportsUploading="false"
android:allowParallelSyncs="false"
android:isAlwaysSyncable="true"/>
- 创建一个同步适配器的子类,并实现onPerformSync()方法。
public class CameraSyncAdapter extends AbstractThreadedSyncAdapter {
public CameraSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
// 在这里实现同步逻辑
}
}
- 在您的应用程序中使用ContentResolver.requestSync()方法来触发同步适配器的同步操作。
ContentResolver.requestSync(a.getAndroidAccount(), AUTHORITY, new Bundle());
也可以携带参数
public void performFullSync() {
Bundle b = new Bundle();
b.putBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, true);
Account cameraAccount = getCameraAccount();
if (cameraAccount != null){
ContentResolver.requestSync(cameraAccount.getAndroidAccount(), AUTHORITY, b);
}
}
但要设置此Account的Syncable为true
ContentResolver.setIsSyncable(a.getAndroidAccount(), AUTHORITY, 1);
ContentResolver.setSyncAutomatically(a.getAndroidAccount(), AUTHORITY, true);
接下来记录一下问题 某天在用Pixel 4a调试时,发现无论怎么操作,CameraSyncAdapter的onPerformSync函数都不会触发。但是在另外一台samsung Galaxy S21国行版 上发现是可以触发的。很奇怪,两台手机都是连接WIFI的,请求API数据、播放视频等其他联网操作都是可以的。
有一天偶尔在medium上看到这篇文章:Using Sync Adapter to transfer data in android
,其中有一段是这样写的。
c. Automated Network Checking: The system only runs your data transfer when your device is connected to a network.
C。自动网络检查: 系统仅在您的设备连接到网络时运行数据传输。
所以就想着是不是 Pixel 无法连接Google服务器,导致网络链接受限(WIFI图标有叹号)。按照解决 Pixel 及 aosp rom 国内 WiFi 网络连接受限这篇文章修改了检查服务器地址。
结果,onPerformSync()就能正常触发了......😅🤣🙃🙃🙃🙃🙃🙃