List of usage examples for android.accounts AccountManager setUserData
public void setUserData(final Account account, final String key, final String value)
From source file:org.totschnig.myexpenses.sync.SyncAdapter.java
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {/* w w w. jav a 2 s. c o m*/ categoryToId = new HashMap<>(); payeeToId = new HashMap<>(); methodToId = new HashMap<>(); accountUuidToId = new HashMap<>(); String uuidFromExtras = extras.getString(KEY_UUID); Timber.i("onPerformSync " + extras.toString()); AccountManager accountManager = AccountManager.get(getContext()); Exceptional<SyncBackendProvider> backendProviderExceptional = SyncBackendProviderFactory.get(getContext(), account); SyncBackendProvider backend; try { backend = backendProviderExceptional.getOrThrow(); } catch (Throwable throwable) { syncResult.databaseError = true; AcraHelper.report(throwable instanceof Exception ? ((Exception) throwable) : new Exception(throwable)); GenericAccountService.deactivateSync(account); accountManager.setUserData(account, GenericAccountService.KEY_BROKEN, "1"); String content = String.format(Locale.ROOT, "The backend could not be instantiated.Reason: %s. Please try to delete and recreate it.", throwable.getMessage()); Intent manageIntent = new Intent(getContext(), ManageSyncBackends.class); NotificationBuilderWrapper builder = NotificationBuilderWrapper .defaultBigTextStyleBuilder(getContext(), "Synchronization backend deactivated", content) .setContentIntent(PendingIntent.getActivity(getContext(), 0, manageIntent, PendingIntent.FLAG_CANCEL_CURRENT)); Notification notification = builder.build(); notification.flags = Notification.FLAG_AUTO_CANCEL; ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification); return; } if (!backend.setUp()) { syncResult.stats.numIoExceptions++; syncResult.delayUntil = 300; return; } String autoBackupFileUri = extras.getString(KEY_UPLOAD_AUTO_BACKUP); if (autoBackupFileUri != null) { try { backend.storeBackup(Uri.parse(autoBackupFileUri)); } catch (IOException e) { String content = getContext().getString(R.string.auto_backup_cloud_failure, autoBackupFileUri, account.name) + " " + e.getMessage(); Notification notification = NotificationBuilderWrapper.defaultBigTextStyleBuilder(getContext(), getContext().getString(R.string.pref_auto_backup_title), content).build(); notification.flags = Notification.FLAG_AUTO_CANCEL; ((NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification); } return; } Cursor c; String[] selectionArgs; String selection = KEY_SYNC_ACCOUNT_NAME + " = ?"; if (uuidFromExtras != null) { selection += " AND " + KEY_UUID + " = ?"; selectionArgs = new String[] { account.name, uuidFromExtras }; } else { selectionArgs = new String[] { account.name }; } String[] projection = { KEY_ROWID }; try { c = provider.query(TransactionProvider.ACCOUNTS_URI, projection, selection + " AND " + KEY_SYNC_SEQUENCE_LOCAL + " = 0", selectionArgs, null); } catch (RemoteException e) { syncResult.databaseError = true; AcraHelper.report(e); return; } if (c == null) { syncResult.databaseError = true; AcraHelper.report("Cursor is null"); return; } if (c.moveToFirst()) { do { long accountId = c.getLong(0); try { provider.update(buildInitializationUri(accountId), new ContentValues(0), null, null); } catch (RemoteException e) { syncResult.databaseError = true; AcraHelper.report(e); return; } } while (c.moveToNext()); } try { c = provider.query(TransactionProvider.ACCOUNTS_URI, projection, selection, selectionArgs, null); } catch (RemoteException e) { syncResult.databaseError = true; AcraHelper.report(e); return; } if (c != null) { if (c.moveToFirst()) { do { long accountId = c.getLong(0); String lastLocalSyncKey = KEY_LAST_SYNCED_LOCAL(accountId); String lastRemoteSyncKey = KEY_LAST_SYNCED_REMOTE(accountId); long lastSyncedLocal = Long .parseLong(getUserDataWithDefault(accountManager, account, lastLocalSyncKey, "0")); long lastSyncedRemote = Long .parseLong(getUserDataWithDefault(accountManager, account, lastRemoteSyncKey, "0")); dbAccount.set(org.totschnig.myexpenses.model.Account.getInstanceFromDb(accountId)); Timber.i("now syncing " + dbAccount.get().label); if (uuidFromExtras != null && extras.getBoolean(KEY_RESET_REMOTE_ACCOUNT)) { if (!backend.resetAccountData(uuidFromExtras)) { syncResult.stats.numIoExceptions++; Timber.e("error resetting account data"); } continue; } if (!backend.withAccount(dbAccount.get())) { syncResult.stats.numIoExceptions++; Timber.e("error withAccount"); continue; } if (backend.lock()) { try { ChangeSet changeSetSince = backend.getChangeSetSince(lastSyncedRemote, getContext()); if (changeSetSince.isFailed()) { syncResult.stats.numIoExceptions++; Timber.e("error getting changeset"); continue; } List<TransactionChange> remoteChanges; lastSyncedRemote = changeSetSince.sequenceNumber; remoteChanges = changeSetSince.changes; List<TransactionChange> localChanges = new ArrayList<>(); long sequenceToTest = lastSyncedLocal + 1; while (true) { List<TransactionChange> nextChanges = getLocalChanges(provider, accountId, sequenceToTest); if (nextChanges.size() > 0) { localChanges.addAll( Stream.of(nextChanges).filter(change -> !change.isEmpty()).toList()); lastSyncedLocal = sequenceToTest; sequenceToTest++; } else { break; } } if (localChanges.size() == 0 && remoteChanges.size() == 0) { continue; } if (localChanges.size() > 0) { localChanges = collectSplits(localChanges); } Pair<List<TransactionChange>, List<TransactionChange>> mergeResult = mergeChangeSets( localChanges, remoteChanges); localChanges = mergeResult.first; remoteChanges = mergeResult.second; if (remoteChanges.size() > 0) { writeRemoteChangesToDb(provider, Stream.of(remoteChanges) .filter(change -> !(change.isCreate() && uuidExists(change.uuid()))) .toList(), accountId); accountManager.setUserData(account, lastRemoteSyncKey, String.valueOf(lastSyncedRemote)); } if (localChanges.size() > 0) { lastSyncedRemote = backend.writeChangeSet(localChanges, getContext()); if (lastSyncedRemote != ChangeSet.FAILED) { if (!BuildConfig.DEBUG) { // on debug build for auditing purposes, we keep changes in the table provider.delete(TransactionProvider.CHANGES_URI, KEY_ACCOUNTID + " = ? AND " + KEY_SYNC_SEQUENCE_LOCAL + " <= ?", new String[] { String.valueOf(accountId), String.valueOf(lastSyncedLocal) }); } accountManager.setUserData(account, lastLocalSyncKey, String.valueOf(lastSyncedLocal)); accountManager.setUserData(account, lastRemoteSyncKey, String.valueOf(lastSyncedRemote)); } } } catch (IOException e) { Timber.e(e, "Error while syncing "); syncResult.stats.numIoExceptions++; } catch (RemoteException | OperationApplicationException | SQLiteException e) { Timber.e(e, "Error while syncing "); syncResult.databaseError = true; AcraHelper.report(e); } finally { if (!backend.unlock()) { Timber.e("Unlocking backend failed"); syncResult.stats.numIoExceptions++; } } } else { //TODO syncResult.delayUntil = ??? syncResult.stats.numIoExceptions++; } } while (c.moveToNext()); } c.close(); } backend.tearDown(); }
From source file:com.sefford.beauthentic.activities.LoginActivity.java
void performLogin() { final AccountManager am = AccountManager.get(this); final Bundle data = new Bundle(); data.putString(AuthenticAuthenticator.EXTRA_PASSWORD, etPassword.getText().toString()); data.putInt(AuthenticAuthenticator.EXTRA_TYPE, AuthenticAuthenticator.Type.PASSWORD.ordinal()); final Account account = new Account(etUsername.getText().toString(), AuthenticAuthenticator.ACCOUNT_TYPE); am.getAuthToken(account, "", data, true, new AccountManagerCallback<Bundle>() { @Override//from w w w.ja v a2s . c om public void run(AccountManagerFuture<Bundle> future) { try { final Bundle result = future.getResult(); if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)) { Sessions.addAccount(am, account, etPassword.getText().toString(), Bundle.EMPTY); am.setAuthToken(account, AuthenticAuthenticator.AUTHTOKEN_TYPE, result.getString(AccountManager.KEY_AUTHTOKEN)); am.setUserData(account, AuthenticAuthenticator.EXTRA_TYPE, Integer.toString(AuthenticAuthenticator.Type.PASSWORD.ordinal())); notifyLoginToGCM(AuthenticAuthenticator.Type.PASSWORD.ordinal(), account.name, etPassword.getText().toString(), result.getString(AccountManager.KEY_AUTHTOKEN)); googleApi .saveCredential( new Credential.Builder(account.name) .setPassword(etPassword.getText().toString()).build(), new SmartlockCredentialCallback()); } else { Snackbar.make(vLoginForm, R.string.error_invalid_credentials, Snackbar.LENGTH_LONG).show(); } } catch (OperationCanceledException e) { Snackbar.make(vLoginForm, R.string.error_operation_cancelled, Snackbar.LENGTH_LONG).show(); } catch (IOException e) { Snackbar.make(vLoginForm, R.string.error_not_connected_to_internet, Snackbar.LENGTH_LONG) .show(); } catch (AuthenticatorException e) { Snackbar.make(vLoginForm, R.string.error_invalid_credentials, Snackbar.LENGTH_LONG).show(); } } }, null); }
From source file:edu.mit.mobile.android.locast.net.NetworkClient.java
protected synchronized void loadFromExistingAccount(Account account) { if (account == null) { throw new IllegalArgumentException("must specify account"); }// w ww . jav a 2s . c om String baseUrlString; final AccountManager am = AccountManager.get(mContext); baseUrlString = am.getUserData(account, AuthenticationService.USERDATA_LOCAST_API_URL); if (baseUrlString == null) { Log.w(TAG, "loading base URL from preferences instead of account metadata"); baseUrlString = getBaseUrlFromPreferences(mContext); // if it's null in the userdata, then it must be an account from before this feature // was added. // Store for later use. am.setUserData(account, AuthenticationService.USERDATA_LOCAST_API_URL, baseUrlString); } try { setBaseUrl(baseUrlString); setCredentialsFromAccount(account); } catch (final MalformedURLException e) { Log.e(TAG, e.getLocalizedMessage(), e); } }
From source file:com.ntsync.android.sync.syncadapter.SyncAdapter.java
private void notifyUserPhotoNotSynced(String accountName) { Account account = new Account(accountName, Constants.ACCOUNT_TYPE); AccountManager acm = AccountManager.get(mContext); String synced = acm.getUserData(account, NOTIF_SHOWN_PHOTO_SYNCED); if (synced == null) { Intent shopIntent = new Intent(mContext, ShopActivity.class); shopIntent.putExtra(ShopActivity.PARM_ACCOUNT_NAME, accountName); TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext); stackBuilder.addParentStack(ShopActivity.class); stackBuilder.addNextIntent(shopIntent); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext) .setSmallIcon(Constants.NOTIF_ICON) .setContentTitle(getText(R.string.notif_photonotsynced_title)).setContentText(accountName) .setAutoCancel(true)// ww w . j a va2s .co m .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)) .setOnlyAlertOnce(true); NotificationManager mNotificationManager = (NotificationManager) mContext .getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(Constants.NOTIF_PHOTO_NOT_SYNCED, mBuilder.build()); acm.setUserData(account, NOTIF_SHOWN_PHOTO_SYNCED, String.valueOf(System.currentTimeMillis())); } }
From source file:org.klnusbaum.udj.network.EventCommService.java
private void enterEvent(Intent intent, AccountManager am, Account account, boolean attemptReauth) { if (!Utils.isNetworkAvailable(this)) { doLoginFail(am, account, EventJoinError.NO_NETWORK_ERROR); return;/* w w w. ja va 2s . c o m*/ } long userId, eventId; String authToken; //TODO hanle error if account isn't provided try { userId = Long.valueOf(am.getUserData(account, Constants.USER_ID_DATA)); //TODO handle if event id isn't provided authToken = am.blockingGetAuthToken(account, "", true); eventId = intent.getLongExtra(Constants.EVENT_ID_EXTRA, Constants.NO_EVENT_ID); } catch (OperationCanceledException e) { Log.e(TAG, "Operation canceled exception in EventCommService"); doLoginFail(am, account, EventJoinError.AUTHENTICATION_ERROR); return; } catch (AuthenticatorException e) { Log.e(TAG, "Authenticator exception in EventCommService"); doLoginFail(am, account, EventJoinError.AUTHENTICATION_ERROR); return; } catch (IOException e) { Log.e(TAG, "IO exception in EventCommService"); doLoginFail(am, account, EventJoinError.AUTHENTICATION_ERROR); return; } try { ServerConnection.joinEvent(eventId, userId, authToken); setEventData(intent, am, account); ContentResolver cr = getContentResolver(); UDJEventProvider.eventCleanup(cr); HashMap<Long, Long> previousRequests = ServerConnection.getAddRequests(userId, eventId, authToken); UDJEventProvider.setPreviousAddRequests(cr, previousRequests); JSONObject previousVotes = ServerConnection.getVoteRequests(userId, eventId, authToken); UDJEventProvider.setPreviousVoteRequests(cr, previousVotes); Intent joinedEventIntent = new Intent(Constants.JOINED_EVENT_ACTION); am.setUserData(account, Constants.LAST_EVENT_ID_DATA, String.valueOf(eventId)); am.setUserData(account, Constants.EVENT_STATE_DATA, String.valueOf(Constants.IN_EVENT)); sendBroadcast(joinedEventIntent); } catch (IOException e) { Log.e(TAG, "IO exception when joining event"); Log.e(TAG, e.getMessage()); doLoginFail(am, account, EventJoinError.SERVER_ERROR); } catch (JSONException e) { Log.e(TAG, "JSON exception when joining event"); Log.e(TAG, e.getMessage()); doLoginFail(am, account, EventJoinError.SERVER_ERROR); } catch (AuthenticationException e) { handleLoginAuthException(intent, am, account, authToken, attemptReauth); } catch (EventOverException e) { Log.e(TAG, "Event Over Exception when joining event"); //Log.e(TAG, e.getMessage()); doLoginFail(am, account, EventJoinError.EVENT_OVER_ERROR); } catch (AlreadyInEventException e) { Log.e(TAG, "Already In Event Exception when joining event"); try { ServerConnection.leaveEvent(e.getEventId(), userId, authToken); enterEvent(intent, am, account, true); } catch (AuthenticationException f) { handleLoginAuthException(intent, am, account, authToken, attemptReauth); } catch (IOException f) { Log.e(TAG, "IO exception when attempting to leave one event before " + "joining another"); Log.e(TAG, f.getMessage()); doLoginFail(am, account, EventJoinError.SERVER_ERROR); } } }
From source file:com.ntsync.android.sync.syncadapter.SyncAdapter.java
private void notifyUserConctactNotSynced(int maxCount, int totalLocalContacts, String accountName) { AccountManager acm = AccountManager.get(mContext); Account account = new Account(accountName, Constants.ACCOUNT_TYPE); String lastTimeShown = acm.getUserData(account, NOTIF_SHOWN_CONTACTS_SYNCED); Long lastTime;// ww w . j a v a 2 s . c o m try { lastTime = lastTimeShown != null ? Long.parseLong(lastTimeShown) : null; } catch (NumberFormatException ex) { LogHelper.logWCause(TAG, "Invalid Config-Settings:" + NOTIF_SHOWN_CONTACTS_SYNCED + " Value:" + lastTimeShown, ex); lastTime = null; } if (lastTime == null || System.currentTimeMillis() > lastTime.longValue() + NOTIF_WAIT_TIME) { // Create Shop-Intent Intent shopIntent = new Intent(mContext, ShopActivity.class); shopIntent.putExtra(ShopActivity.PARM_ACCOUNT_NAME, account.name); // Adds the back stack TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext); stackBuilder.addParentStack(ShopActivity.class); stackBuilder.addNextIntent(shopIntent); // Create Notification NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext) .setSmallIcon(Constants.NOTIF_ICON) .setContentTitle(String.format(getText(R.string.notif_contactnotsynced_title), maxCount, totalLocalContacts)) .setContentText(String.format(getText(R.string.notif_contactnotsynced_content), account.name)) .setAutoCancel(true).setOnlyAlertOnce(true) .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)); NotificationManager mNotificationManager = (NotificationManager) mContext .getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(Constants.NOTIF_CONTACTS_NOT_SYNCED, mBuilder.build()); acm.setUserData(account, NOTIF_SHOWN_CONTACTS_SYNCED, String.valueOf(System.currentTimeMillis())); } }