List of usage examples for android.accounts AccountManager get
public static AccountManager get(Context context)
From source file:com.synox.android.ui.activity.FileActivity.java
/** * Invalidates the credentials stored for the current OC account and requests new credentials to the user, * navigating to {@link AuthenticatorActivity} * * @param context Android Context needed to access the {@link AccountManager}. Received as a parameter * to make the method accessible to {@link android.content.BroadcastReceiver}s. *//*from w ww .ja va2 s. c o m*/ protected void requestCredentialsUpdate(Context context) { try { /// step 1 - invalidate credentials of current account OwnCloudClient client; OwnCloudAccount ocAccount = new OwnCloudAccount(getAccount(), context); client = (OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(ocAccount)); if (client != null) { OwnCloudCredentials cred = client.getCredentials(); if (cred != null) { AccountManager am = AccountManager.get(context); if (cred.authTokenExpires()) { am.invalidateAuthToken(getAccount().type, cred.getAuthToken()); } else { am.clearPassword(getAccount()); } } } /// step 2 - request credentials to user Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class); updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount()); updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN); updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivity(updateAccountCredentials); } catch (com.synox.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) { Toast.makeText(context, R.string.auth_account_does_not_exist, Toast.LENGTH_SHORT).show(); } }
From source file:com.ntsync.android.sync.syncadapter.SyncAdapter.java
/** * Allows to show the Contact not synced message again * /*from w w w. j a v a 2 s .c om*/ * @param context * @param account */ private static void unhideMaxContactMessage(Context context, Account account) { AccountManager acm = AccountManager.get(context); acm.setUserData(account, NOTIF_SHOWN_CONTACTS_SYNCED, null); }
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;/*www . java2s.c om*/ 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())); } }
From source file:com.raceyourself.android.samsung.ProviderService.java
private void authorize() { UserDetail me = Helper.getUser();/*from www . jav a 2s.co m*/ if (me != null && me.getApiAccessToken() != null) return; AccountManager mAccountManager = AccountManager.get(this); List<Account> accounts = new ArrayList<Account>(); accounts.addAll(Arrays.asList(mAccountManager.getAccountsByType("com.google"))); accounts.addAll(Arrays.asList(mAccountManager.getAccountsByType("com.googlemail"))); String email = null; for (Account account : accounts) { if (account.name != null && account.name.contains("@")) { email = account.name; break; } } // Potential fault: Can there be multiple accounts? Do we need to sort or provide a selector? // hash email so we don't send user's identity to server // can't guarantee uniqueness but want very low probability of collisions // using SHA-256 means we'd expect a collision on approx. our 1-millionth user // TODO: make this more unique before Samsung sell 1m Gear IIs. MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(email.getBytes()); String hash = new String(messageDigest.digest()); hash = new String(Base64.encode(hash.getBytes(), Base64.DEFAULT)).replace("@", "_").replace("\n", "_"); //base64 encode and substitute @ symbols hash += "@hashed.raceyourself.com"; // make it look like an email so it passes server validation Helper.login(hash, SERVER_TOKEN); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "Implementation of SHA-256 algorithm not found. Authorisation failed. Exiting."); throw new RuntimeException(); } }
From source file:com.microsoft.windowsazure.mobileservices.MobileServiceClient.java
/** * Invokes Microsoft Azure Mobile Service authentication using a the Google * account registered in the device// w ww .j a v a 2s . co m * * @param activity The activity that triggered the authentication * @param account The account used for the login operation * @param scopes The scopes used as authentication token type for login */ public ListenableFuture<MobileServiceUser> loginWithGoogleAccount(Activity activity, Account account, String scopes) { final SettableFuture<MobileServiceUser> future = SettableFuture.create(); try { if (account == null) { throw new IllegalArgumentException("account"); } final MobileServiceClient client = this; AccountManagerCallback<Bundle> authCallback = new AccountManagerCallback<Bundle>() { @Override public void run(AccountManagerFuture<Bundle> futureBundle) { try { if (futureBundle.isCancelled()) { future.setException(new MobileServiceException("User cancelled")); // callback.onCompleted(null, new // MobileServiceException("User cancelled"), null); } else { Bundle bundle = futureBundle.getResult(); String token = (String) (bundle.get(AccountManager.KEY_AUTHTOKEN)); JsonObject json = new JsonObject(); json.addProperty("access_token", token); ListenableFuture<MobileServiceUser> loginFuture = client .login(MobileServiceAuthenticationProvider.Google, json); Futures.addCallback(loginFuture, new FutureCallback<MobileServiceUser>() { @Override public void onFailure(Throwable e) { future.setException(e); } @Override public void onSuccess(MobileServiceUser user) { future.set(user); } }); } } catch (Exception e) { future.setException(e); } } }; AccountManager acMgr = AccountManager.get(activity.getApplicationContext()); acMgr.getAuthToken(account, scopes, null, activity, authCallback, null); } catch (Exception e) { future.setException(e); } return future; }
From source file:com.phonegap.ContactAccessorSdk5.java
@Override /**//from w w w .j a v a 2 s. c o m * This method will save a contact object into the devices contacts database. * * @param contact the contact to be saved. * @returns true if the contact is successfully saved, false otherwise. */ public boolean save(JSONObject contact) { AccountManager mgr = AccountManager.get(mApp); Account[] accounts = mgr.getAccounts(); Account account = null; if (accounts.length == 1) account = accounts[0]; else if (accounts.length > 1) { for (Account a : accounts) { if (a.type.contains("eas") && a.name.matches(EMAIL_REGEXP)) /*Exchange ActiveSync*/ { account = a; break; } } if (account == null) { for (Account a : accounts) { if (a.type.contains("com.google") && a.name.matches(EMAIL_REGEXP)) /*Google sync provider*/ { account = a; break; } } } if (account == null) { for (Account a : accounts) { if (a.name.matches(EMAIL_REGEXP)) /*Last resort, just look for an email address...*/ { account = a; break; } } } } if (account == null) return false; String id = getJsonString(contact, "id"); // Create new contact if (id == null) { return createNewContact(contact, account); } // Modify existing contact else { return modifyContact(id, contact, account); } }
From source file:com.google.samples.apps.sergio.ui.BaseActivity.java
private void signInOrCreateAnAccount() { //Get list of accounts on device. AccountManager am = AccountManager.get(BaseActivity.this); Account[] accountArray = am.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE); if (accountArray.length == 0) { //Send the user to the "Add Account" page. Intent intent = new Intent(Settings.ACTION_ADD_ACCOUNT); intent.putExtra(Settings.EXTRA_ACCOUNT_TYPES, new String[] { "com.google" }); startActivity(intent);/*from w w w . jav a 2 s. co m*/ } else { //Try to log the user in with the first account on the device. startLoginProcess(); mDrawerLayout.closeDrawer(Gravity.START); } }
From source file:com.google.samples.apps.iosched.ui.BaseActivity.java
private void signInOrCreateAnAccount() { //Get list of accounts on device. AccountManager am = AccountManager.get(BaseActivity.this); Account[] accountArray = am.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE); if (accountArray.length == 0) { //Send the user to the "Add Account" page. Intent intent = new Intent(Settings.ACTION_ADD_ACCOUNT); intent.putExtra(Settings.EXTRA_ACCOUNT_TYPES, new String[] { GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE }); startActivity(intent);/*ww w . j a va 2 s .co m*/ } else { //Try to log the user in with the first account on the device. startLoginProcess(); mDrawerLayout.closeDrawer(GravityCompat.START); } }
From source file:com.karura.framework.plugins.utils.ContactAccessorSdk5.java
@Override /**/*w w w . ja v a2 s.c o m*/ * This method will save a contact object into the devices contacts database. * * @param contact the contact to be saved. * @returns the id if the contact is successfully saved, null otherwise. */ public String save(JSONObject contact) { AccountManager mgr = AccountManager.get(getContext()); Account[] accounts = mgr.getAccounts(); String accountName = null; String accountType = null; if (accounts.length == 1) { accountName = accounts[0].name; accountType = accounts[0].type; } else if (accounts.length > 1) { for (Account a : accounts) { if (a.type.contains("eas") && a.name.matches(EMAIL_REGEXP)) /* * Exchange ActiveSync */ { accountName = a.name; accountType = a.type; break; } } if (accountName == null) { for (Account a : accounts) { if (a.type.contains("com.google") && a.name.matches(EMAIL_REGEXP)) /* * Google sync provider */ { accountName = a.name; accountType = a.type; break; } } } if (accountName == null) { for (Account a : accounts) { if (a.name.matches(EMAIL_REGEXP)) /* * Last resort, just look for an email address... */ { accountName = a.name; accountType = a.type; break; } } } } String id = getJsonString(contact, "id"); // Create new contact if (id == null) { return createNewContact(contact, accountType, accountName); } // Modify existing contact else { return modifyContact(id, contact, accountType, accountName); } }
From source file:com.nononsenseapps.notepad.MainActivity.java
private void enableSync() { final Activity activity = this; // Get the first Google account on the device final Account[] accounts = AccountManager.get(activity).getAccountsByType("com.google"); if (accounts.length > 0) { final Account account = accounts[0]; // Request access AccountManager.get(activity).getAuthToken(account, SyncAdapter.AUTH_TOKEN_TYPE, null, activity, new AccountManagerCallback<Bundle>() { @Override/*from w ww.j ava2 s .c o m*/ public void run(AccountManagerFuture<Bundle> future) { // This is the callback class, it handles all the // steps // after requesting access try { String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN); if (token != null && !token.equals("") && account != null) { // Get preference editor Editor editor = PreferenceManager.getDefaultSharedPreferences(activity).edit(); // Write account name to prefs editor.putString(SyncPrefs.KEY_ACCOUNT, account.name); // Set it syncable ContentResolver.setIsSyncable(account, NotePad.AUTHORITY, 1); // Write to pref editor.putBoolean(SyncPrefs.KEY_SYNC_ENABLE, true); // Commit prefs editor.commit(); // Then request sync requestSync(account.name); } } catch (OperationCanceledException e) { Log.e("SyncFix", "Error1"); // if the request was canceled for any reason } catch (AuthenticatorException e) { Log.e("SyncFix", "Error2"); // if there was an error communicating with the // authenticator or // if the authenticator returned an invalid // response } catch (IOException e) { Log.e("SyncFix", "Error3"); // if the authenticator returned an error // response that // indicates that it encountered an IOException // while // communicating with the authentication server } } }, null); } }