Java Code Examples for android.content.SyncResult

The following are top voted examples for showing how to use android.content.SyncResult. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: iosched-reader   File: ForceSyncNowAction.java   Source Code and License 7 votes vote down vote up
@Override
public void run(final Context context, final Callback callback) {
    ConferenceDataHandler.resetDataTimestamp(context);
    final Bundle bundle = new Bundle();
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    new AsyncTask<Context, Void, Void>() {
        @Override
        protected Void doInBackground(Context... contexts) {
            Account account = AccountUtils.getActiveAccount(context);
            if (account == null) {
                callback.done(false, "Cannot sync if there is no active account.");
            } else {
                new SyncHelper(contexts[0]).performSync(new SyncResult(),
                  AccountUtils.getActiveAccount(context), bundle);
            }
          return null;
        }
    }.execute(context);
}
 
Example 2
Project: chromium-for-android-56-debug-video   File: ChromeBrowserSyncAdapter.java   Source Code and License 6 votes vote down vote up
private BrowserParts getBrowserParts(final Context context,
        final String account, final PendingInvalidation invalidation,
        final SyncResult syncResult, final Semaphore semaphore) {
    return new EmptyBrowserParts() {
        @Override
        public void finishNativeInitialization() {
            // Startup succeeded, so we can notify the invalidation.
            notifyInvalidation(invalidation.mObjectSource, invalidation.mObjectId,
                    invalidation.mVersion, invalidation.mPayload);
            semaphore.release();
        }

        @Override
        public void onStartupFailure() {
            // The startup failed, so we defer the invalidation.
            DelayedInvalidationsController.getInstance().addPendingInvalidation(
                    context, account, invalidation);
            // Using numIoExceptions so Android will treat this as a soft error.
            syncResult.stats.numIoExceptions++;
            semaphore.release();
        }
    };
}
 
Example 3
Project: odoo-work   File: LoginActivity.java   Source Code and License 6 votes vote down vote up
private void getUserData(final OUser user) {
    progressDialog.setMessage(getString(R.string.msg_setting_your_account));
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {

            registerForFCM(user);

            ProjectTeams teams = new ProjectTeams(LoginActivity.this);
            SyncAdapter adapter = teams.getSyncAdapter();
            SyncResult result = adapter.syncModelData();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressDialog.dismiss();
            startSplashScreen();
        }
    }.execute();
}
 
Example 4
Project: odoo-work   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
private void deleteFromLocal(OModel model, HashSet<Integer> checkIds, SyncResult syncResult) {
    ODomain domain = new ODomain();
    domain.add("id", "in", new ArrayList<>(checkIds));
    OdooResult result = odoo.searchRead(model.getModelName(), new OdooFields("id"), domain, 0, 0, null);
    if (result == null) {
        Log.e(TAG, "FATAL : Request aborted.");
        return;
    }
    if (result.containsKey("error")) {
        Log.e(TAG, result.get("error") + "");
        return;
    }
    HashSet<Integer> serverIds = new HashSet<>();
    for (OdooRecord record : result.getRecords()) {
        serverIds.add(record.getDouble("id").intValue());
    }
    checkIds.removeAll(serverIds);
    int deleted = model.deleteAll(new ArrayList<>(checkIds));
    if (syncResult != null) syncResult.stats.numDeletes += deleted;
}
 
Example 5
Project: odoo-work   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
private void deleteFromServer(OModel model, SyncResult syncResult) {
    LocalRecordState recordState = new LocalRecordState(mContext);
    List<Integer> ids = recordState.getServerIds(model.getModelName());
    if (!ids.isEmpty()) {
        OdooResult result = odoo.unlinkRecord(model.getModelName(), ids);
        if (result == null) {
            Log.e(TAG, "FATAL : Request aborted.");
            return;
        }
        if (result.containsKey("error")) {
            Log.e(TAG, result.get("error") + "");
            return;
        }
        if (result.getBoolean("result")) {
            syncResult.stats.numSkippedEntries += ids.size();
            recordState.delete("server_id in (" + TextUtils.join(", ", ids) + ") and model = ?", model.getModelName());
        }
    }
}
 
Example 6
Project: TVGuide   File: TvGuideSyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {

    if ( Utility.isNotDuplicateSync(getContext())) {
        if (BuildConfig.DEBUG) Log.d(LOG_TAG,"Start sync!");
        sendSyncStatus(START_SYNC);
        final TvService service = TvApiClient.getClient().create(TvService.class);
        syncCategories(service, provider, syncResult);
        syncChannels(service, provider, syncResult);
        syncPrograms(service, provider, syncResult);
        notifyTvGuide(syncResult.stats.numInserts, syncResult.stats.numIoExceptions);
        prefHelper.setLastSyncTime(getContext().getString(R.string.pref_last_sync_time_key),
                                            System.currentTimeMillis());
        prefHelper.setFirstRun(getContext().getString(R.string.pref_fist_run_key),false);
        sendSyncStatus(END_SYNC);
        if (BuildConfig.DEBUG) Log.d(LOG_TAG,"End sync!");
    }
}
 
Example 7
Project: EasyAppleSyncAdapter   File: BaseSyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
                          SyncResult syncResult) {
    // required for dav4android (ServiceLoader)
    Thread.currentThread().setContextClassLoader(getContext().getClassLoader());

    try {
        syncLocalAndRemoteCollections(account, provider);
        syncCalendarsEvents(account, provider, extras);

        // notify any registered caller that sync operation is finished
        getContext().getContentResolver().notifyChange(GlobalConstant.CONTENT_URI, null, false);
    } catch (InvalidAccountException | CalendarStorageException e) {
        e.printStackTrace();
    }
}
 
