Example usage for android.accounts AccountManager get

List of usage examples for android.accounts AccountManager get

Introduction

In this page you can find the example usage for android.accounts AccountManager get.

Prototype

public static AccountManager get(Context context) 

Source Link

Document

Gets an AccountManager instance associated with a Context.

Usage

From source file:dev.drsoran.moloko.sync.SyncAdapter.java

private String checkAccount(Account account) {
    final AccountManager accountManager = AccountManager.get(context);

    final String authToken;
    try {/*from  w ww  .  j  a va  2s  .  co  m*/
        authToken = accountManager.blockingGetAuthToken(account, Constants.AUTH_TOKEN_TYPE,
                true /* notifyAuthFailure */);
    } catch (OperationCanceledException e) {
        throw new SyncException(e);
    } catch (AuthenticatorException e) {
        ++syncResult.stats.numAuthExceptions;
        throw new SyncException(e);
    } catch (IOException e) {
        ++syncResult.stats.numIoExceptions;
        throw new SyncException(e);
    }

    return authToken;
}

From source file:com.cerema.cloud2.files.services.FileDownloader.java

/**
 * Service clean up//from w  w w .ja  v a  2 s .  com
 */
@Override
public void onDestroy() {
    Log_OC.v(TAG, "Destroying service");
    mBinder = null;
    mServiceHandler = null;
    mServiceLooper.quit();
    mServiceLooper = null;
    mNotificationManager = null;

    // remove AccountsUpdatedListener
    AccountManager am = AccountManager.get(getApplicationContext());
    am.removeOnAccountsUpdatedListener(this);

    super.onDestroy();
}

From source file:com.ntsync.android.sync.activities.AccountListFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REGISTRATION_CODE && resultCode == Activity.RESULT_OK) {
        // Create Account for new Registration
        String username = data.getStringExtra(RegisterActivity.PARAM_USERNAME);
        String password = data.getStringExtra(RegisterActivity.PARAM_PWD);
        Account account = new Account(username, Constants.ACCOUNT_TYPE);
        Context context = this.getActivity();
        AccountManager acm = AccountManager.get(context);
        SyncUtils.createAccount(context, account, acm, password);
    }/*  www  .  j av a  2s . c om*/
}

From source file:com.activiti.android.app.fragments.integration.alfresco.AlfrescoIntegrationFragment.java

public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    if (requestCode == 10 && resultCode == Activity.RESULT_OK) {
        String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
        Account[] accounts = AccountManager.get(getActivity())
                .getAccountsByType(AlfrescoIntegrator.ALFRESCO_ACCOUNT_TYPE);
        for (int i = 0; i < accounts.length; i++) {
            if (accountName.equals(accounts[i].name)) {
                selectedAccount = accounts[i];
                break;
            }//from  w  ww  .j  a  v  a 2s  .  co  m
        }
    }
}

From source file:cn.code.notes.gtask.remote.GTaskClient.java

private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
    String authToken;/*  w w  w.  j  a v  a2s  .  c o  m*/
    AccountManager accountManager = AccountManager.get(activity);
    Account[] accounts = accountManager.getAccountsByType("com.google");

    if (accounts.length == 0) {
        Log.e(TAG, "there is no available google account");
        return null;
    }

    String accountName = SystemEditActivity.getSyncAccountName(activity);
    Account account = null;
    for (Account a : accounts) {
        if (a.name.equals(accountName)) {
            account = a;
            break;
        }
    }
    if (account != null) {
        mAccount = account;
    } else {
        Log.e(TAG, "unable to get an account with the same name in the settings");
        return null;
    }

    // get the token now
    AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, "goanna_mobile",
            null, activity, null, null);
    try {
        Bundle authTokenBundle = accountManagerFuture.getResult();
        authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
        if (invalidateToken) {
            accountManager.invalidateAuthToken("com.google", authToken);
            loginGoogleAccount(activity, false);
        }
    } catch (Exception e) {
        Log.e(TAG, "get auth token failed");
        authToken = null;
    }

    return authToken;
}

From source file:com.example.jumpnote.android.jsonrpc.AuthenticatedJsonRpcJavaClient.java

public static void ensureHasTokenWithUI(Activity activity, Account account,
        final EnsureHasTokenWithUICallback callback) {
    AccountManager am = AccountManager.get(activity);
    am.getAuthToken(account, APPENGINE_SERVICE_NAME, null, activity, new AccountManagerCallback<Bundle>() {
        public void run(AccountManagerFuture<Bundle> authBundleFuture) {
            Bundle authBundle = null;/*from   w  w  w . j av a 2s  . co  m*/
            try {
                authBundle = authBundleFuture.getResult();
            } catch (OperationCanceledException e) {
                callback.onAuthDenied();
                return;
            } catch (AuthenticatorException e) {
                callback.onError(e);
                return;
            } catch (IOException e) {
                callback.onError(e);
                return;
            }

            if (authBundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                callback.onHasToken((String) authBundle.get(AccountManager.KEY_AUTHTOKEN));
            } else {
                callback.onError(
                        new IllegalStateException("No auth token available, but operation not canceled."));
            }
        }
    }, null);
}

