所以我一直遇到这个问题,当我明确调用requestSync时,首先调用onPerformSync,其次是30或60秒后,但大多数是60秒,这很奇怪。我正在使用ContentObserver,这种行为只发生在我使用ContentObserver时。我尝试直接从我的内容提供商调用requestSync,并且没有触发其他onPerformSync。我的代码摘录列在下面。
提供商调用notifyChange
@Nullable
@Override
public Uri insert(@NonNull Uri uri, ContentValues values) {
Log.d(LOG_TAG, "Inserting with uri " + uri + " with values " + values.toString());
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int match = sUriMatcher.match(uri);
....
// This direct requestSync call does not trigger extra syncs
//Bundle extras = new Bundle();
//extras.putString(SyncAdapter.CHANGED_URI, uri.toString());
//getContext().getContentResolver().requestSync(SyncAccount.getAccount(), Contract.CONTENT_AUTHORITY, extras);
getContext().getContentResolver().notifyChange(contentUri, null);
return contentUri;
}
带onChange的ContentObserver
public class TableObserver extends ContentObserver {
private final static String LOG_TAG = TableObserver.class.getSimpleName();
private final Account mAccount;
public TableObserver(Handler handler, Account account) {
super(handler);
mAccount = account;
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange, null);
}
@Override
public void onChange(boolean selfChange, Uri uri) {
Log.d(LOG_TAG, "Provider changed here: " + uri.toString());
Bundle args = new Bundle();
args.putString(SyncAdapter.CHANGED_URI, uri.toString());
ContentResolver.requestSync(mAccount, Contract.CONTENT_AUTHORITY, args);
}
}
使用onPerformSync同步适配器
public class SyncAdapter extends AbstractThreadedSyncAdapter {
private static final String LOG_TAG = SyncAdapter.class.getSimpleName();
public static final String CHANGED_URI = "changed_uri";
private ContentResolver mContentResolver;
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
mContentResolver = context.getContentResolver();
}
public SyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
super(context, autoInitialize, allowParallelSyncs);
mContentResolver = context.getContentResolver();
}
// This is automatically performed in a background thread.
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
Log.d(LOG_TAG, "Synchronizing: " + extras.get(CHANGED_URI));
}
}
答案 0 :(得分:2)
通过将false传递给notifyChange来修复它,后者确实删除了方法的同步到网络行为,如下所示:
getContext().getContentResolver().notifyChange(contentUri, null, false);