Example 8
Project: simplest-sync-adapter   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
/**
 * Called by the Android system in response to a request to run the sync adapter. The work
 * required to read data from the network, parse it, and store it in the content provider
 * should be done here. Extending AbstractThreadedSyncAdapter ensures that all methods within SyncAdapter
 * run on a background thread. For this reason, blocking I/O and other long-running tasks can be
 * run <em>in situ</em>, and you don't have to set up a separate thread for them.
 *
 * <p>
 * <p>This is where we actually perform any work required to perform a sync.
 * {@link AbstractThreadedSyncAdapter} guarantees that this will be called on a non-UI thread,
 * so it is safe to perform blocking I/O here.
 * <p>
 *
 * <p>The syncResult argument allows you to pass information back to the method that triggered
 * the sync.
 */
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
                          ContentProviderClient provider, SyncResult syncResult) {

    // Your code to sync data
    // between mobile database and
    // the server goes here.

    for (int i = 0; i < 15; i++) {
        try {
            Thread.sleep(1000);
            Log.i(TAG, ">>>> sleeping the thread: " + (i + 1));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }   // end for

    // write DB data sanity checks at the end.
}
 
Example 9
Project: smconf-android   File: ForceSyncNowAction.java   Source Code and License 6 votes vote down vote up
@Override
public void run(final Context context, final Callback callback) {
    ConferenceDataHandler.resetDataTimestamp(context);
    final Bundle bundle = new Bundle();
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    new AsyncTask<Context, Void, Void>() {
        @Override
        protected Void doInBackground(Context... contexts) {
            Account account = AccountUtils.getActiveAccount(context);
            if (account == null) {
                callback.done(false, "Cannot sync if there is no active account.");
            } else {
                new SyncHelper(contexts[0]).performSync(new SyncResult(),
                  AccountUtils.getActiveAccount(context), bundle);
            }
          return null;
        }
    }.execute(context);
}
 
Example 10
Project: odoo-follow-up   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
private void deleteFromLocal(OModel model, HashSet<Integer> checkIds, SyncResult syncResult) {
    ODomain domain = new ODomain();
    domain.add("id", "in", new ArrayList<>(checkIds));
    OdooResult result = odoo.searchRead(model.getModelName(), new OdooFields("id"), domain, 0, 0, null);
    if (result == null) {
        Log.e(TAG, "FATAL : Request aborted.");
        return;
    }
    if (result.containsKey("error")) {
        Log.e(TAG, result.get("error") + "");
        return;
    }
    HashSet<Integer> serverIds = new HashSet<>();
    for (OdooRecord record : result.getRecords()) {
        serverIds.add(record.getDouble("id").intValue());
    }
    checkIds.removeAll(serverIds);
    int deleted = model.deleteAll(new ArrayList<>(checkIds));
    if (syncResult != null) syncResult.stats.numDeletes += deleted;
}
 
Example 11
Project: odoo-follow-up   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
private void deleteFromServer(OModel model, SyncResult syncResult) {
    LocalRecordState recordState = new LocalRecordState(mContext);
    List<Integer> ids = recordState.getServerIds(model.getModelName());
    if (!ids.isEmpty()) {
        OdooResult result = odoo.unlinkRecord(model.getModelName(), ids);
        if (result == null) {
            Log.e(TAG, "FATAL : Request aborted.");
            return;
        }
        if (result.containsKey("error")) {
            Log.e(TAG, result.get("error") + "");
            return;
        }
        if (result.getBoolean("result")) {
            syncResult.stats.numSkippedEntries += ids.size();
            recordState.delete("server_id in (" + TextUtils.join(", ", ids) + ") and model = ?", model.getModelName());
        }
    }
}
 
Example 12
Project: gito-github-client   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
                          ContentProviderClient provider, SyncResult syncResult) {
    String key = "onPerformSync";
    final GithubRemoteDataSource githubRepository =
            GithubRepository.Injection.provideRemoteDataSource(getContext());
    githubRepository.getUserSync();
    Cursor cursor = getContext().getContentResolver().query(RepositoryContract
                    .RepositoryEntry.CONTENT_URI_REPOSITORY_STARGAZERS,
            RepositoryContract.RepositoryEntry.REPOSITORY_COLUMNS_WITH_ADDITIONAL_INFO,
            null, null, null);
    boolean forceSync = cursor == null || !cursor.moveToFirst();
    if (cursor != null) {
        cursor.close();
    }

    if (mSyncSettings.isSynced(key) && !forceSync) {
        return;
    } else {
        mSyncSettings.synced(key);
    }
    List<Repository> repositories = githubRepository.getRepositoriesSync();
    githubRepository.getRepositoriesWithAdditionalInfoSync(repositories);
    githubRepository.getTrendingRepositoriesSync(githubRepository.getDefaultPeriodForTrending(),
            githubRepository.getDefaultLanguageForTrending(), false);
}
 
Example 13
Project: TimesMunch   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
    public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
        String data = "";
//        try {
//            URL url = new URL("http://api.nytimes.com/svc/news/v3/content/nyt/all/.json?limit=5&api-key=fd0457bbde566c4783e7643346b77859:5:74605174");
//            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//            connection.connect();
//            InputStream inStream = connection.getInputStream();
//            data = getInputData(inStream);
//        } catch (Throwable e) {
//            e.printStackTrace();
//        }
//
//
//        Gson gson = new Gson();
//        NYTSearchResult result = gson.fromJson(data, NYTSearchResult.class);
//        for (int i = 0; i < 5; i++) {
//            String title = result.getResults().get(i).getTitle();
//            Log.d(TAG, "THE TITLE OF THE " + (i + 1)
//                    + " ARTICLE IS: " + title);
//        }
    }
 
Example 14
Project: OurVLE   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
/**
 * Perform a sync for this account. SyncAdapter-specific parameters may
 * be specified in extras, which is guaranteed to not be null. Invocations
 * of this method are guaranteed to be serialized.
 *
 * @param account    the account that should be synced
 * @param extras     SyncAdapter-specific parameters
 * @param authority  the authority of this sync request
 * @param provider   a ContentProviderClient that points to the ContentProvider for this
 *                   authority
 * @param syncResult SyncAdapter-specific parameters
 */
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
    sharedPrefs = super.getContext().getSharedPreferences(MoodleConstants.PREFS_STRING, Context.MODE_PRIVATE);

    first_update = sharedPrefs.getInt(MoodleConstants.FIRST_UPDATE, 404); // flag to check whether this is the first update

    mSites = new Select().all().from(SiteInfo.class).execute();

    if(mSites==null)
        return;
    if(mSites.size()<=0)
        return;

    token = mSites.get(0).getToken(); // gets the url token

    courses = new Select().all().from(Course.class).execute(); // gets all the courses

    updateLatestEvents();
    updateLatestForumPosts();
    updateLatestDiscussionPots();
   // updateLatestCourseContent();
    updateMembers();
}
 
