List of usage examples for android.accounts Account Account
public Account(@NonNull Account other, @NonNull String accessId)
From source file:com.upenn.chriswang1990.sunshine.sync.SunshineSyncAdapter.java
/** * Helper method to get the fake account to be used with SyncAdapter, or make a new one * if the fake account doesn't exist yet. If we make a new account, we call the * onAccountCreated method so we can initialize things. * * @param context The context used to access the account service * @return a fake account./*ww w . j a v a 2 s . com*/ */ public static Account getSyncAccount(Context context) { // Get an instance of the Android account manager AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); // Create the account type and default account Account newAccount = new Account(context.getString(R.string.app_name), context.getString(R.string.sync_account_type)); // If the password doesn't exist, the account doesn't exist if (null == accountManager.getPassword(newAccount)) { /* * Add the account and account type, no password or user data * If successful, return the Account object, otherwise report an error. */ if (!accountManager.addAccountExplicitly(newAccount, "", null)) { return null; } /* * If you don't set android:syncable="true" in * in your <provider> element in the manifest, * then call ContentResolver.setIsSyncable(account, AUTHORITY, 1) * here. */ onAccountCreated(newAccount, context); } return newAccount; }
From source file:org.ohmage.auth.AuthenticatorActivityTest.java
public void testAuthTokenReceived_validAccessToken_createsOhmageAccount() throws Throwable { final AccessToken fakeAccessToken = new AccessToken("token", "refresh", "user"); setPlusClientFragmentSuccessfullyConnects(); when(fakeAuthHelper.googleAuthGetToken(fakeGoogleEmail)).thenReturn(fakeGoogleToken); // For some reason the argument captor messes up the next test so I'm doing this doAnswer(new Answer() { @Override/* w w w. j a v a 2 s. c o m*/ public Object answer(InvocationOnMock invocation) throws Throwable { ((CancelableCallback) invocation.getArguments()[2]).success(fakeAccessToken, null); return null; } }).when(fakeOhmageService).getAccessToken(eq(AuthUtil.GrantType.GOOGLE_OAUTH2), eq(fakeGoogleToken), any(CancelableCallback.class)); onView(withId(R.id.sign_in_google_button)).perform(click()); Account account = new Account(fakeGoogleEmail, AuthUtil.ACCOUNT_TYPE); verify(fakeAccountManager).addAccountExplicitly(account, "refresh", null); verify(fakeAccountManager).setAuthToken(account, AuthUtil.AUTHTOKEN_TYPE, "token"); }
From source file:org.ohmage.auth.AuthenticatorActivity.java
private Account addOrFindAccount(String email, String password) { Account[] accounts = am.getAccountsByType(AuthUtil.ACCOUNT_TYPE); Account account = accounts.length != 0 ? accounts[0] : new Account(email, AuthUtil.ACCOUNT_TYPE); if (accounts.length == 0) { am.addAccountExplicitly(account, password, null); // Turn on automatic syncing for this account ContentResolver.setSyncAutomatically(account, OhmageContract.CONTENT_AUTHORITY, true); ContentResolver.addPeriodicSync(account, StreamContract.CONTENT_AUTHORITY, new Bundle(), AuthUtil.SYNC_INTERVAL); ContentResolver.setSyncAutomatically(account, StreamContract.CONTENT_AUTHORITY, true); ContentResolver.addPeriodicSync(account, StreamContract.CONTENT_AUTHORITY, new Bundle(), AuthUtil.SYNC_INTERVAL); ContentResolver.setSyncAutomatically(account, ResponseContract.CONTENT_AUTHORITY, true); ContentResolver.addPeriodicSync(account, ResponseContract.CONTENT_AUTHORITY, new Bundle(), AuthUtil.SYNC_INTERVAL); ContentResolver.setSyncAutomatically(account, AppLogSyncAdapter.CONTENT_AUTHORITY, true); ContentResolver.addPeriodicSync(account, AppLogSyncAdapter.CONTENT_AUTHORITY, new Bundle(), AuthUtil.SYNC_INTERVAL); } else {/*from ww w. j av a 2s.c o m*/ am.setPassword(accounts[0], password); } return account; }
From source file:com.android.contacts.list.DefaultContactBrowseListFragment.java
private void turnSyncOn() { final ContactListFilter filter = getFilter(); if (filter.filterType == ContactListFilter.FILTER_TYPE_ACCOUNT && mReasonSyncOff == SyncUtil.SYNC_SETTING_ACCOUNT_SYNC_OFF) { ContentResolver.setSyncAutomatically(new Account(filter.accountName, filter.accountType), ContactsContract.AUTHORITY, true); mAlertContainer.setVisibility(View.GONE); } else {//from w w w . j a v a 2 s . co m final EnableGlobalSyncDialogFragment dialog = new EnableGlobalSyncDialogFragment(); dialog.show(this, filter); } }
From source file:com.android.contacts.list.DefaultContactBrowseListFragment.java
@Override public void onEnableAutoSync(ContactListFilter filter) { // Turn on auto-sync ContentResolver.setMasterSyncAutomatically(true); // This should be OK (won't block) because this only happens after a user action final List<AccountInfo> accountInfos = Futures.getUnchecked(mWritableAccountsFuture); // Also enable Contacts sync final List<AccountWithDataSet> accounts = AccountInfo.extractAccounts(accountInfos); final List<Account> syncableAccounts = filter.getSyncableAccounts(accounts); if (syncableAccounts != null && syncableAccounts.size() > 0) { for (Account account : syncableAccounts) { ContentResolver.setSyncAutomatically(new Account(account.name, account.type), ContactsContract.AUTHORITY, true); }/* www . j a v a2s . c o m*/ } mAlertContainer.setVisibility(View.GONE); }
From source file:mobisocial.musubi.ui.fragments.AccountLinkDialog.java
/** * Returns a current token for the given Google account, or * null if a token isn't available without user interaction. *//*w w w . j a v a2 s .c om*/ public static String silentBlockForGoogleToken(Context context, String accountName) throws IOException { Account account = new Account(accountName, ACCOUNT_TYPE_GOOGLE); AccountManager accountManager = AccountManager.get(context); // Need to get cached token, invalidate it, then get the token again String token = blockForCachedGoogleToken(context, account, accountManager); if (token != null) { accountManager.invalidateAuthToken(ACCOUNT_TYPE_GOOGLE, token); } token = blockForCachedGoogleToken(context, account, accountManager); return token; }
From source file:mobisocial.musubi.ui.fragments.AccountLinkDialog.java
private AccountManagerFuture<Bundle> tryGoogleAccount(Context context, String accountName) { if (accountName == null) { Log.e(TAG, "No selected Google account."); return null; }// w w w . j a v a 2 s . c o m Account account = new Account(accountName, ACCOUNT_TYPE_GOOGLE); AccountManager accountManager = AccountManager.get(context); return accountManager.getAuthToken(account, GOOGLE_OAUTH_SCOPE, true, new GoogleAccountManagerCallback(account), null); }
From source file:com.android.contacts.list.DefaultContactBrowseListFragment.java
private void setSyncOffAlert() { final ContactListFilter filter = getFilter(); final Account account = filter.filterType == ContactListFilter.FILTER_TYPE_ACCOUNT && filter.isGoogleAccountType() ? new Account(filter.accountName, filter.accountType) : null; if (account == null && !filter.isContactsFilterType()) { mAlertContainer.setVisibility(View.GONE); } else {// w ww .j a v a2 s . c o m mReasonSyncOff = SyncUtil.calculateReasonSyncOff(getContext(), account); final boolean isAlertVisible = SyncUtil.isAlertVisible(getContext(), account, mReasonSyncOff); setSyncOffMsg(mReasonSyncOff); mAlertContainer.setVisibility(isAlertVisible ? View.VISIBLE : View.GONE); } }
From source file:com.ntsync.android.sync.client.NetworkUtilities.java
private static String retryAuthentification(int retryCount, AccountManager accountManager, String authtoken, String accountName, HttpResponse response) throws AuthenticationException, OperationCanceledException, NetworkErrorException, ServerException { accountManager.invalidateAuthToken(Constants.ACCOUNT_TYPE, authtoken); String newToken = null;// www . ja v a2s .c o m if (retryCount == 0) { newToken = blockingGetAuthToken(accountManager, new Account(accountName, Constants.ACCOUNT_TYPE), null); } if (newToken == null) { throw new AuthenticationException(response.getStatusLine().toString()); } return newToken; }
From source file:mobile.tiis.appv2.LoginActivity.java
/** * This method will take the url built to use the webservice * and will try to parse JSON from the webservice stream to get * the user and password if they are correct or not. In case correct, fills * the Android Account Manager.//from ww w .java2 s . c o m * * <p>This method will throw a Toast message when user and password * are not valid * */ protected void startWebService(final CharSequence loginURL, final String username, final String password) { client.setBasicAuth(username, password, true); //new handler in case of login error in the thread handler = new Handler(); Thread thread = new Thread(new Runnable() { public void run() { try { int balanceCounter = 0; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(loginURL.toString()); Utils.writeNetworkLogFileOnSD( Utils.returnDeviceIdAndTimestamp(getApplicationContext()) + loginURL.toString()); httpGet.setHeader("Authorization", "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP)); HttpResponse httpResponse = httpClient.execute(httpGet); InputStream inputStream = httpResponse.getEntity().getContent(); Log.d("", loginURL.toString()); ByteArrayInputStream bais = Utils.getMultiReadInputStream(inputStream); Utils.writeNetworkLogFileOnSD(Utils.returnDeviceIdAndTimestamp(getApplicationContext()) + Utils.getStringFromInputStreamAndLeaveStreamOpen(bais)); bais.reset(); JsonFactory factory = new JsonFactory(); JsonParser jsonParser = factory.createJsonParser(bais); JsonToken token = jsonParser.nextToken(); if (token == JsonToken.START_OBJECT) { balanceCounter++; boolean idNextToHfId = false; while (!(balanceCounter == 0)) { token = jsonParser.nextToken(); if (token == JsonToken.START_OBJECT) { balanceCounter++; } else if (token == JsonToken.END_OBJECT) { balanceCounter--; } else if (token == JsonToken.FIELD_NAME) { String object = jsonParser.getCurrentName(); switch (object) { case "HealthFacilityId": token = jsonParser.nextToken(); app.setLoggedInUserHealthFacilityId(jsonParser.getText()); Log.d("", "healthFacilityId is: " + jsonParser.getText()); idNextToHfId = true; break; case "Firstname": token = jsonParser.nextToken(); app.setLoggedInFirstname(jsonParser.getText()); Log.d("", "firstname is: " + jsonParser.getText()); break; case "Lastname": token = jsonParser.nextToken(); app.setLoggedInLastname(jsonParser.getText()); Log.d("", "lastname is: " + jsonParser.getText()); break; case "Username": token = jsonParser.nextToken(); app.setLoggedInUsername(jsonParser.getText()); Log.d("", "username is: " + jsonParser.getText()); break; case "Lastlogin": token = jsonParser.nextToken(); Log.d("", "lastlogin is: " + jsonParser.getText()); break; case "Id": if (idNextToHfId) { token = jsonParser.nextToken(); app.setLoggedInUserId(jsonParser.getText()); Log.d("", "Id is: " + jsonParser.getText()); } break; default: break; } } } Account account = new Account(username, ACCOUNT_TYPE); AccountManager accountManager = AccountManager.get(LoginActivity.this); // boolean accountCreated = accountManager.addAccountExplicitly(account, LoginActivity.this.password, null); boolean accountCreated = accountManager.addAccountExplicitly(account, password, null); Bundle extras = LoginActivity.this.getIntent().getExtras(); if (extras != null) { if (accountCreated) { //Pass the new account back to the account manager AccountAuthenticatorResponse response = extras .getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE); Bundle res = new Bundle(); res.putString(AccountManager.KEY_ACCOUNT_NAME, username); res.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE); res.putString(AccountManager.KEY_PASSWORD, password); response.onResult(res); } } SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("secondSyncNeeded", true); editor.commit(); ContentValues values = new ContentValues(); values.put(SQLHandler.SyncColumns.UPDATED, 1); values.put(SQLHandler.UserColumns.FIRSTNAME, app.getLOGGED_IN_FIRSTNAME()); values.put(SQLHandler.UserColumns.LASTNAME, app.getLOGGED_IN_LASTNAME()); values.put(SQLHandler.UserColumns.HEALTH_FACILITY_ID, app.getLOGGED_IN_USER_HF_ID()); values.put(SQLHandler.UserColumns.ID, app.getLOGGED_IN_USER_ID()); values.put(SQLHandler.UserColumns.USERNAME, app.getLOGGED_IN_USERNAME()); values.put(SQLHandler.UserColumns.PASSWORD, password); databaseHandler.addUser(values); Log.d(TAG, "initiating offline for " + username + " password = " + password); app.initializeOffline(username, password); Intent intent; if (prefs.getBoolean("synchronization_needed", true)) { Log.d("supportLog", "call the loggin second time before the account was found"); intent = new Intent(LoginActivity.this, LotSettingsActivity.class); } else { Log.d("supportLog", "call the loggin second time before the account was found"); intent = new Intent(LoginActivity.this, LotSettingsActivity.class); evaluateIfFirstLogin(app.getLOGGED_IN_USER_ID()); } app.setUsername(username); startActivity(intent); } //if login failed show error else { handler.post(new Runnable() { public void run() { progressDialog.show(); progressDialog.dismiss(); toastMessage("Login failed.\nPlease check your details!"); loginButton.setEnabled(true); } }); } } catch (Exception e) { handler.post(new Runnable() { public void run() { progressDialog.show(); progressDialog.dismiss(); toastMessage("Login failed Login failed.\n" + "Please check your details or your web connectivity"); loginButton.setEnabled(true); } }); e.printStackTrace(); } } }); thread.start(); }