Example usage for android.accounts AccountManager getAccountsByType

List of usage examples for android.accounts AccountManager getAccountsByType

Introduction

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

Prototype

@NonNull
public Account[] getAccountsByType(String type) 

Source Link

Document

Lists all accounts of particular type visible to the caller.

Usage

From source file:com.github.pockethub.android.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    userLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

    if (sp.getBoolean(PREF_FIRST_USE, true)) {
        openWelcomeScreen();//from  w ww .  ja  va2  s .c  o m
    }

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);

            if (!userLearnedDrawer) {
                SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
                sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
                userLearnedDrawer = true;
                Log.d(TAG, "User learned drawer");
            }
        }
    };
    drawerLayout.setDrawerListener(actionBarDrawerToggle);

    navigationView = (NavigationView) findViewById(R.id.navigation_view);

    navigationView.setNavigationItemSelectedListener(this);

    getSupportLoaderManager().initLoader(0, null, this);

    TokenStore tokenStore = TokenStore.getInstance(this);

    if (tokenStore.getToken() == null) {
        AccountManager manager = AccountManager.get(this);
        Account[] accounts = manager.getAccountsByType(getString(R.string.account_type));
        if (accounts.length > 0) {
            Account account = accounts[0];
            AccountsHelper.getUserToken(this, account);
            tokenStore.saveToken(AccountsHelper.getUserToken(this, account));
        }
    }
}

From source file:com.github.pockethub.android.ui.MainActivity.java

@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
    int itemId = menuItem.getItemId();

    if (itemId == R.id.navigation_home) {
        switchFragment(new HomePagerFragment(), org);
        getSupportActionBar().setTitle(getString(R.string.app_name));
        return true;
    } else if (itemId == R.id.navigation_gists) {
        switchFragment(new GistsPagerFragment(), null);
        getSupportActionBar().setTitle(menuItem.getTitle());
        return true;
    } else if (itemId == R.id.navigation_issue_dashboard) {
        switchFragment(new IssueDashboardPagerFragment(), null);
        getSupportActionBar().setTitle(menuItem.getTitle());
        return true;
    } else if (itemId == R.id.navigation_bookmarks) {
        switchFragment(new FilterListFragment(), null);
        getSupportActionBar().setTitle(menuItem.getTitle());
        return true;
    } else if (itemId == R.id.navigation_log_out) {
        AccountManager accountManager = getAccountManager();
        Account[] allGitHubAccounts = accountManager.getAccountsByType(getString(R.string.account_type));

        for (Account account : allGitHubAccounts) {
            accountManager.removeAccount(account, null, null);
        }/*from   w  ww. j  av  a2  s .  com*/

        Intent in = new Intent(this, LoginActivity.class);
        in.addFlags(IntentCompat.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(in);
        finish();
        return false;

    } else if (menuItemOrganizationMap.containsKey(menuItem)) {
        switchFragment(new HomePagerFragment(), menuItemOrganizationMap.get(menuItem));
        navigationView.getMenu().findItem(R.id.navigation_home).setChecked(true);
        return false;
    } else {
        throw new IllegalStateException("MenuItem " + menuItem + " not known");
    }
}

From source file:falcofinder.android.fuehrerschein.chat.AccountsActivity.java

/**
 * Registers for C2DM messaging with the given account name.
 * //from   w  ww.j av a 2 s .c o  m
 * @param accountName a String containing a Google account name
 */
