onPerformSync()被多次调用

5

我的应用程序拥有一个同步适配器,遵循Android开发者网站所展示的结构。 onPerformSync()方法从互联网获取数据,并使用批量插入将其插入数据库:

Vector<ContentValues> cVVector = new Vector<ContentValues>(rssItems.size());

for(RssItem rssItem : rssItems) {
    ContentValues newsValues = new ContentValues();
    // Get data from the remote server
    // Fill all the values
    newsValues.put(...);
    // Add the values to a vector, at the end a BulkInsert will be called
    cVVector.add(newsValues);
}
mContext.getContentResolver().bulkInsert(NewsEntry.CONTENT_URI, cvArray);

当涉及到冲突时,数据库有一个“忽略”策略:

final String SQL_CREATE_NEWS_TABLE = "CREATE TABLE " + NewsEntry.TABLE_NAME + " (" +
                NewsEntry._ID + " INTEGER PRIMARY KEY," +
                NewsEntry.COLUMN_NEWS_TITTLE + " TEXT UNIQUE NOT NULL, " +
                NewsEntry.COLUMN_NEWS_CONTENT + " TEXT NOT NULL, " +
                NewsEntry.COLUMN_NEWS_DESCRIPTION + " TEXT NOT NULL, " +
                NewsEntry.COLUMN_NEWS_IMAGE + " TEXT, " +
                NewsEntry.COLUMN_NEWS_DATE + " TEXT NOT NULL, " +
                NewsEntry.COLUMN_NEWS_LINK + " TEXT NOT NULL, " +
                "UNIQUE (" + NewsEntry.COLUMN_NEWS_TITTLE +") ON CONFLICT IGNORE"+
                " );";

同步适配器被配置为每86400秒执行一次同步。

/**
 * Helper method to schedule the sync adapter periodic execution
 */
public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) {
    Account account = getSyncAccount(context);
    String authority = context.getString(R.string.content_authority);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // we can enable inexact timers in our periodic sync
        SyncRequest request = new SyncRequest.Builder().
                syncPeriodic(syncInterval, flexTime).
                setSyncAdapter(account, authority).build();
        ContentResolver.requestSync(request);
    } else {
        ContentResolver.addPeriodicSync(account,
                authority, new Bundle(), syncInterval);
    }
}

然而,它被称为连续的。
2个回答

0

只有在使用“requestSync”API强制调用并且在带有空Bundle的账户创建时才会调用onPerformSync()。


0

我遇到了同样的问题,最终发现我在每个onPerformSync()之前多次调用了ContentResolver.requestSync()。换句话说,requestSync()会导致onPerformSync()被调用。这是我的错误,我应该重新考虑逻辑。

尝试在代码中记录requestSync()的调用,很可能你能找到错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接