0

所以我一直有這個問題,其中onPerformSync是第一次調用時,我顯式調用requestSync,其次是30或60秒後,但大多是60秒,它的奇怪。我正在使用ContentObserver,並且只有在使用ContentObserver時纔會發生此行爲。我嘗試直接從我的內容提供者調用requestSync,並且沒有觸發額外的onPerformSync。我的代碼片段列在下面。使用ContentObserver調用兩次同步適配器

商稱有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; 
} 

ContentObserver用的onChange

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)); 
    } 
} 

回答

1

通過傳遞虛假到有NotifyChange這不固定它消除了網絡行爲同步的方法如下:

getContext().getContentResolver().notifyChange(contentUri, null, false);