private void register(final String accountName) {
    // Store the account name in shared preferences
    final SharedPreferences prefs = Util.getSharedPreferences(mContext);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(Util.ACCOUNT_NAME, accountName);
    editor.remove(Util.AUTH_COOKIE);
    editor.remove(Util.DEVICE_REGISTRATION_ID);
    editor.commit();

    // Obtain an auth token and register
    final AccountManager mgr = AccountManager.get(mContext);
    Account[] accts = mgr.getAccountsByType("com.google");
    for (Account acct : accts) {
        final Account account = acct;
        if (account.name.equals(accountName)) {
            if (Util.isDebug(mContext)) {
                // Use a fake cookie for the dev mode app engine server
                // The cookie has the form email:isAdmin:userId
                // We set the userId to be the same as the email
                String authCookie = "dev_appserver_login=" + accountName + ":false:" + accountName;
                prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit();

                //commento c2dm non usato
                //C2DMessaging.register(mContext, Setup.SENDER_ID);

            } else {
                // Get the auth token from the AccountManager and convert
                // it into a cookie for the appengine server
                final Activity activity = this;
                mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                    public void run(AccountManagerFuture<Bundle> future) {
                        String authToken = getAuthToken(future);
                        // Ensure the token is not expired by invalidating it and
                        // obtaining a new one
                        mgr.invalidateAuthToken(account.type, authToken);
                        mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                            public void run(AccountManagerFuture<Bundle> future) {
                                String authToken = getAuthToken(future);
                                // Convert the token into a cookie for future use
                                String authCookie = getAuthCookie(authToken);
                                Editor editor = prefs.edit();
                                editor.putString(Util.AUTH_COOKIE, authCookie);
                                editor.commit();
                                //commento c2dm non usato
                                // C2DMessaging.register(mContext, Setup.SENDER_ID);
                            }
                        }, null);
                    }
                }, null);
            }
            break;
        }
    }
}

From source file:com.nest5.businessClient.AccountsActivity.java

/**
 * Registers for C2DM messaging with the given account name.
 * //www. j  av a  2s  .c o  m
 * @param accountName a String containing a Google account name
 */
private void register(final String accountName) {
    // Store the account name in shared preferences
    final SharedPreferences prefs = Util.getSharedPreferences(mContext);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(Util.ACCOUNT_NAME, accountName);
    editor.remove(Util.AUTH_COOKIE);
    editor.remove(Util.DEVICE_REGISTRATION_ID);
    editor.commit();

    // Obtain an auth token and register
    final AccountManager mgr = AccountManager.get(mContext);
    Account[] accts = mgr.getAccountsByType("com.google");
    for (Account acct : accts) {
        final Account account = acct;
        if (account.name.equals(accountName)) {

            // Get the auth token from the AccountManager and convert
            // it into a cookie for the appengine server
            final Activity activity = this;
            mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                public void run(AccountManagerFuture<Bundle> future) {
                    String authToken = getAuthToken(future);
                    // Ensure the token is not expired by invalidating it and
                    // obtaining a new one
                    mgr.invalidateAuthToken(account.type, authToken);
                    mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                        public void run(AccountManagerFuture<Bundle> future) {
                            String authToken = getAuthToken(future);
                            // Convert the token into a cookie for future use
                            String authCookie = getAuthCookie(authToken);
                            Editor editor = prefs.edit();
                            editor.putString(Util.AUTH_COOKIE, authCookie);
                            editor.commit();
                            C2DMessaging.register(mContext, Setup.SENDER_ID);
                        }
                    }, null);
                }
            }, null);

            break;
        }
    }
}

From source file:org.pixmob.appengine.client.demo.DemoActivity.java

private void reset() {
    final AccountManager accountManager = AccountManager.get(this);
    final Account[] accounts = accountManager.getAccountsByType("com.google");
    if (accounts.length == 0) {
        accountAdapter = new AccountAdapter(this, new Account[0]);
        setListAdapter(accountAdapter);/*  w w w .j ava  2  s.c o m*/
        showDialog(NO_ACCOUNT_DIALOG);
    } else {
        Arrays.sort(accounts, AccountComparator.INSTANCE);
        accountAdapter = new AccountAdapter(this, accounts);
        setListAdapter(accountAdapter);
    }

    appspotBaseView.setText(appspotBase);
}

From source file:com.he5ed.lib.cloudprovider.auth.OAuth2Fragment.java

/**
 * Create a new user account or update the current user account
 *
 * @param user user information returned from server
 *///from  w ww  .  j a va2 s  .  c  o m
