android - 多次调用 onPerformSync()

标签 android android-syncadapter

我的应用程序有一个按照 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);
    }
}

然而,它被连续调用。

最佳答案

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

关于android - 多次调用 onPerformSync(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25961624/

相关文章:

android - 如何安排服务在android中运行

android - GcmTaskService 与 SyncAdapter

android - 当应用程序重置数据时如何取消定期同步?卸载该应用程序后如何删​​除相关帐户?

android - 使用 SyncAdapter 同步联系人,工作

android - 加载图片时加载资源失败

安卓:开火xmpp

android - 如何获取非 Activity View 的复选框 ID?

java - 如何在android java ListView 中选择多个项目

android - 将多个参数放入 ContentResolver.requestSync

android - 在 Android 中,联系人同步适配器应该在单独的进程中运行吗?