Example 15
Project: AndroidChromium   File: ChromeBrowserSyncAdapter.java   Source Code and License 6 votes vote down vote up
private BrowserParts getBrowserParts(final Context context,
        final String account, final PendingInvalidation invalidation,
        final SyncResult syncResult, final Semaphore semaphore) {
    return new EmptyBrowserParts() {
        @Override
        public void finishNativeInitialization() {
            // Startup succeeded, so we can notify the invalidation.
            notifyInvalidation(invalidation.mObjectSource, invalidation.mObjectId,
                    invalidation.mVersion, invalidation.mPayload);
            semaphore.release();
        }

        @Override
        public void onStartupFailure() {
            // The startup failed, so we defer the invalidation.
            DelayedInvalidationsController.getInstance().addPendingInvalidation(
                    context, account, invalidation);
            // Using numIoExceptions so Android will treat this as a soft error.
            syncResult.stats.numIoExceptions++;
            semaphore.release();
        }
    };
}
 
Example 16
Project: android-wg-planer   File: TimetableSyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
    Lesson[] oldLessons = TimetableContentHelper.getTimetable(getContext());
    Lesson[] lessons = new SyncServerInterface(getContext()).getTimetable();

    lessons = ClassesUtils.filterLessons(getContext(), lessons);

    if (lessons.length != oldLessons.length || !Utils.containsAll(lessons, oldLessons)) {
        TimetableNotification.notify(getContext());
    }

    TimetableContentHelper.clearTimetable(getContext());

    if (lessons.length > 0) {
        TimetableContentHelper.addLessons(getContext(), lessons);
    }
}
 
Example 17
Project: android-wg-planer   File: RepresentationsSyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
    Representation[] oldRepresentations = RepresentationsContentHelper.getRepresentations(getContext());
    Representation[] representations = new SyncServerInterface(getContext()).getRepresentations();

    representations = ClassesUtils.filterRepresentations(getContext(), representations);

    if (representations.length != oldRepresentations.length || !Utils.containsAll(representations, oldRepresentations)) {
        RepresentationsNotification.notify(getContext());
    }

    RepresentationsContentHelper.clearRepresentations(getContext());

    if (representations.length > 0) {
        RepresentationsContentHelper.addRepresentations(getContext(), representations);
    }
}
 
Example 18
Project: android-wg-planer   File: UserSyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
    try {
        String username = mAccountManager.blockingGetAuthToken(account, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS, true);

        SyncServerInterface serverInterface = new SyncServerInterface(getContext());
        User user = serverInterface.getUserInfo(username);

        UserContentHelper.clearUsers(getContext());

        if (user != null) {
            UserContentHelper.addUser(getContext(), user);
        }
    } catch (OperationCanceledException | IOException | AuthenticatorException e) {
        e.printStackTrace();
        syncResult.stats.numParseExceptions++;
    }
}
 
Example 19
Project: 2015-Google-I-O-app   File: ForceSyncNowAction.java   Source Code and License 6 votes vote down vote up
@Override
public void run(final Context context, final Callback callback) {
    ConferenceDataHandler.resetDataTimestamp(context);
    final Bundle bundle = new Bundle();
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    new AsyncTask<Context, Void, Void>() {
        @Override
        protected Void doInBackground(Context... contexts) {
            Account account = AccountUtils.getActiveAccount(context);
            if (account == null) {
                callback.done(false, "Cannot sync if there is no active account.");
            } else {
                new SyncHelper(contexts[0]).performSync(new SyncResult(),
                  AccountUtils.getActiveAccount(context), bundle);
            }
          return null;
        }
    }.execute(context);
}
 
Example 20
Project: Vafrinn   File: ChromiumSyncAdapter.java   Source Code and License 6 votes vote down vote up
private BrowserStartupController.StartupCallback getStartupCallback(final Context context,
        final String account, final PendingInvalidation invalidation,
        final SyncResult syncResult, final Semaphore semaphore) {
    return new BrowserStartupController.StartupCallback() {
        @Override
        public void onSuccess(boolean alreadyStarted) {
            // Startup succeeded, so we can notify the invalidation.
            notifyInvalidation(invalidation.mObjectSource, invalidation.mObjectId,
                    invalidation.mVersion, invalidation.mPayload);
            semaphore.release();
        }

        @Override
        public void onFailure() {
            // The startup failed, so we defer the invalidation.
            DelayedInvalidationsController.getInstance().addPendingInvalidation(
                    context, account, invalidation);
            // Using numIoExceptions so Android will treat this as a soft error.
            syncResult.stats.numIoExceptions++;
            semaphore.release();
        }
    };
}
 
Example 21
Project: BeAuthentic   File: AuthenticSyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, final SyncResult syncResult) {
    final Account primaryAccount = Sessions.getPrimaryPhoneAccount(AccountManager.get(getContext()));
    if (primaryAccount != null) {
        retrieveMessageFromFirebase(primaryAccount, new ValueEventListenerAdapter() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                syncResult.stats.numUpdates++;
                final Intent intent = new Intent(LoggedActivity.ACTION_REFRESH);
                intent.putExtra(LoggedActivity.EXTRA_MESSAGE, TextUtils.isEmpty(snapshot.getValue().toString()) ? "" : snapshot.getValue().toString());
                getContext().sendBroadcast(intent);
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {
                syncResult.stats.numIoExceptions++;
            }
        });
    }
}
 
