【发布时间】:2021-06-24 07:58:22
【问题描述】:
我正在尝试从 android 媒体存储中获取更改。我用下一个资源创建了GallerySyncAdapter:
<?xml version="1.0" encoding="utf-8"?>
<sync-adapter xmlns:android="http://schemas.android.com/apk/res/android"
android:accountType="example.com"
android:allowParallelSyncs="false"
android:contentAuthority="media"
android:isAlwaysSyncable="true"
android:supportsUploading="true"
android:userVisible="true" />
添加了ContentResolver.setIsSyncable(accoutn, MediaStore.AUTHORITY, 1)和ContentResolver.setSyncAutomatically(account, MediaStore.AUTHORITY, true),所以必须自动同步。但是当我拍一些照片时,我的GallerySyncAdapter.onPerformSync 没有被调用。
GallerySyncAdapter来源:
class GallerySyncAdapter(
context: Context,
autoInitialize: Boolean
) : AbstractThreadedSyncAdapter(context, autoInitialize) {
override fun onPerformSync(
account: Account?,
extras: Bundle?,
authority: String?,
provider: ContentProviderClient?,
syncResult: SyncResult?
) {
Log.d("GallerySyncAdapter", "Need sync images...")
}
}
GallerySyncService:
class GallerySyncService : Service() {
override fun onCreate() {
synchronized(sSyncAdapterLock) {
sSyncAdapter = sSyncAdapter ?: GallerySyncAdapter(applicationContext, true)
}
}
override fun onBind(intent: Intent): IBinder {
return sSyncAdapter?.syncAdapterBinder ?: throw IllegalStateException()
}
companion object {
private var sSyncAdapter: GallerySyncAdapter? = null
private val sSyncAdapterLock = Any()
}
}
AndroidManifest.xml中的声明
<service
android:name=".services.GallerySyncService"
android:exported="true">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="@xml/gallerysyncadapter" />
</service>
帐户已正确创建,因此我可以从 Settings -> Accounts -> My Account -> Sync account -> Sync now 开始同步,但是当我更改媒体(制作新照片、视频等)时,同步没有开始。
当我声明 ContentObserver 而不是 SyncAdapter 时,它正在工作:
resolver.registerContentObserver(
MediaStore.AUTHORITY_URI, // content://media
true, // notifyForDescendants
galleryObserver // my own observer
)
但我需要一个解决方案来获取更改,即使我的应用程序没有启动。
【问题讨论】:
标签: android mediastore android-syncadapter