From source file:com.sharpcart.android.wizardpager.SharpCartLoginActivity.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_wizard);

    mContext = this;
    mAccountManager = AccountManager.get(this);

    //init progress dialog
    pd = new ProgressDialog(this);

    if (savedInstanceState != null) {
        mWizardModel.load(savedInstanceState.getBundle("model"));
    }//from  w  w w .ja  v  a2s . c om

    mWizardModel.registerListener(this);

    mPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
    mPager = (ViewPager) findViewById(R.id.pager);
    mPager.setAdapter(mPagerAdapter);
    mStepPagerStrip = (StepPagerStrip) findViewById(R.id.strip);
    mStepPagerStrip.setOnPageSelectedListener(new StepPagerStrip.OnPageSelectedListener() {
        @Override
        public void onPageStripSelected(int position) {
            position = Math.min(mPagerAdapter.getCount() - 1, position);
            if (mPager.getCurrentItem() != position) {
                mPager.setCurrentItem(position);
            }
        }
    });

    mNextButton = (Button) findViewById(R.id.next_button);
    mPrevButton = (Button) findViewById(R.id.prev_button);

    mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(final int position) {
            mStepPagerStrip.setCurrentPage(position);

            if (mConsumePageSelectedEvent) {
                mConsumePageSelectedEvent = false;
                return;
            }

            mEditingAfterReview = false;
            updateBottomBar();
        }
    });

    mNextButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(final View view) {

            //Check Internet connection
            if (!hasInternetConnection) {
                Toast.makeText(mContext, "No Internet Connection", Toast.LENGTH_SHORT).show();

                //Check Internet connection. if there is none we wont be able to register the user
                checkInternetConnection = new CheckInternetConnection();
                checkInternetConnection.execute();
            }

            //Check to see if user already exists on servers
            if (mPager.getCurrentItem() == 0) {
                final ArrayList<ReviewItem> reviewItems = new ArrayList<ReviewItem>();
                for (final Page page : mWizardModel.getCurrentPageSequence()) {
                    page.getReviewItems(reviewItems);
                }

                checkIfRegistered(reviewItems.get(0).getDisplayValue(), reviewItems.get(1).getDisplayValue());
            }

            //If we have reached the last page
            if (mPager.getCurrentItem() == mCurrentPageSequence.size()) {

                //if we still dont have an Internet connection we cant move on
                if (!hasInternetConnection) {
                    new NoInternetConnectionDialog().show(getSupportFragmentManager(), "");

                } else {
                    /*
                     * Login/Create new account
                     * 1. Save relevant information to UserProfile object
                     * 2. Update SharedPreferences
                     * 3. Create Authenticator account
                     * 4. Update server
                     */

                    final ContentValues cv = new ContentValues();

                    //Reset all items active to 1
                    cv.put(SharpCartContentProvider.COLUMN_ACTIVE, "1");

                    getContentResolver().update(SharpCartContentProvider.CONTENT_URI_SHOPPING_ITEMS, cv, null,
                            null);

                    final ArrayList<ReviewItem> reviewItems = new ArrayList<ReviewItem>();
                    for (final Page page : mWizardModel.getCurrentPageSequence()) {
                        page.getReviewItems(reviewItems);
                    }

                    Collections.sort(reviewItems, new Comparator<ReviewItem>() {
                        @Override
                        public int compare(final ReviewItem a, final ReviewItem b) {
                            return a.getWeight() > b.getWeight() ? +1 : a.getWeight() < b.getWeight() ? -1 : 0;
                        }
                    });

                    mCurrentReviewItems = reviewItems;

                    //Save relevant information to UserProfile object
                    UserProfile.getInstance().setUserName(mCurrentReviewItems.get(0).getDisplayValue());
                    UserProfile.getInstance().setPassword(mCurrentReviewItems.get(1).getDisplayValue());
                    UserProfile.getInstance().setZip(mCurrentReviewItems.get(2).getDisplayValue());
                    UserProfile.getInstance().setFamilySize(mCurrentReviewItems.get(3).getDisplayValue());

                    //update shared preferences
                    //update settings
                    final SharedPreferences sharedPref = PreferenceManager
                            .getDefaultSharedPreferences(mContext);
                    sharedPref.edit().putString("pref_zip", UserProfile.getInstance().getZip()).commit();
                    sharedPref.edit().putString("pref_family_size",
                            String.valueOf(UserProfile.getInstance().getFamilySize())).commit();

                    sharedPref.edit().putLong("user_profile_last_updated", new Date().getTime()).commit();

                    //Present user with a dialog to choose up to 4 local stores based on their ZIP code
                    final Intent i = new Intent(view.getContext(), ChooseGroceryStoreMapFragment.class);
                    startActivityForResult(i, SELECT_STORES);

                }
            } else {
                if (mEditingAfterReview) {
                    mPager.setCurrentItem(mPagerAdapter.getCount() - 1);
                } else {
                    mPager.setCurrentItem(mPager.getCurrentItem() + 1);
                }
            }
        }
    });

    mPrevButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            mPager.setCurrentItem(mPager.getCurrentItem() - 1);
        }
    });

    onPageTreeChanged();
    updateBottomBar();

    //Check Internet connection. if there is none we wont be able to register the user
    checkInternetConnection = new CheckInternetConnection();
    checkInternetConnection.execute();
}