Example 22
Project: FMTech   File: bty.java   Source Code and License 6 votes vote down vote up
public bty(btl parambtl, Context paramContext, int paramInt, bup parambup, SyncResult paramSyncResult, ois paramois, long paramLong)
{
  this.a = paramInt;
  this.b = parambup;
  this.c = paramSyncResult;
  this.t = paramois;
  this.v = ((AutoBackupEnvironment)mbb.a(paramContext, AutoBackupEnvironment.class));
  this.u = paramLong;
  this.s = System.currentTimeMillis();
  if (System.currentTimeMillis() - parambtl.j > 900000L)
  {
    parambtl.i = ((ifj)mbb.a(parambtl.f, ifj.class)).f().d();
    parambtl.j = System.currentTimeMillis();
  }
  this.d = parambtl.i;
  this.j = btl.a(parambtl, paramContext);
  this.f = ((iwb)mbb.a(paramContext, iwb.class)).a(paramInt);
  int i1 = parambtl.a().size();
  this.e = ((this.d - b()) / i1);
  this.r = Math.min(104857600L, this.e);
  this.l = this.r;
  SQLiteDatabase localSQLiteDatabase = bqj.a(paramContext, paramInt).getReadableDatabase();
  this.h = btl.a(localSQLiteDatabase, 1);
  this.g = btl.a(localSQLiteDatabase, 10);
}
 
Example 23
Project: FMTech   File: auq.java   Source Code and License 6 votes vote down vote up
private final void a(int paramInt, bup parambup, SyncResult paramSyncResult, boolean paramBoolean)
{
  try
  {
    if (Log.isLoggable("PhotoSyncService", 4)) {
      new StringBuilder(66).append("----> Start highlights metadata down sync for account: ").append(paramInt);
    }
    bsn localbsn = bsn.e;
    bry.a(getContext(), paramInt, parambup, localbsn);
    bgp.a(getContext(), paramInt, dnn.b, System.currentTimeMillis());
    return;
  }
  catch (Exception localException)
  {
    do
    {
      if (Log.isLoggable("PhotoSyncService", 6)) {
        Log.e("PhotoSyncService", 65 + "----> doHighlightsMetadataDownSync error for account: " + paramInt);
      }
    } while (GooglePhotoDownsyncService.a(localException));
    SyncStats localSyncStats = paramSyncResult.stats;
    localSyncStats.numIoExceptions = (1L + localSyncStats.numIoExceptions);
  }
}
 
Example 24
Project: FMTech   File: auq.java   Source Code and License 6 votes vote down vote up
private final void a(List<Integer> paramList, bup parambup, SyncResult paramSyncResult)
{
  hyi localhyi = (hyi)mbb.a(getContext(), hyi.class);
  Iterator localIterator = paramList.iterator();
  while (localIterator.hasNext())
  {
    int i = ((Integer)localIterator.next()).intValue();
    if (localhyi.b(bwb.g, i))
    {
      try
      {
        a(i, parambup, paramSyncResult, false);
      }
      catch (Exception localException)
      {
        Log.e("PhotoSyncService", 83 + "----> performUnconditionalHighlightsMetadataDownSync error for account: " + i, localException);
      }
      if (!GooglePhotoDownsyncService.a(localException))
      {
        SyncStats localSyncStats = paramSyncResult.stats;
        localSyncStats.numIoExceptions = (1L + localSyncStats.numIoExceptions);
      }
    }
  }
}
 
Example 25
Project: FMTech   File: ForceSyncNowAction.java   Source Code and License 6 votes vote down vote up
@Override
public void run(final Context context, final Callback callback) {
    ConferenceDataHandler.resetDataTimestamp(context);
    final Bundle bundle = new Bundle();
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    new AsyncTask<Context, Void, Void>() {
        @Override
        protected Void doInBackground(Context... contexts) {
            Account account = AccountUtils.getActiveAccount(context);
            if (account == null) {
                callback.done(false, "Cannot sync if there is no active account.");
            } else {
                new SyncHelper(contexts[0]).performSync(new SyncResult(),
                  AccountUtils.getActiveAccount(context), bundle);
            }
          return null;
        }
    }.execute(context);
}
 
Example 26
Project: 365browser   File: ChromeBrowserSyncAdapter.java   Source Code and License 6 votes vote down vote up
private BrowserParts getBrowserParts(final Context context,
        final String account, final PendingInvalidation invalidation,
        final SyncResult syncResult, final Semaphore semaphore) {
    return new EmptyBrowserParts() {
        @Override
        public void finishNativeInitialization() {
            // Startup succeeded, so we can notify the invalidation.
            notifyInvalidation(invalidation.mObjectSource, invalidation.mObjectId,
                    invalidation.mVersion, invalidation.mPayload);
            semaphore.release();
        }

        @Override
        public void onStartupFailure() {
            // The startup failed, so we defer the invalidation.
            DelayedInvalidationsController.getInstance().addPendingInvalidation(
                    context, account, invalidation);
            // Using numIoExceptions so Android will treat this as a soft error.
            syncResult.stats.numIoExceptions++;
            semaphore.release();
        }
    };
}
 
Example 27
Project: aelf-dailyreadings   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
private void syncReading(LecturesController.WHAT what, AelfDate when, SyncResult syncResult) throws InterruptedException {
    // Load from network, if not in cache and not outdated
    if(!mController.isLecturesInCache(what, when, false)) {
        try {
            Log.i(TAG, what.urlName()+" for "+when.toIsoString()+" QUEUED");
            pendingDownloads.add(mController.getLecturesFromNetwork(what, when));
        } catch (IOException e) {
            if (e.getCause() instanceof InterruptedException) {
                throw (InterruptedException) e.getCause();
            }
            // Error already propagated to Sentry. Do not propagate twice !
            Log.e(TAG, "I/O error while syncing");
            syncResult.stats.numIoExceptions++;
        }
    } else {
        Log.i(TAG, what.urlName()+" for "+when.toIsoString()+" SKIPPED");
    }
}
 
Example 28
Project: gma-android   File: GmaSyncService.java   Source Code and License 6 votes vote down vote up
@Override
public void onHandleIntent(@NonNull final Intent intent) {
    // short-circuit if we don't have a valid guid
    final String guid = intent.getStringExtra(EXTRA_GUID);
    if (guid == null) {
        return;
    }

    // dispatch sync request
    final int type = intent.getIntExtra(EXTRA_SYNCTYPE, SYNCTYPE_NONE);
    final Bundle extras = intent.getExtras();
    final SyncResult result = new SyncResult();
    mSyncAdapter.dispatchSync(guid, type, extras, result);

    // request a sync next time we are online if we had errors syncing
    if (result.hasError()) {
        final Account account = AccountUtils.getAccount(this, ACCOUNT_TYPE, guid);
        if (account != null) {
            ContentResolver.requestSync(account, SYNC_AUTHORITY, extras);
        }
    }
}
 
