2014-09-21 93 views
5

我的應用程序有一個按照Android developer site顯示的結構創建的同步適配器。該onPerformSync()方法從互聯網獲取數據,並與大容量插入其插入在數據庫上:有衝突的交易時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); 
    } 
} 

然而,它被連續調用。

回答

0

onPerformSync()只有在使用「requestSync」api強制調用時纔會被調用,並且在使用空包創建賬戶時會被調用一次。

0

我被卡住了同樣的問題,畢竟我發現我也多次呼籲ContentResolver.requestSync()(每onPerformSync()之前)。換句話說,requestSync()導致onPerformSync()呼叫。這是我的錯誤,我應該重新考慮邏輯。

嘗試在您的代碼中登錄requestSync()調用,並且您可能會發現錯誤。