【问题标题】:onPerformSync() called multiple times多次调用 onPerformSync()
【发布时间】:2014-09-21 16:58:50
【问题描述】:

我的应用程序有一个按照Android developer site 显示的结构创建的同步适配器。 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);

数据库在处理冲突时具有 IGNORE 策略:

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

但是,它是连续调用的。

【问题讨论】:

    标签: android android-syncadapter


    【解决方案1】:

    onPerformSync() 仅在使用“requestSync”api 强制调用时才会调用,并且在使用空包创建帐户时调用一次。

    【讨论】:

      【解决方案2】:

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

      尝试在您的代码中记录requestSync() 调用,您可能会发现错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-19
        • 2013-03-31
        相关资源
        最近更新 更多