Example 29
Project: saarang-iosched   File: ForceSyncNowAction.java   Source Code and License 6 votes vote down vote up
@Override
public void run(final Context context, final Callback callback) {
    final Bundle bundle = new Bundle();
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    new AsyncTask<Context, Void, Void>() {
        @Override
        protected Void doInBackground(Context... contexts) {
            Account account = AccountUtils.getActiveAccount(context);
            if (account == null) {
                callback.done(false, "Cannot sync if there is no active account.");
            } else {
                new SyncHelper(contexts[0]).performSync(new SyncResult(),
                  AccountUtils.getActiveAccount(context), bundle);
            }
          return null;
        }
    }.execute(context);
}
 
Example 30
Project: AppDevFestSudeste2015   File: ForceSyncNowAction.java   Source Code and License 6 votes vote down vote up
@Override
public void run(final Context context, final Callback callback) {
    final Bundle bundle = new Bundle();
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    new AsyncTask<Context, Void, Void>() {
        @Override
        protected Void doInBackground(Context... contexts) {
            Account account = AccountUtils.getActiveAccount(context);
            if (account == null) {
                callback.done(false, "Cannot sync if there is no active account.");
            } else {
                new SyncHelper(contexts[0]).performSync(new SyncResult(),
                  AccountUtils.getActiveAccount(context), bundle);
            }
          return null;
        }
    }.execute(context);
}
 
Example 31
Project: JJCamera   File: ForceSyncNowAction.java   Source Code and License 6 votes vote down vote up
@Override
public void run(final Context context, final Callback callback) {
    ConferenceDataHandler.resetDataTimestamp(context);
    final Bundle bundle = new Bundle();
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    new AsyncTask<Context, Void, Void>() {
        @Override
        protected Void doInBackground(Context... contexts) {
            Account account = AccountUtils.getActiveAccount(context);
            if (account == null) {
                callback.done(false, "Cannot sync if there is no active account.");
            } else {
                new SyncHelper(contexts[0]).performSync(new SyncResult(),
                  AccountUtils.getActiveAccount(context), bundle);
            }
          return null;
        }
    }.execute(context);
}
 
Example 32
Project: attendee-checkin   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
                          ContentProviderClient provider, SyncResult syncResult) {
    String authToken = extras.getString(EXTRA_AUTH_TOKEN);
    if (TextUtils.isEmpty(authToken)) {
        Log.d(TAG, "Not authorized. Cannot sync.");
        return;
    }
    mApiClient.blockingConnect(5, TimeUnit.SECONDS);
    try {
        String cookie = getCookie(authToken);
        syncCheckins(provider, cookie);
        if (!extras.getBoolean(EXTRA_ONLY_CHECKINS, false)) {
            syncEvents(provider, cookie);
        }
    } catch (IOException e) {
        Log.e(TAG, "Error performing sync.", e);
    }
}
 
Example 33
Project: hr   File: OSyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
                          ContentProviderClient provider, SyncResult syncResult) {
    // Creating model Object
    mModel = new OModel(mContext, null, OdooAccountManager.getDetails(mContext, account.name))
            .createInstance(mModelClass);
    mUser = mModel.getUser();
    if (OdooAccountManager.isValidUserObj(mContext, mUser)) {
        // Creating Odoo instance
        mOdoo = createOdooInstance(mContext, mUser);
        Log.i(TAG, "User        : " + mModel.getUser().getAndroidName());
        Log.i(TAG, "Model       : " + mModel.getModelName());
        Log.i(TAG, "Database    : " + mModel.getDatabaseName());
        Log.i(TAG, "Odoo Version: " + mUser.getOdooVersion().getServerSerie());
        // Calling service callback
        if (mService != null)
            mService.performDataSync(this, extras, mUser);

        //Creating domain
        ODomain domain = (mDomain.containsKey(mModel.getModelName())) ?
                mDomain.get(mModel.getModelName()) : null;

        // Ready for sync data from server
        syncData(mModel, mUser, domain, syncResult, true, true);
    }
}
 
Example 34
Project: Popeens-DSub   File: SubsonicSyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
	String invalidMessage = isNetworkValid();
	if(invalidMessage != null) {
		Log.w(TAG, "Not running sync: " + invalidMessage);
		return;
	}

	// Make sure battery > x% or is charging
	IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
	Intent batteryStatus = context.registerReceiver(null, intentFilter);
	int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
	if (status != BatteryManager.BATTERY_STATUS_CHARGING && status != BatteryManager.BATTERY_STATUS_FULL) {
		int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
		int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

		if ((level / (float) scale) < 0.15) {
			Log.w(TAG, "Not running sync, battery too low");
			return;
		}
	}

	executeSync(context);
}
 
Example 35
Project: MarketAndroid   File: MasterListSyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(
        Account account,
        Bundle extras,
        String authority,
        ContentProviderClient provider,
        SyncResult syncResult) {


   /* Ln.v("Refreshing Data Stream");
    m_accountUtils.refreshAuthToken(new AccountUtils.TokenRefreshListener() {
        @Override
        public void onTokenRefreshed() {
            Ln.v("Synchronizing with Server");
            m_smartListService.synchronizeSmartLists();
        }
    });*/





}
 
Example 36
Project: iosched   File: ForceSyncNowAction.java   Source Code and License 6 votes vote down vote up
@Override
public void run(final Context context, final Callback callback) {
    ConferenceDataHandler.resetDataTimestamp(context);
    final Bundle bundle = new Bundle();
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    new AsyncTask<Context, Void, Void>() {
        @Override
        protected Void doInBackground(Context... contexts) {
            Account account = AccountUtils.getActiveAccount(context);
            if (account == null) {
                callback.done(false, "Cannot sync if there is no active account.");
            } else {
                new SyncHelper(contexts[0]).performSync(new SyncResult(), bundle);
            }
          return null;
        }
    }.execute(context);
}
 