private void addAccount(User user) {
    boolean accountExist = false;
    AccountManager am = AccountManager.get(getActivity());
    // check if account already exist in AccountManager
    Account[] accounts = am.getAccountsByType(CloudProvider.ACCOUNT_TYPE);
    for (Account account : accounts) {
        if (account.name.equals(user.id)) {
            accountExist = true;
            break;
        }
    }

    Account account = new Account(user.id, CloudProvider.ACCOUNT_TYPE);
    Bundle userData = new Bundle(); // must be string value
    String accessToken = mTokenInfo.get(Authenticator.KEY_ACCESS_TOKEN);
    String refreshToken = mTokenInfo.get(Authenticator.KEY_REFRESH_TOKEN);
    String expiryDuration = mTokenInfo.get(Authenticator.KEY_EXPIRY);
    if (accountExist) {
        // update current account access token
        am.setAuthToken(account, CloudProvider.AUTH_TYPE, accessToken);
        if (refreshToken != null)
            am.setUserData(account, Authenticator.KEY_REFRESH_TOKEN, refreshToken);
        if (expiryDuration != null)
            am.setUserData(account, Authenticator.KEY_EXPIRY, expiryDuration);
    } else {
        // add new account into AccountManager
        if (refreshToken != null)
            userData.putString(Authenticator.KEY_REFRESH_TOKEN, refreshToken);
        if (expiryDuration != null)
            userData.putString(Authenticator.KEY_EXPIRY, expiryDuration);
        userData.putString(Authenticator.KEY_CLOUD_API, AuthHelper.getCloudApi(mCloudApi));
        userData.putString(Authenticator.KEY_USERNAME, user.name);
        userData.putString(Authenticator.KEY_EMAIL, user.email);
        userData.putString(Authenticator.KEY_AVATAR_URL, user.avatarUrl);

        am.addAccountExplicitly(account, null, userData);
        am.setAuthToken(account, CloudProvider.AUTH_TYPE, accessToken);
    }

    // send result back to AccountManager
    Bundle result = new Bundle();
    result.putString(AccountManager.KEY_ACCOUNT_NAME, user.id);
    result.putString(AccountManager.KEY_ACCOUNT_TYPE, CloudProvider.ACCOUNT_TYPE);
    ((AccountAuthenticatorActivity) getActivity()).setAccountAuthenticatorResult(result);

    getActivity().finish();
}

From source file:com.owncloud.android.ui.activity.ManageAccountsActivity.java

/**
 * Callback executed after the {@link AccountManager} removed an account
 *
 * @param future    Result of the removal; future.getResult() is true if account was removed correctly.
 *//*from  w  w  w  .  ja va2 s  .c o m*/
@Override
public void run(AccountManagerFuture<Boolean> future) {
    if (future != null && future.isDone()) {
        Account account = new Account(mAccountBeingRemoved, MainApp.getAccountType());
        if (!AccountUtils.exists(account.name, MainApp.getAppContext())) {
            // Cancel transfers of the removed account
            if (mUploaderBinder != null) {
                mUploaderBinder.cancel(account);
            }
            if (mDownloaderBinder != null) {
                mDownloaderBinder.cancel(account);
            }
        }

        mAccountListAdapter = new AccountListAdapter(this, getAccountListItems(), mTintedCheck);
        mListView.setAdapter(mAccountListAdapter);

        AccountManager am = AccountManager.get(this);
        if (am.getAccountsByType(MainApp.getAccountType()).length == 0) {
            // Show create account screen if there isn't any account
            am.addAccount(MainApp.getAccountType(), null, null, null, this, null, null);
        } else { // at least one account left
            if (AccountUtils.getCurrentOwnCloudAccount(this) == null) {
                // current account was removed - set another as current
                String accountName = "";
                Account[] accounts = AccountManager.get(this).getAccountsByType(MainApp.getAccountType());
                if (accounts.length != 0) {
                    accountName = accounts[0].name;
                }
                AccountUtils.setCurrentOwnCloudAccount(this, accountName);
            }
        }
    }
}

From source file:org.mozilla.gecko.overlays.service.sharemethods.SendTab.java

/**
 * Load the state of the user's Firefox Sync accounts and broadcast it to any registered
 * listeners. This will cause any UIs that may exist that depend on this information to update.
 *//*from www .  jav  a 2  s  . co m*/