From source file:com.example.simba.myapplicationnote.gtask.remote.GTaskClient.java

private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
    String authToken;//  w  ww  .jav a2s.  c  o  m
    AccountManager accountManager = AccountManager.get(activity);
    Account[] accounts = accountManager.getAccountsByType("com.google");

    if (accounts.length == 0) {
        Log.e(TAG, "there is no available google account");
        return null;
    }

    String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
    Account account = null;
    for (Account a : accounts) {
        if (a.name.equals(accountName)) {
            account = a;
            break;
        }
    }
    if (account != null) {
        mAccount = account;
    } else {
        Log.e(TAG, "unable to get an account with the same name in the settings");
        return null;
    }

    // get the token now
    AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, "goanna_mobile",
            null, activity, null, null);
    try {
        Bundle authTokenBundle = accountManagerFuture.getResult();
        authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
        if (invalidateToken) {
            accountManager.invalidateAuthToken("com.google", authToken);
            loginGoogleAccount(activity, false);
        }
    } catch (Exception e) {
        Log.e(TAG, "get auth token failed");
        authToken = null;
    }

    return authToken;
}

From source file:org.klnusbaum.udj.EventListFragment.java

public void onActivityCreated(Bundle icicle) {
    super.onActivityCreated(icicle);
    am = AccountManager.get(getActivity());
    Account[] udjAccounts = am.getAccountsByType(Constants.ACCOUNT_TYPE);
    Log.d(TAG, "Accounts length was " + udjAccounts.length);
    if (udjAccounts.length < 1) {
        Intent getAccountIntent = new Intent(getActivity(), AuthActivity.class);
        startActivityForResult(getAccountIntent, ACCOUNT_CREATION);
        return;/*  w  w w. java  2 s.  co m*/
    } else if (udjAccounts.length == 1) {
        account = udjAccounts[0];
    } else {
        account = udjAccounts[0];
        //TODO implement if there are more than 1 account
    }
    if (icicle != null) {
        if (icicle.containsKey(LOCATION_STATE_EXTRA)) {
            lastKnown = (Location) icicle.getParcelable(LOCATION_STATE_EXTRA);
        }
        if (icicle.containsKey(LAST_SEARCH_TYPE_EXTRA)) {
            restoreLastSearch(icicle);
        }
    }
    setEmptyText(getActivity().getString(R.string.no_event_items));
    eventAdapter = new EventListAdapter(getActivity());
    setListAdapter(eventAdapter);
    setListShown(false);
}

From source file:ir.keloud.android.lib.common.accounts.AccountUtils.java

/**
 * /*from  w w w .  j  av a  2  s  . c  o m*/
 * @return
 * @throws IOException 
 * @throws AuthenticatorException 
 * @throws OperationCanceledException 
 */
public static KeloudCredentials getCredentialsForAccount(Context context, Account account)
        throws OperationCanceledException, AuthenticatorException, IOException {

    KeloudCredentials credentials = null;
    AccountManager am = AccountManager.get(context);

    boolean isOauth2 = am.getUserData(account, AccountUtils.Constants.KEY_SUPPORTS_OAUTH2) != null;

    boolean isSamlSso = am.getUserData(account, AccountUtils.Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null;

    if (isOauth2) {
        String accessToken = am.blockingGetAuthToken(account,
                AccountTypeUtils.getAuthTokenTypeAccessToken(account.type), false);

        credentials = KeloudCredentialsFactory.newBearerCredentials(accessToken);

    } else if (isSamlSso) {
        String accessToken = am.blockingGetAuthToken(account,
                AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(account.type), false);

        credentials = KeloudCredentialsFactory.newSamlSsoCredentials(accessToken);

    } else {
        String username = account.name.substring(0, account.name.lastIndexOf('@'));
        String password = am.blockingGetAuthToken(account, AccountTypeUtils.getAuthTokenTypePass(account.type),
                false);

        credentials = KeloudCredentialsFactory.newBasicCredentials(username, password);
    }

    return credentials;

}