Example 37
Project: androidclient   File: Syncer.java   Source Code and License 6 votes vote down vote up
private void commit(ContentProviderClient usersProvider, SyncResult syncResult) {
    // commit users table
    Uri uri = Users.CONTENT_URI.buildUpon()
        .appendQueryParameter(Users.RESYNC, "true")
        .appendQueryParameter(Users.COMMIT, "true")
        .build();
    try {
        usersProvider.update(uri, null, null, null);
        Log.d(TAG, "users database committed");
        Contact.invalidate();
    }
    catch (Exception e) {
        Log.e(TAG, "error committing users database - aborting sync", e);
        syncResult.databaseError = true;
    }
}
 
Example 38
Project: NewsReaders   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
                          ContentProviderClient provider, SyncResult syncResult) {
    Log.i(TAG, "Beginning network synchronization");
    Long datetime = PrefUtils.getLastSync(mContext);

    try {
        List<Entry> entryList = api.newsList(datetime);
        for (int i = 0; i < entryList.size(); i++) {
            insertEntry(entryList.get(i));
        }
        PrefUtils.setLastSync(mContext, new Date().getTime());
    } catch (RetrofitError retrofitError) {
        Log.e(TAG, "Error syncing", retrofitError);
    }
    EventBus.getDefault().post(new SyncEndedEvent());
    Log.i(TAG, "Network synchronization complete");
}
 
Example 39
Project: SyncManagerAndroid-DemoGoogleTasks   File: TaskSyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
		ContentProviderClient provider, SyncResult syncResult) {
	Log.d(TAG, "onPerformSync");
	try {
		TaskApi api = new GoogleTaskApi(getGoogleAuthToken());
		TaskDb db = new TaskDb(mContext);

		db.open();
		try {
			TaskSyncLocalDatastore localDatastore = new TaskSyncLocalDatastore(db); 
			TaskSyncRemoteDatastore remoteDatastore = new TaskSyncRemoteDatastore(api);
			SyncManager<Task, Task> syncManager = new SyncManager<Task, Task>(localDatastore, remoteDatastore);

			syncManager.sync();
			
		}	finally {
			db.close();
		}
		getContext().getContentResolver().notifyChange(TaskSyncContentProvider.CONTENT_URI, null);
		
	} catch (Exception e) {
		Log.e(TAG, "syncFailed:" + e.getMessage());
	}	
}
 
Example 40
Project: github-v2   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(final Account account, final Bundle extras,
        final String authority, final ContentProviderClient provider,
        final SyncResult syncResult) {
    accountScope.enterWith(account, AccountManager.get(getContext()));
    try {
        contextScope.enter(getContext());
        try {
            cancelCampaign();
            campaign = campaignFactory.create(syncResult);
            campaign.run();
        } finally {
            contextScope.exit(getContext());
        }
    } finally {
        accountScope.exit();
    }
}
 
Example 41
Project: devfestnorte-app   File: ForceSyncNowAction.java   Source Code and License 6 votes vote down vote up
@Override
public void run(final Context context, final Callback callback) {
    final Bundle bundle = new Bundle();
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    new AsyncTask<Context, Void, Void>() {
        @Override
        protected Void doInBackground(Context... contexts) {
            Account account = AccountUtils.getActiveAccount(context);
            if (account == null) {
                callback.done(false, "Cannot sync if there is no active account.");
            } else {
                new SyncHelper(contexts[0]).performSync(new SyncResult(),
                  AccountUtils.getActiveAccount(context), bundle);
            }
          return null;
        }
    }.execute(context);
}
 
Example 42
Project: devfestnorte-app   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
        final ContentProviderClient provider, final SyncResult syncResult) {
    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);
    final boolean userDataOnly = extras.getBoolean(EXTRA_SYNC_USER_DATA_ONLY, false);

    final String logSanitizedAccountName = sSanitizeAccountNamePattern
            .matcher(account.name).replaceAll("[email protected]");

    if (uploadOnly) {
        return;
    }

    LOGI(TAG, "Beginning sync for account " + logSanitizedAccountName + "," +
            " uploadOnly=" + uploadOnly +
            " manualSync=" + manualSync +
            " userDataOnly =" + userDataOnly +
            " initialize=" + initialize);

    // Sync from bootstrap and remote data, as needed
    new SyncHelper(mContext).performSync(syncResult, account, extras);
}
 
Example 43
Project: android_maplib   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
protected void sync(
        LayerGroup layerGroup,
        String authority,
        SyncResult syncResult)
{
    for (int i = 0; i < layerGroup.getLayerCount(); i++) {
        if (isCanceled()) {
            return;
        }
        ILayer layer = layerGroup.getLayer(i);
        if (layer instanceof LayerGroup) {
            sync((LayerGroup) layer, authority, syncResult);
        } else if (layer instanceof INGWLayer) {
            INGWLayer ngwLayer = (INGWLayer) layer;
            String accountName = ngwLayer.getAccountName();
            if (!mVersions.containsKey(accountName))
                mVersions.put(accountName, NGWUtil.getNgwVersion(getContext(), accountName));

            Pair<Integer, Integer> ver = mVersions.get(accountName);
            ngwLayer.sync(authority, ver, syncResult);
        }
    }
}
 
Example 44
Project: android_maplib   File: NGWVectorLayer.java   Source Code and License 6 votes vote down vote up
protected boolean proceedAttach(JSONObject result, SyncResult syncResult) throws JSONException {
    // get attach info
    if (!result.has("upload_meta")) {
        if (Constants.DEBUG_MODE) {
            Log.d(Constants.TAG, "Problem sendAttachOnServer(), result has not upload_meta, result: " + result.toString());
        }
        syncResult.stats.numParseExceptions++;
        return false;
    }

    JSONArray uploadMetaArray = result.getJSONArray("upload_meta");
    if (uploadMetaArray.length() == 0) {
        if (Constants.DEBUG_MODE) {
            Log.d(Constants.TAG, "Problem sendAttachOnServer(), result upload_meta length() == 0");
        }
        syncResult.stats.numParseExceptions++;
        return false;
    }

    return true;
}
 