public SendTab(Context aContext) {
    super(aContext);
    // Initialise the UI state intent...

    // Determine if the user has a new or old style sync account and load the available sync
    // clients for it.
    final AccountManager accountManager = AccountManager.get(context);
    final Account[] fxAccounts = accountManager.getAccountsByType(FxAccountConstants.ACCOUNT_TYPE);

    if (fxAccounts.length > 0) {
        final AndroidFxAccount fxAccount = new AndroidFxAccount(context, fxAccounts[0]);
        if (fxAccount.getState().getNeededAction() != State.Action.None) {
            // We have a Firefox Account, but it's definitely not able to send a tab
            // right now. Redirect to the status activity.
            Log.w(LOGTAG, "Firefox Account named like " + fxAccount.getObfuscatedEmail()
                    + " needs action before it can send a tab; redirecting to status activity.");

            setOverrideIntent(FxAccountStatusActivity.class);
            return;
        }

        tabSender = new FxAccountTabSender(fxAccount);

        updateClientList(tabSender);

        Log.i(LOGTAG, "Allowing tab send for Firefox Account.");
        registerDisplayURICommand();
        return;
    }

    final Account[] syncAccounts = accountManager.getAccountsByType(SyncConstants.ACCOUNTTYPE_SYNC);
    if (syncAccounts.length > 0) {
        tabSender = new Sync11TabSender(context, syncAccounts[0], accountManager);

        updateClientList(tabSender);

        Log.i(LOGTAG, "Allowing tab send for Sync account.");
        registerDisplayURICommand();
        return;
    }

    // Have registered UIs offer to set up a Firefox Account.
    setOverrideIntent(FxAccountGetStartedActivity.class);
}

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

public void onLoadFinished(Loader<List<AccountInfo>> loader, List<AccountInfo> data) {
    int bigestAccountIndex = -1;
    int currCount = -1;

    if (sourceAccountAdapter != null) {
        List<AccountInfo> myAccountsData = new ArrayList<AccountInfo>();
        List<AccountInfo> newListData = new ArrayList<AccountInfo>();
        int listPos = 0;
        for (AccountInfo info : data) {
            if (Constants.ACCOUNT_TYPE.equals(info.accountType)) {
                myAccountsData.add(info);
                continue;
            }/* www.  ja v a2 s . c o  m*/
            if (info.getContactCount() > currCount) {
                currCount = info.getContactCount();
                bigestAccountIndex = listPos;
            }

            newListData.add(info);
            listPos++;
        }
        // If more than one of our accounts is here allow importing to
        // the other
        if (!myAccountsData.isEmpty()) {
            AccountManager accountManager = AccountManager.get(ImportActivity.this);
            Account[] myAccounts = accountManager.getAccountsByType(Constants.ACCOUNT_TYPE);
            if (myAccounts.length > 1) {
                for (AccountInfo accountInfo : myAccountsData) {
                    if (accountInfo.getContactCount() > currCount) {
                        currCount = accountInfo.getContactCount();
                        bigestAccountIndex = listPos;
                    }
                    newListData.add(accountInfo);
                    listPos++;
                }
            }
        }

        boolean containsOldData = sourceAccountAdapter.getCount() > 0;
        sourceAccountAdapter.setData(newListData);

        if (bigestAccountIndex >= 0 && !containsOldData) {
            Spinner spinner = (Spinner) findViewById(R.id.sourceAccountSpinner);
            if (spinner != null) {
                spinner.setSelection(bigestAccountIndex);
            }
        }
        updateBtnState();
    }
}

From source file:com.pixplicity.castdemo.MainActivity.java

public String getUsername() {
    if (mUsername == null) {
        mUsername = "anonymous";
        // Default username
        AccountManager manager = AccountManager.get(this);
        Account[] accounts = manager.getAccountsByType("com.google");
        List<String> possibleEmails = new LinkedList<String>();
        for (Account account : accounts) {
            possibleEmails.add(account.name);
        }/*from   www  .  j  a  v a  2s  . c  o m*/
        if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
            String email = possibleEmails.get(0);
            String[] parts = email.split("@");
            if (parts.length > 0 && parts[0] != null) {
                mUsername = parts[0];
            }
        }
    }
    return mUsername;
}