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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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();
    }
}