Example 45
Project: android_maplib   File: NGWVectorLayer.java   Source Code and License 6 votes vote down vote up
protected void log(SyncResult syncResult, String code) {
    int responseCode = Integer.parseInt(code);
    switch (responseCode) {
        case HttpURLConnection.HTTP_UNAUTHORIZED:
        case HttpURLConnection.HTTP_FORBIDDEN:
            syncResult.stats.numAuthExceptions++;
            break;
        case 1:
            syncResult.stats.numParseExceptions++;
            break;
        case 0:
        default:
        case HttpURLConnection.HTTP_NOT_FOUND:
        case HttpURLConnection.HTTP_INTERNAL_ERROR:
            syncResult.stats.numIoExceptions++;
            break;
    }
}
 
Example 46
Project: android_maplib   File: VectorLayer.java   Source Code and License 6 votes vote down vote up
protected Void doInBackground(Void... params) {
    try {
        NGWVectorLayer layer = (NGWVectorLayer) MapDrawable.getInstance().getLayerByPathName(getPath().getName());
        FeatureChanges.initialize(layer.getChangeTableName());
        List<Long> ids = query(null);
        for (Long id : ids) {
            Feature feature = getFeatureWithAttaches(id);
            layer.addChange(feature.getId(), CHANGE_OPERATION_NEW);
            Map<String, AttachItem> attaches = feature.getAttachments();
            for (AttachItem attach : attaches.values())
                layer.addChange(feature.getId(), Long.parseLong(attach.getAttachId()), CHANGE_OPERATION_NEW);
        }

        Pair<Integer, Integer> ver = NGWUtil.getNgwVersion(mContext, layer.getAccountName());
        layer.sync(mAuthority, ver, new SyncResult());
    } catch (Exception ignored) { }

    return null;
}
 
Example 47
Project: Wardrobe_app   File: SyncService.java   Source Code and License 6 votes vote down vote up
/**
 * Download data from the server.
 */

private void downloadFromServer() {
    // Perform a sync using SyncHelper
    if (mSyncHelper == null) {
        mSyncHelper = new SyncHelper(this);
    }

    // Dummy SyncResult object, we can use this for detecting issues
    // at some point.
    SyncResult syncResult = new SyncResult();
    try {
        mSyncHelper.performSync(syncResult,
                SyncHelper.FLAG_SYNC_LOCAL | SyncHelper.FLAG_SYNC_REMOTE);

    } catch (IOException e) {
        ++syncResult.stats.numIoExceptions;
        LOGE(Config.LOG_TAG, "Error syncing data for Droidcon London 2013.", e);
    }
}
 
Example 48
Project: saarang-iosched   File: ForceSyncNowAction.java   Source Code and License 6 votes vote down vote up
@Override
public void run(final Context context, final Callback callback) {
    final Bundle bundle = new Bundle();
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    new AsyncTask<Context, Void, Void>() {
        @Override
        protected Void doInBackground(Context... contexts) {
            Account account = AccountUtils.getActiveAccount(context);
            if (account == null) {
                callback.done(false, "Cannot sync if there is no active account.");
            } else {
                new SyncHelper(contexts[0]).performSync(new SyncResult(),
                  AccountUtils.getActiveAccount(context), bundle);
            }
          return null;
        }
    }.execute(context);
}
 
Example 49
Project: TruckMuncher-Android   File: SyncTask.java   Source Code and License 6 votes vote down vote up
private void translateApiResultToSyncResult(ApiResult apiResult, SyncResult syncResult) {
    switch (apiResult) {
        case NEEDS_USER_INPUT:
            syncResult.tooManyRetries = true;
            break;
        case SHOULD_RETRY:
            syncResult.fullSyncRequested = true;
            break;
        case TEMPORARY_ERROR:
            syncResult.stats.numIoExceptions++;
            break;
        case PERMANENT_ERROR:
            syncResult.stats.numParseExceptions++;
            break;
        case OK:
            // No-op
            break;
        default:
            throw new IllegalStateException("Got an unhandled ApiResult type");
    }
}
 
Example 50
Project: AddressBook_eclipse   File: ContactsSyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult)
{
	Log.i(TAG, "onPerformSync");
	try
	{
		Session session = new Session();
		session.id = this.mAccountManager.blockingGetAuthToken(account, this.getContext().getPackageName(), true);
		AddressBookApiController controller = new AddressBookApiController(this.getContext());
		List<Contact> remoteContacts = controller.getContacts(session);
		//List<Contact> localContacts = new Select().from(Contact.class).execute();
		for (Contact contact : remoteContacts)
		{
			contact.save();
		}
	}
	catch (Exception ex)
	{
		Log.e(TAG, ex.toString());
	}
}
 
Example 51
Project: v2ex   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
        final ContentProviderClient provider, final SyncResult syncResult) {
    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);
    final boolean remoteSync = extras.getBoolean(EXTRA_SYNC_REMOTE, false);

    final String logSanitizedAccountName = sSanitizeAccountNamePattern
            .matcher(account.name).replaceAll("[email protected]");

    if (uploadOnly) {
        return;
    }

    LOGI(TAG, "Beginning sync for account " + logSanitizedAccountName + "," +
            " uploadOnly=" + uploadOnly +
            " manualSync=" + manualSync +
            " remoteSync =" + remoteSync +
            " initialize=" + initialize);
    // Sync from bootstrap and remote data, as needed
    new SyncHelper(mContext).performSync(syncResult, account, extras);
}
 
Example 52
Project: android-chromium   File: ChromiumSyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
                          ContentProviderClient provider, SyncResult syncResult) {
    if (!DelayedSyncController.getInstance().shouldPerformSync(getContext(), extras, account)) {
        return;
    }

    // Browser startup is asynchronous, so we will need to wait for startup to finish.
    Semaphore semaphore = new Semaphore(0);

    // Configure the callback with all the data it needs.
    BrowserStartupController.StartupCallback callback =
            getStartupCallback(mApplication, account, extras, syncResult, semaphore);
    startBrowserProcess(callback, syncResult, semaphore);

    try {
        // Wait for startup to complete.
        semaphore.acquire();
    } catch (InterruptedException e) {
        Log.w(TAG, "Got InterruptedException when trying to request a sync.", e);
        // Using numIoExceptions so Android will treat this as a soft error.
        syncResult.stats.numIoExceptions++;
    }
}
 
