List of usage examples for android.content ContentResolver SYNC_EXTRAS_MANUAL
String SYNC_EXTRAS_MANUAL
To view the source code for android.content ContentResolver SYNC_EXTRAS_MANUAL.
Click Source Link
From source file:com.katamaditya.apps.weather4u.weathersync.Weather4USyncAdapter.java
/** * Helper method to have the sync adapter sync immediately * * @param context The context used to access the account service *///from w ww . j a v a2 s .c o m public static void syncImmediately(Context context) { //Log.d("Weather4USyncAdapter", "syncImmediately"); Bundle bundle = new Bundle(); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync(getSyncAccount(context), context.getString(R.string.content_authority), bundle); }
From source file:io.github.hidroh.materialistic.data.SyncDelegate.java
@UiThread public static void scheduleSync(Context context, Job job) { if (!Preferences.Offline.isEnabled(context)) { return;/*from ww w.j a va 2 s . c o m*/ } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !TextUtils.isEmpty(job.id)) { JobInfo.Builder builder = new JobInfo.Builder(Long.valueOf(job.id).intValue(), new ComponentName(context.getPackageName(), ItemSyncJobService.class.getName())) .setRequiredNetworkType( Preferences.Offline.isWifiOnly(context) ? JobInfo.NETWORK_TYPE_UNMETERED : JobInfo.NETWORK_TYPE_ANY) .setExtras(job.toPersistableBundle()); if (Preferences.Offline.currentConnectionEnabled(context)) { builder.setOverrideDeadline(0); } ((JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE)).schedule(builder.build()); } else { Bundle extras = new Bundle(job.toBundle()); extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); Account syncAccount; AccountManager accountManager = AccountManager.get(context); Account[] accounts = accountManager.getAccountsByType(BuildConfig.APPLICATION_ID); if (accounts.length == 0) { syncAccount = new Account(SYNC_ACCOUNT_NAME, BuildConfig.APPLICATION_ID); accountManager.addAccountExplicitly(syncAccount, null, null); } else { syncAccount = accounts[0]; } ContentResolver.requestSync(syncAccount, MaterialisticProvider.PROVIDER_AUTHORITY, extras); } }
From source file:de.azapps.mirakel.sync.SyncAdapter.java
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {//from ww w. jav a 2 s .c o m // Mostly it is annoying if there is a notification. So don't show it boolean showNotification = false; // But if the user actively clicks on "sync" then show it. if (extras.containsKey(ContentResolver.SYNC_EXTRAS_MANUAL)) showNotification = true; Log.v(TAG, "SyncAdapter"); Intent intent = new Intent(mContext, MainActivity.class); intent.setAction(MainActivity.SHOW_LISTS); PendingIntent p = PendingIntent.getService(mContext, 0, intent, 0); NotificationCompat.Builder mNB = new NotificationCompat.Builder(mContext).setContentTitle("Mirakel") .setContentText("Sync").setSmallIcon(android.R.drawable.stat_notify_sync) .setWhen(System.currentTimeMillis()).setOngoing(true).setContentIntent(p); if (showNotification) mNotificationManager.notify(notifyID, mNB.build()); String type = (AccountManager.get(mContext)).getUserData(account, BUNDLE_SERVER_TYPE); boolean success = false; if (type == null) type = TaskWarriorSync.TYPE; if (type.equals(TaskWarriorSync.TYPE)) { TW_ERRORS error = new TaskWarriorSync(mContext).sync(account); switch (error) { case NO_ERROR: last_message = mContext.getText(R.string.finish_sync); success = true; break; case TRY_LATER: last_message = mContext.getText(R.string.message_try_later); break; case ACCESS_DENIED: last_message = mContext.getText(R.string.message_access_denied); break; case CANNOT_CREATE_SOCKET: last_message = mContext.getText(R.string.message_create_socket); break; case ACCOUNT_SUSPENDED: last_message = mContext.getText(R.string.message_account_suspended); break; case CANNOT_PARSE_MESSAGE: last_message = mContext.getText(R.string.message_parse_message); break; case MESSAGE_ERRORS: last_message = mContext.getText(R.string.message_message_error); break; case CONFIG_PARSE_ERROR: last_message = mContext.getText(R.string.wrong_config); break; case NOT_ENABLED: default: return; } Log.d(TAG, "finish Sync"); } else if (type.equals(CalDavSync.TYPE)) { new CalDavSync(mContext).sync(account); } else { Log.wtf(TAG, "Unknown SyncType"); } mNotificationManager.cancel(notifyID); if (showNotification && !success) { mNB = new NotificationCompat.Builder(mContext) .setContentTitle("Mirakel: " + mContext.getText(R.string.finish_sync)) .setContentText(last_message).setSmallIcon(android.R.drawable.stat_notify_sync) .setPriority(NotificationCompat.PRIORITY_LOW).setContentIntent(p); mNotificationManager.notify(notifyID, mNB.build()); } Intent i = new Intent(Mirakel.SYNC_FINISHED); mContext.sendBroadcast(i); }
From source file:org.kontalk.sync.SyncAdapter.java
/** * Requests a manual sync to the system. * @return true if the sync has been actually requested to the system. */// ww w . ja v a 2 s .c o m public static boolean requestSync(Context context, boolean force) { if (!force && isThrottling()) { Log.d(TAG, "not requesting sync - throttling"); return false; } // do not start if offline if (Preferences.getOfflineMode()) { Log.d(TAG, "not requesting sync - offline mode"); return false; } Account acc = Authenticator.getDefaultAccount(context); Bundle extra = new Bundle(); // override auto-sync and background data settings extra.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); // put our sync ahead of other sync operations :) extra.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); ContentResolver.requestSync(acc, ContactsContract.AUTHORITY, extra); return true; }
From source file:com.example.jumpnote.android.SyncAdapter.java
@Override public void onPerformSync(final Account account, Bundle extras, String authority, final ContentProviderClient provider, final SyncResult syncResult) { TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); String clientDeviceId = tm.getDeviceId(); final long newSyncTime = System.currentTimeMillis(); final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false); final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false); final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false); C2DMReceiver.refreshAppC2DMRegistrationState(mContext); Log.i(TAG, "Beginning " + (uploadOnly ? "upload-only" : "full") + " sync for account " + account.name); // Read this account's sync metadata final SharedPreferences syncMeta = mContext.getSharedPreferences("sync:" + account.name, 0); long lastSyncTime = syncMeta.getLong(LAST_SYNC, 0); long lastServerSyncTime = syncMeta.getLong(SERVER_LAST_SYNC, 0); // Check for changes in either app-wide auto sync registration information, or changes in // the user's preferences for auto sync on this account; if either changes, piggy back the // new registration information in this sync. long lastRegistrationChangeTime = C2DMessaging.getLastRegistrationChange(mContext); boolean autoSyncDesired = ContentResolver.getMasterSyncAutomatically() && ContentResolver.getSyncAutomatically(account, JumpNoteContract.AUTHORITY); boolean autoSyncEnabled = syncMeta.getBoolean(DM_REGISTERED, false); // Will be 0 for no change, -1 for unregister, 1 for register. final int deviceRegChange; JsonRpcClient.Call deviceRegCall = null; if (autoSyncDesired != autoSyncEnabled || lastRegistrationChangeTime > lastSyncTime || initialize || manualSync) {//www . j ava2 s. c o m String registrationId = C2DMessaging.getRegistrationId(mContext); deviceRegChange = (autoSyncDesired && registrationId != null) ? 1 : -1; if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Auto sync selection or registration information has changed, " + (deviceRegChange == 1 ? "registering" : "unregistering") + " messaging for this device, for account " + account.name); } try { if (deviceRegChange == 1) { // Register device for auto sync on this account. deviceRegCall = new JsonRpcClient.Call(JumpNoteProtocol.DevicesRegister.METHOD); JSONObject params = new JSONObject(); DeviceRegistration device = new DeviceRegistration(clientDeviceId, DEVICE_TYPE, registrationId); params.put(JumpNoteProtocol.DevicesRegister.ARG_DEVICE, device.toJSON()); deviceRegCall.setParams(params); } else { // Unregister device for auto sync on this account. deviceRegCall = new JsonRpcClient.Call(JumpNoteProtocol.DevicesUnregister.METHOD); JSONObject params = new JSONObject(); params.put(JumpNoteProtocol.DevicesUnregister.ARG_DEVICE_ID, clientDeviceId); deviceRegCall.setParams(params); } } catch (JSONException e) { logErrorMessage("Error generating device registration remote RPC parameters.", manualSync); e.printStackTrace(); return; } } else { deviceRegChange = 0; } // Get the list of locally changed notes. If this is an upload-only sync and there were // no local changes, cancel the sync. List<ModelJava.Note> locallyChangedNotes = null; try { locallyChangedNotes = getLocallyChangedNotes(provider, account, new Date(lastSyncTime)); } catch (RemoteException e) { logErrorMessage("Remote exception accessing content provider: " + e.getMessage(), manualSync); e.printStackTrace(); syncResult.stats.numIoExceptions++; return; } if (uploadOnly && locallyChangedNotes.isEmpty() && deviceRegCall == null) { Log.i(TAG, "No local changes; upload-only sync canceled."); return; } // Set up the RPC sync calls final AuthenticatedJsonRpcJavaClient jsonRpcClient = new AuthenticatedJsonRpcJavaClient(mContext, Config.SERVER_AUTH_URL_TEMPLATE, Config.SERVER_RPC_URL); try { jsonRpcClient.blockingAuthenticateAccount(account, manualSync ? AuthenticatedJsonRpcJavaClient.NEED_AUTH_INTENT : AuthenticatedJsonRpcJavaClient.NEED_AUTH_NOTIFICATION, false); } catch (AuthenticationException e) { logErrorMessage("Authentication exception when attempting to sync.", manualSync); e.printStackTrace(); syncResult.stats.numAuthExceptions++; return; } catch (OperationCanceledException e) { Log.i(TAG, "Sync for account " + account.name + " manually canceled."); return; } catch (RequestedUserAuthenticationException e) { syncResult.stats.numAuthExceptions++; return; } catch (InvalidAuthTokenException e) { logErrorMessage("Invalid auth token provided by AccountManager when attempting to " + "sync.", manualSync); e.printStackTrace(); syncResult.stats.numAuthExceptions++; return; } // Set up the notes sync call. JsonRpcClient.Call notesSyncCall = new JsonRpcClient.Call(JumpNoteProtocol.NotesSync.METHOD); try { JSONObject params = new JSONObject(); params.put(JumpNoteProtocol.ARG_CLIENT_DEVICE_ID, clientDeviceId); params.put(JumpNoteProtocol.NotesSync.ARG_SINCE_DATE, Util.formatDateISO8601(new Date(lastServerSyncTime))); JSONArray locallyChangedNotesJson = new JSONArray(); for (ModelJava.Note locallyChangedNote : locallyChangedNotes) { locallyChangedNotesJson.put(locallyChangedNote.toJSON()); } params.put(JumpNoteProtocol.NotesSync.ARG_LOCAL_NOTES, locallyChangedNotesJson); notesSyncCall.setParams(params); } catch (JSONException e) { logErrorMessage("Error generating sync remote RPC parameters.", manualSync); e.printStackTrace(); syncResult.stats.numParseExceptions++; return; } List<JsonRpcClient.Call> jsonRpcCalls = new ArrayList<JsonRpcClient.Call>(); jsonRpcCalls.add(notesSyncCall); if (deviceRegChange != 0) jsonRpcCalls.add(deviceRegCall); jsonRpcClient.callBatch(jsonRpcCalls, new JsonRpcClient.BatchCallback() { public void onData(Object[] data) { if (data[0] != null) { // Read notes sync data. JSONObject dataJson = (JSONObject) data[0]; try { List<ModelJava.Note> changedNotes = new ArrayList<ModelJava.Note>(); JSONArray notesJson = dataJson.getJSONArray(JumpNoteProtocol.NotesSync.RET_NOTES); for (int i = 0; i < notesJson.length(); i++) { changedNotes.add(new ModelJava.Note(notesJson.getJSONObject(i))); } reconcileSyncedNotes(provider, account, changedNotes, syncResult.stats); // If sync is successful (no exceptions thrown), update sync metadata long newServerSyncTime = Util .parseDateISO8601(dataJson.getString(JumpNoteProtocol.NotesSync.RET_NEW_SINCE_DATE)) .getTime(); syncMeta.edit().putLong(LAST_SYNC, newSyncTime).commit(); syncMeta.edit().putLong(SERVER_LAST_SYNC, newServerSyncTime).commit(); Log.i(TAG, "Sync complete, setting last sync time to " + Long.toString(newSyncTime)); } catch (JSONException e) { logErrorMessage("Error parsing note sync RPC response", manualSync); e.printStackTrace(); syncResult.stats.numParseExceptions++; return; } catch (ParseException e) { logErrorMessage("Error parsing note sync RPC response", manualSync); e.printStackTrace(); syncResult.stats.numParseExceptions++; return; } catch (RemoteException e) { logErrorMessage("RemoteException in reconcileSyncedNotes: " + e.getMessage(), manualSync); e.printStackTrace(); return; } catch (OperationApplicationException e) { logErrorMessage("Could not apply batch operations to content provider: " + e.getMessage(), manualSync); e.printStackTrace(); return; } finally { provider.release(); } } // Read device reg data. if (deviceRegChange != 0) { // data[1] will be null in case of an error (successful unregisters // will have an empty JSONObject, not null). boolean registered = (data[1] != null && deviceRegChange == 1); syncMeta.edit().putBoolean(DM_REGISTERED, registered).commit(); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Stored account auto sync registration state: " + Boolean.toString(registered)); } } } public void onError(int callIndex, JsonRpcException e) { if (e.getHttpCode() == 403) { Log.w(TAG, "Got a 403 response, invalidating App Engine ACSID token"); jsonRpcClient.invalidateAccountAcsidToken(account); } provider.release(); logErrorMessage("Error calling remote note sync RPC", manualSync); e.printStackTrace(); } }); }
From source file:com.samsung.android.remindme.SyncAdapter.java
@Override public void onPerformSync(final Account account, Bundle extras, String authority, final ContentProviderClient provider, final SyncResult syncResult) { Log.i(TAG, "onPerformSync called!"); TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); String clientDeviceId = tm.getDeviceId(); final long newSyncTime = System.currentTimeMillis(); final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false); final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false); final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false); C2DMReceiver.refreshAppC2DMRegistrationState(mContext); Log.i(TAG, "Beginning " + (uploadOnly ? "upload-only" : "full") + " sync for account " + account.name); // Read this account's sync metadata final SharedPreferences syncMeta = mContext.getSharedPreferences("sync:" + account.name, 0); long lastSyncTime = syncMeta.getLong(LAST_SYNC, 0); long lastServerSyncTime = syncMeta.getLong(SERVER_LAST_SYNC, 0); // Check for changes in either app-wide auto sync registration information, or changes in // the user's preferences for auto sync on this account; if either changes, piggy back the // new registration information in this sync. long lastRegistrationChangeTime = C2DMessaging.getLastRegistrationChange(mContext); boolean autoSyncDesired = ContentResolver.getMasterSyncAutomatically() && ContentResolver.getSyncAutomatically(account, RemindMeContract.AUTHORITY); boolean autoSyncEnabled = syncMeta.getBoolean(DM_REGISTERED, false); // Will be 0 for no change, -1 for unregister, 1 for register. final int deviceRegChange; JsonRpcClient.Call deviceRegCall = null; if (autoSyncDesired != autoSyncEnabled || lastRegistrationChangeTime > lastSyncTime || initialize || manualSync) {/*from w w w. j a v a2s .com*/ String registrationId = C2DMessaging.getRegistrationId(mContext); deviceRegChange = (autoSyncDesired && registrationId != null) ? 1 : -1; if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Auto sync selection or registration information has changed, " + (deviceRegChange == 1 ? "registering" : "unregistering") + " messaging for this device, for account " + account.name); } try { if (deviceRegChange == 1) { // Register device for auto sync on this account. deviceRegCall = new JsonRpcClient.Call(RemindMeProtocol.DevicesRegister.METHOD); JSONObject params = new JSONObject(); DeviceRegistration device = new DeviceRegistration(clientDeviceId, DEVICE_TYPE, registrationId); params.put(RemindMeProtocol.DevicesRegister.ARG_DEVICE, device.toJSON()); deviceRegCall.setParams(params); } else { // Unregister device for auto sync on this account. deviceRegCall = new JsonRpcClient.Call(RemindMeProtocol.DevicesUnregister.METHOD); JSONObject params = new JSONObject(); params.put(RemindMeProtocol.DevicesUnregister.ARG_DEVICE_ID, clientDeviceId); deviceRegCall.setParams(params); } } catch (JSONException e) { logErrorMessage("Error generating device registration remote RPC parameters.", manualSync); e.printStackTrace(); return; } } else { deviceRegChange = 0; } // Get the list of locally changed alerts. If this is an upload-only sync and there were // no local changes, cancel the sync. List<ModelJava.Alert> locallyChangedAlerts = null; try { locallyChangedAlerts = getLocallyChangedAlerts(provider, account, new Date(lastSyncTime)); } catch (RemoteException e) { logErrorMessage("Remote exception accessing content provider: " + e.getMessage(), manualSync); e.printStackTrace(); syncResult.stats.numIoExceptions++; return; } if (uploadOnly && locallyChangedAlerts.isEmpty() && deviceRegCall == null) { Log.i(TAG, "No local changes; upload-only sync canceled."); return; } // Set up the RPC sync calls final AuthenticatedJsonRpcJavaClient jsonRpcClient = new AuthenticatedJsonRpcJavaClient(mContext, Config.SERVER_AUTH_URL_TEMPLATE, Config.SERVER_RPC_URL); try { jsonRpcClient.blockingAuthenticateAccount(account, manualSync ? AuthenticatedJsonRpcJavaClient.NEED_AUTH_INTENT : AuthenticatedJsonRpcJavaClient.NEED_AUTH_NOTIFICATION, false); } catch (AuthenticationException e) { logErrorMessage("Authentication exception when attempting to sync. root cause: " + e.getMessage(), manualSync); e.printStackTrace(); syncResult.stats.numAuthExceptions++; return; } catch (OperationCanceledException e) { Log.i(TAG, "Sync for account " + account.name + " manually canceled."); return; } catch (RequestedUserAuthenticationException e) { syncResult.stats.numAuthExceptions++; return; } catch (InvalidAuthTokenException e) { logErrorMessage("Invalid auth token provided by AccountManager when attempting to " + "sync.", manualSync); e.printStackTrace(); syncResult.stats.numAuthExceptions++; return; } // Set up the alerts sync call. JsonRpcClient.Call alertsSyncCall = new JsonRpcClient.Call(RemindMeProtocol.AlertsSync.METHOD); try { JSONObject params = new JSONObject(); params.put(RemindMeProtocol.ARG_CLIENT_DEVICE_ID, clientDeviceId); params.put(RemindMeProtocol.AlertsSync.ARG_SINCE_DATE, Util.formatDateISO8601(new Date(lastServerSyncTime))); JSONArray locallyChangedAlertsJson = new JSONArray(); for (ModelJava.Alert locallyChangedAlert : locallyChangedAlerts) { locallyChangedAlertsJson.put(locallyChangedAlert.toJSON()); } params.put(RemindMeProtocol.AlertsSync.ARG_LOCAL_NOTES, locallyChangedAlertsJson); alertsSyncCall.setParams(params); } catch (JSONException e) { logErrorMessage("Error generating sync remote RPC parameters.", manualSync); e.printStackTrace(); syncResult.stats.numParseExceptions++; return; } List<JsonRpcClient.Call> jsonRpcCalls = new ArrayList<JsonRpcClient.Call>(); jsonRpcCalls.add(alertsSyncCall); if (deviceRegChange != 0) jsonRpcCalls.add(deviceRegCall); jsonRpcClient.callBatch(jsonRpcCalls, new JsonRpcClient.BatchCallback() { public void onData(Object[] data) { if (data[0] != null) { // Read alerts sync data. JSONObject dataJson = (JSONObject) data[0]; try { List<ModelJava.Alert> changedAlerts = new ArrayList<ModelJava.Alert>(); JSONArray alertsJson = dataJson.getJSONArray(RemindMeProtocol.AlertsSync.RET_NOTES); for (int i = 0; i < alertsJson.length(); i++) { changedAlerts.add(new ModelJava.Alert(alertsJson.getJSONObject(i))); } reconcileSyncedAlerts(provider, account, changedAlerts, syncResult.stats); // If sync is successful (no exceptions thrown), update sync metadata long newServerSyncTime = Util .parseDateISO8601( dataJson.getString(RemindMeProtocol.AlertsSync.RET_NEW_SINCE_DATE)) .getTime(); syncMeta.edit().putLong(LAST_SYNC, newSyncTime).commit(); syncMeta.edit().putLong(SERVER_LAST_SYNC, newServerSyncTime).commit(); Log.i(TAG, "Sync complete, setting last sync time to " + Long.toString(newSyncTime)); } catch (JSONException e) { logErrorMessage("Error parsing alert sync RPC response", manualSync); e.printStackTrace(); syncResult.stats.numParseExceptions++; return; } catch (ParseException e) { logErrorMessage("Error parsing alert sync RPC response", manualSync); e.printStackTrace(); syncResult.stats.numParseExceptions++; return; } catch (RemoteException e) { logErrorMessage("RemoteException in reconcileSyncedAlerts: " + e.getMessage(), manualSync); e.printStackTrace(); return; } catch (OperationApplicationException e) { logErrorMessage("Could not apply batch operations to content provider: " + e.getMessage(), manualSync); e.printStackTrace(); return; } finally { provider.release(); } } // Read device reg data. if (deviceRegChange != 0) { // data[1] will be null in case of an error (successful unregisters // will have an empty JSONObject, not null). boolean registered = (data[1] != null && deviceRegChange == 1); syncMeta.edit().putBoolean(DM_REGISTERED, registered).commit(); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Stored account auto sync registration state: " + Boolean.toString(registered)); } } } public void onError(int callIndex, JsonRpcException e) { if (e.getHttpCode() == 403) { Log.w(TAG, "Got a 403 response, invalidating App Engine ACSID token"); jsonRpcClient.invalidateAccountAcsidToken(account); } provider.release(); logErrorMessage("Error calling remote alert sync RPC", manualSync); e.printStackTrace(); } }); }
From source file:com.activiti.android.platform.provider.transfer.ContentTransferManager.java
public static void startShare(Activity activity, String contentId, String filepath, String mimetype) { Bundle settingsBundle = new Bundle(); settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); settingsBundle.putInt(ContentTransferSyncAdapter.ARGUMENT_MODE, ContentTransferSyncAdapter.MODE_SHARE); settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_FILE_PATH, filepath); settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_CONTENT_ID, contentId); settingsBundle.putString(ContentTransferSyncAdapter.ARGUMENT_MIMETYPE, mimetype); ContentResolver.requestSync(ActivitiAccountManager.getInstance(activity).getCurrentAndroidAccount(), ContentTransferProvider.AUTHORITY, settingsBundle); }
From source file:com.skywomantechnology.app.guildviewer.sync.GuildViewerSyncAdapter.java
/** * Sync the remote data immediately passing along sync data to * the routines to determine how much data to sync * * @param context Activity context//from ww w . j a va2 s. com * @param syncAll if true process all news items within the date range, * if false process normally by checking the timestamps * @param syncMax Max number of news items to process */ public static void syncImmediately(Context context, boolean syncAll, int syncMax) { Bundle bundle = new Bundle(); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); bundle.putBoolean(SYNC_EXTRAS_SYNC_ALL, syncAll); bundle.putInt(SYNC_EXTRAS_SYNC_MAX, syncMax); ContentResolver.requestSync(getSyncAccount(context), context.getString(R.string.content_authority), bundle); }
From source file:com.bodeme.easycloud.syncadapter.DavSyncAdapter.java
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {// www . j av a 2 s . co m Log.i(TAG, "Performing sync for authority " + authority); // set class loader for iCal4j ResourceLoader Thread.currentThread().setContextClassLoader(getContext().getClassLoader()); // create httpClient, if necessary httpClientLock.writeLock().lock(); if (httpClient == null) { Log.d(TAG, "Creating new DavHttpClient"); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); httpClient = DavHttpClient.create(settings.getBoolean(Constants.SETTING_DISABLE_COMPRESSION, false), settings.getBoolean(Constants.SETTING_NETWORK_LOGGING, false), !settings.getBoolean(Constants.IGNORE_SSL_ERRORS, false)); } // prevent httpClient shutdown until we're ready by holding a read lock // acquiring read lock before releasing write lock will downgrade the write lock to a read lock httpClientLock.readLock().lock(); httpClientLock.writeLock().unlock(); try { // get local <-> remote collection pairs Map<LocalCollection<?>, RemoteCollection<?>> syncCollections = getSyncPairs(account, provider); if (syncCollections == null) Log.i(TAG, "Nothing to synchronize"); else try { for (Map.Entry<LocalCollection<?>, RemoteCollection<?>> entry : syncCollections.entrySet()) new SyncManager(entry.getKey(), entry.getValue()) .synchronize(extras.containsKey(ContentResolver.SYNC_EXTRAS_MANUAL), syncResult); } catch (DavException ex) { syncResult.stats.numParseExceptions++; Log.e(TAG, "Invalid DAV response", ex); } catch (HttpException ex) { if (ex.getCode() == HttpStatus.SC_UNAUTHORIZED) { Log.e(TAG, "HTTP Unauthorized " + ex.getCode(), ex); syncResult.stats.numAuthExceptions++; } else if (ex.isClientError()) { Log.e(TAG, "Hard HTTP error " + ex.getCode(), ex); syncResult.stats.numParseExceptions++; } else { Log.w(TAG, "Soft HTTP error " + ex.getCode() + " (Android will try again later)", ex); syncResult.stats.numIoExceptions++; } } catch (LocalStorageException ex) { syncResult.databaseError = true; Log.e(TAG, "Local storage (content provider) exception", ex); } catch (IOException ex) { syncResult.stats.numIoExceptions++; Log.e(TAG, "I/O error (Android will try again later)", ex); } } finally { // allow httpClient shutdown httpClientLock.readLock().unlock(); } Log.i(TAG, "Sync complete for " + authority); }
From source file:com.openerp.services.UserGroupsSyncService.java
/** * Perform sync.//w ww . j a va 2 s . co m * * @param context * the context * @param account * the account * @param extras * the extras * @param authority * the authority * @param provider * the provider * @param syncResult * the sync result */ public void performSync(Context context, Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { // TODO Auto-generated method stub try { UserGroupsDb usergroups = new UserGroupsDb(context); Intent intent = new Intent(); intent.setAction(SyncFinishReceiver.SYNC_FINISH); if (OpenERPServerConnection.isNetworkAvailable(context)) { Log.i(TAG + "::performSync()", "Sync with Server Started"); OEHelper oe = usergroups.getOEInstance(); if (oe.syncWithServer(usergroups, null, false, false)) { MailFollowerDb group_follower = new MailFollowerDb(context); OEHelper oe_1 = group_follower.getOEInstance(); JSONObject domain = new JSONObject(); int partner_id = Integer.parseInt(OpenERPAccountManager.currentUser(context).getPartner_id()); domain.accumulate("domain", new JSONArray("[[\"partner_id\", \"=\", " + partner_id + "],[\"res_model\",\"=\", \"" + usergroups.getModelName() + "\"]]")); if (oe_1.syncWithServer(group_follower, domain, false, false)) { Log.i(TAG, "UserGroups Sync Finished"); MailFollowerDb follower = new MailFollowerDb(context); List<HashMap<String, Object>> user_groups = follower.executeSQL(follower.getModelName(), new String[] { "res_id" }, new String[] { "partner_id = ?", "AND", "res_model = ?" }, new String[] { partner_id + "", "mail.group" }); JSONArray group_ids = new JSONArray(); if (user_groups.size() > 0) { for (HashMap<String, Object> row : user_groups) { group_ids.put(Integer.parseInt(row.get("res_id").toString())); } } context.sendBroadcast(intent); Bundle bundle = new Bundle(); bundle.putString("group_ids", group_ids.toString()); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); ContentResolver.requestSync(account, MessageProvider.AUTHORITY, bundle); } } } else { Log.e("OpenERPServerConnection", "Unable to Connect with server"); } } catch (Exception e) { e.printStackTrace(); } }