Example 53
Project: android-chromium   File: ChromiumSyncAdapter.java   Source Code and License 6 votes vote down vote up
private void startBrowserProcess(
        final BrowserStartupController.StartupCallback callback,
        final SyncResult syncResult, Semaphore semaphore) {
    try {
        ThreadUtils.runOnUiThreadBlocking(new Runnable() {
            @Override
            public void run() {
                initCommandLine();
                if (mAsyncStartup) {
                    BrowserStartupController.get(mApplication)
                            .startBrowserProcessesAsync(callback);
                } else {
                    startBrowserProcessesSync(callback);
                }
            }
        });
    } catch (RuntimeException e) {
        // It is still unknown why we ever experience this. See http://crbug.com/180044.
        Log.w(TAG, "Got exception when trying to request a sync. Informing Android system.", e);
        // Using numIoExceptions so Android will treat this as a soft error.
        syncResult.stats.numIoExceptions++;
        semaphore.release();
    }
}
 
Example 54
Project: COCOFramework   File: CocoSyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
                          ContentProviderClient provider, SyncResult syncResult) {

    // Building a print of the extras we got
    StringBuilder sb = new StringBuilder();
    if (extras != null) {
        for (String key : extras.keySet()) {
            sb.append(key + "[" + extras.get(key) + "] ");
        }
    }

    Log.d("> onPerformSync for account[" + account.name + "]. Extras: " + sb.toString());

    try {
        run(account, extras, authority,
                provider, syncResult);
    } catch (Throwable e) {
        e.printStackTrace();
    }
}
 
Example 55
Project: unicef_gis_mobile   File: SyncAdapter.java   Source Code and License 6 votes vote down vote up
private void handleException(String authtoken, Exception e,
		SyncResult syncResult) {
	if (e instanceof AuthenticatorException) {
		syncResult.stats.numParseExceptions++;
		Log.e("SyncAdapter", "AuthenticatorException", e);
	} else if (e instanceof OperationCanceledException) {
		Log.e("SyncAdapter", "OperationCanceledExcepion", e);
	} else if (e instanceof IOException) {
		Log.e("SyncAdapter", "IOException", e);
		syncResult.stats.numIoExceptions++;
	} else if (e instanceof AuthenticationException) {
		accountManager.invalidateAuthToken(Authenticator.ACCOUNT_TYPE, authtoken);
		syncResult.stats.numIoExceptions++;
		if (authtoken != null)
			Log.e("SyncAdapter", "Auth failed, invalidating token: " + authtoken);
		Log.e("SyncAdapter", "AuthenticationException", e);
	} else if (e instanceof ParseException) {
		syncResult.stats.numParseExceptions++;
		Log.e("SyncAdapter", "ParseException", e);
	} else if (e instanceof JsonParseException) {
		syncResult.stats.numParseExceptions++;
		Log.e("SyncAdapter", "JSONException", e);
	} else if (e instanceof ServerUrlPreferenceNotSetException) {
		Log.e("SyncAdapter", "ServerUrlPreferenceNotSetException", e);
	}
}
 
Example 56
Project: cordova-android-chromium   File: ChromiumSyncAdapter.java   Source Code and License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
                          ContentProviderClient provider, SyncResult syncResult) {
    if (!DelayedSyncController.getInstance().shouldPerformSync(getContext(), extras, account)) {
        return;
    }

    // Browser startup is asynchronous, so we will need to wait for startup to finish.
    Semaphore semaphore = new Semaphore(0);

    // Configure the callback with all the data it needs.
    BrowserStartupController.StartupCallback callback =
            getStartupCallback(mApplication, account, extras, syncResult, semaphore);
    startBrowserProcess(callback, syncResult, semaphore);

    try {
        // Wait for startup to complete.
        semaphore.acquire();
    } catch (InterruptedException e) {
        Log.w(TAG, "Got InterruptedException when trying to request a sync.", e);
        // Using numIoExceptions so Android will treat this as a soft error.
        syncResult.stats.numIoExceptions++;
    }
}
 
Example 57
Project: cordova-android-chromium   File: ChromiumSyncAdapter.java   Source Code and License 6 votes vote down vote up
private void startBrowserProcess(
        final BrowserStartupController.StartupCallback callback,
        final SyncResult syncResult, Semaphore semaphore) {
    try {
        ThreadUtils.runOnUiThreadBlocking(new Runnable() {
            @Override
            public void run() {
                initCommandLine();
                if (mAsyncStartup) {
                    BrowserStartupController.get(mApplication)
                            .startBrowserProcessesAsync(callback);
                } else {
                    startBrowserProcessesSync(callback);
                }
            }
        });
    } catch (RuntimeException e) {
        // It is still unknown why we ever experience this. See http://crbug.com/180044.
        Log.w(TAG, "Got exception when trying to request a sync. Informing Android system.", e);
        // Using numIoExceptions so Android will treat this as a soft error.
        syncResult.stats.numIoExceptions++;
        semaphore.release();
    }
}
 
Example 58
Project: FBEventSync   File: SyncContext.java   Source Code and License 5 votes vote down vote up
public SyncContext(Context context, Account account, String accessToken,
                   ContentProviderClient providerClient, SyncResult syncResult, Logger logger) {
    mContext = context;
    mAccount = account;
    mAccessToken = accessToken;
    mProviderClient = providerClient;
    mSyncResult = syncResult;
    mLogger = logger;
}
 
Example 59
Project: PeSanKita-android   File: ContactsSyncAdapter.java   Source Code and License 5 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
                          ContentProviderClient provider, SyncResult syncResult)
{
  Log.w(TAG, "onPerformSync(" + authority +")");

  if (TextSecurePreferences.isPushRegistered(getContext())) {
    try {
      DirectoryHelper.refreshDirectory(getContext(), KeyCachingService.getMasterSecret(getContext()));
    } catch (IOException e) {
      Log.w(TAG, e);
    }
  }
}
 
Example 60
Project: airgram   File: ContactsSyncAdapterService.java   Source Code and License 5 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
    try {
        ContactsSyncAdapterService.performSync(mContext, account, extras, authority, provider, syncResult);
    } catch (OperationCanceledException e) {
        FileLog.e("tmessages", e);
    }
}