Example usage for android.accounts AccountManager getAccounts

List of usage examples for android.accounts AccountManager getAccounts

Introduction

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

Prototype

@NonNull
public Account[] getAccounts() 

Source Link

Document

Lists all accounts visible to the caller regardless of type.

Usage

From source file:org.systematicsheep.IdentifyUser.AccountReader.java

/**
 * Get all accounts on device./*from   ww w .ja  v a 2  s .c  om*/
 * 
 * @return
 */
private JSONArray getAllAccounts() throws JSONException {
    JSONArray accountsJson = new JSONArray();
    AccountManager accountManager = AccountManager.get(cordova.getActivity());
    Account[] accounts = accountManager.getAccounts();
    for (Account account : accounts) {
        JSONObject accJson = new JSONObject();
        accJson.put("name", account.name);
        accJson.put("type", account.type);
        accountsJson.put(accJson);
    }
    return accountsJson;
}

From source file:com.survivingwithandroid.accountnavigationdrawer.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String[] itmes = getResources().getStringArray(R.array.items_array);

    frame = (FrameLayout) findViewById(R.id.content_frame);

    Spinner spinner = (Spinner) findViewById(R.id.spinnerAccount);

    String[] items = new String[] { "item1", "item2", "item3" };

    AccountManager accMgr = AccountManager.get(this);

    Account[] accountList = accMgr.getAccounts();
    final String[] accountNames = new String[accountList.length + 1];
    int i = 1;// w  w  w.  jav a 2s  . c  om
    accountNames[0] = getResources().getString(R.string.infospinner);

    for (Account account : accountList) {
        String name = account.name;
        accountNames[i++] = name;
    }

    ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
            accountNames);
    spinner.setAdapter(adp);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            System.out.println("Pos [" + position + "]");
            if (position == 0)
                return;

            String currentAccount = accountNames[position];
            credential = GoogleAccountCredential.usingOAuth2(MainActivity.this, DriveScopes.DRIVE);
            credential.setSelectedAccountName(currentAccount);
            service = getDriveService(credential);
            AsyncAuth auth = new AsyncAuth();
            auth.execute("");
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);
    mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, itmes));

    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);
    // We should handle actionbar event correctly
}

From source file:com.afwsamples.testdpc.provision.PostProvisioningTask.java

public Intent getPostProvisioningLaunchIntent(Intent intent) {
    // Enable the profile after provisioning is complete.
    Intent launch;/* w  w w  . j ava  2s . c o m*/

    // Retreive the admin extras bundle, which we can use to determine the original context for
    // TestDPCs launch.
    PersistableBundle extras = intent.getParcelableExtra(EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE);
    String packageName = mContext.getPackageName();
    boolean synchronousAuthLaunch = LaunchIntentUtil.isSynchronousAuthLaunch(extras);
    boolean cosuLaunch = LaunchIntentUtil.isCosuLaunch(extras);
    boolean isProfileOwner = mDevicePolicyManager.isProfileOwnerApp(packageName);
    boolean isDeviceOwner = mDevicePolicyManager.isDeviceOwnerApp(packageName);

    // Drop out quickly if we're neither profile or device owner.
    if (!isProfileOwner && !isDeviceOwner) {
        return null;
    }

    if (isProfileOwner) {
        launch = new Intent(mContext, EnableProfileActivity.class);
    } else if (cosuLaunch) {
        launch = new Intent(mContext, EnableCosuActivity.class);
        launch.putExtra(EXTRA_PROVISIONING_ADMIN_EXTRAS_BUNDLE, extras);
    } else {
        launch = new Intent(mContext, EnableDeviceOwnerActivity.class);
    }

    if (synchronousAuthLaunch) {
        String accountName = LaunchIntentUtil.getAddedAccountName(extras);
        if (accountName != null) {
            launch.putExtra(LaunchIntentUtil.EXTRA_ACCOUNT_NAME, accountName);
        }
    }

    // For synchronous auth cases, we can assume accounts are already setup (or will be shortly,
    // as account migration for Profile Owner is asynchronous). For COSU we don't want to show
    // the account option to the user, as no accounts should be added for now.
    // In other cases, offer to add an account to the newly configured device/profile.
    if (!synchronousAuthLaunch && !cosuLaunch) {
        AccountManager accountManager = AccountManager.get(mContext);
        Account[] accounts = accountManager.getAccounts();
        if (accounts != null && accounts.length == 0) {
            // Add account after provisioning is complete.
            Intent addAccountIntent = new Intent(mContext, AddAccountActivity.class);
            addAccountIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            addAccountIntent.putExtra(AddAccountActivity.EXTRA_NEXT_ACTIVITY_INTENT, launch);
            return addAccountIntent;
        }
    }

    launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    return launch;
}

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

@Override
protected void onResume() {
    super.onResume();
    // Check if Account is available
    AccountManager acm = AccountManager.get(this);
    boolean found = false;
    for (Account accounts : acm.getAccounts()) {
        if (Constants.ACCOUNT_TYPE.equals(accounts.type) && TextUtils.equals(accounts.name, mUsername)) {
            found = true;/*from w ww .j  ava  2s . com*/
        }
    }
    if (!found) {
        clearNotification(mUsername);
        setResult(RESULT_CANCELED);
        finish();
        return;
    }
}

From source file:com.agiro.scanner.android.AppEngineClient.java

private String getAuthToken(Context context, Account account) {
    String authToken = null;//  w w w.  j av  a  2s.  c o m
    AccountManager accountManager = AccountManager.get(context);
    try {
        AccountManagerFuture<Bundle> future = accountManager.getAuthToken(account, AUTH_TOKEN_TYPE, false, null,
                null);
        Bundle bundle = future.getResult();
        Account[] accs = accountManager.getAccounts();
        Log.v(TAG, "Account size = " + accs.length);
        Log.v(TAG, "Listing accounts");
        for (Account acc : accs) {
            Log.v(TAG, "Account: " + acc);
        }
        authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
        // User will be asked for "App Engine" permission.
        if (authToken == null) {
            Log.e(TAG, "No authToken");
            // No auth token - will need to ask permission from user.
            Intent intent = new Intent("com.google.ctp.AUTH_PERMISSION");
            intent.putExtra("AccountManagerBundle", bundle);
            context.sendBroadcast(intent);
        }
    } catch (OperationCanceledException e) {
        Log.w(TAG, e.getMessage());
    } catch (AuthenticatorException e) {
        Log.w(TAG, e.getMessage());
    } catch (IOException e) {
        Log.w(TAG, e.getMessage());
    }
    return authToken;
}

From source file:de.spiritcroc.syncsettings.SelectSyncActivity.java

private void loadSyncs(boolean skipPermissionCheck) {
    // Permission to read accounts required
    if (!skipPermissionCheck && ContextCompat.checkSelfPermission(this,
            Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.GET_ACCOUNTS },
                REQUEST_PERMISSION_GET_ACCOUNTS);
        return;//from  www  . jav  a 2s . co  m
    }

    syncs.clear();

    // Syncs with no account will be master sync setting
    syncs.add(new Sync(null, getString(R.string.sync_master_on)));
    syncs.add(new Sync(null, getString(R.string.sync_master_off)));
    syncs.add(new Sync(null, getString(R.string.sync_master_toggle)));

    // Get user accounts
    AccountManager accountManager = AccountManager.get(getApplicationContext());
    Account[] accounts = accountManager.getAccounts();

    // Get authorities
    ArrayList<String> authorities = Util.getAuthorities();

    // Get available account/authority combinations
    if (DEBUG)
        Log.d(LOG_TAG, "Found accounts: " + accounts.length);
    for (Account account : accounts) {
        if (DEBUG)
            Log.d(LOG_TAG, "Found account " + account.name);
        for (int i = 0; i < authorities.size(); i++) {
            if (ContentResolver.getIsSyncable(account, authorities.get(i)) > 0) {
                syncs.add(new Sync(account, authorities.get(i)));
                if (DEBUG)
                    Log.d(LOG_TAG, "Added authority " + authorities.get(i));
            }
        }
    }

    // Build expandable list
    groups.clear();
    for (int i = 0; i < syncs.size(); i++) {
        if (syncs.get(i).account != null && !groups.contains(syncs.get(i).account)) {
            groups.add(syncs.get(i).account);
        }
    }

    final String ROOT = "ROOT_NAME";
    final String CHILD = "CHILD_NAME";

    List<Map<String, String>> groupData = new ArrayList<Map<String, String>>() {
        {
            // Add master sync group:
            add(new HashMap<String, String>() {
                {
                    put(ROOT, getString(R.string.sync_master));
                }
            });
            // Add accounts:
            for (int i = 0; i < groups.size(); i++) {
                final int j = i;
                add(new HashMap<String, String>() {
                    {
                        put(ROOT, groups.get(j).name + " (" + groups.get(j).type + ")");
                    }
                });
            }
        }
    };

    final List<List<Map<String, String>>> listOfChildGroups = new ArrayList<>();

    // Add master sync items:
    List<Map<String, String>> masterChildGroup = new ArrayList<Map<String, String>>() {
        {
            for (int j = 0; j < syncs.size(); j++) {
                final Sync sync = syncs.get(j);
                if (sync.account == null) {
                    add(new HashMap<String, String>() {
                        {
                            put(CHILD, sync.authority);
                        }
                    });
                } else {
                    break;
                }
            }
        }
    };
    // Add account data:
    listOfChildGroups.add(masterChildGroup);
    for (int i = 0; i < groups.size(); i++) {
        final int x = i;
        List<Map<String, String>> childGroup = new ArrayList<Map<String, String>>() {
            {
                for (int j = 0; j < syncs.size(); j++) {
                    final Sync sync = syncs.get(j);
                    if (sync.account != null && sync.account.equals(groups.get(x))) {
                        add(new HashMap<String, String>() {
                            {
                                put(CHILD, sync.authority);
                            }
                        });
                    }
                }
            }
        };
        listOfChildGroups.add(childGroup);
    }

    listView.setAdapter(new SimpleExpandableListAdapter(this,

            groupData, android.R.layout.simple_expandable_list_item_1, new String[] { ROOT },
            new int[] { android.R.id.text1 },

            listOfChildGroups, android.R.layout.simple_expandable_list_item_1, new String[] { CHILD },
            new int[] { android.R.id.text1 }));
}

From source file:org.sociotech.fishification.ui.fragments.CreateFishFragment.java

@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {

    String userName = null;/*  w  w w  . j  a v  a 2s . c  om*/
    cursor.moveToFirst();
    if (!cursor.isAfterLast()) {

        if (cursorLoader.getId() == 0) {

            userName = cursor.getString(ProfileQuery.DISPLAY_NAME);

        } else {
            userName = cursor.getString(ProfileQuery.ADDRESS);
        }
    }

    if (userName != null && !userName.isEmpty()) {

        // Set UserName
        setEditText(R.id.authorNameText, userName);

    } else if (cursorLoader.getId() == 0) {

        // Select primary e-mail address
        getActivity().getSupportLoaderManager().initLoader(1, null, this);

    } else {

        // Parse accounts for user name or e-mail address
        AccountManager am = AccountManager.get(getActivity());
        Account[] accounts = am.getAccountsByType("XING");
        if (accounts != null && accounts.length > 0) {
            setEditText(R.id.authorNameText, accounts[0].name);
        } else {
            accounts = am.getAccounts();
            if (accounts != null && accounts.length > 0) {
                setEditText(R.id.authorNameText, accounts[0].name);
            }
        }
    }
}

From source file:de.appplant.cordova.emailcomposer.EmailComposerImpl.java

/**
 * If email apps are available.//  w  ww.  ja v a2s .  c om
 *
 * @param ctx
 * The application context.
 * @return
 * true if available, otherwise false
 */
private boolean isEmailAccountConfigured(Context ctx) {
    Uri uri = Uri.fromParts("mailto", "max@mustermann.com", null);
    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
    PackageManager pm = ctx.getPackageManager();
    int apps = pm.queryIntentActivities(intent, 0).size();

    if (apps == 0) {
        return false;
    }

    AccountManager am = AccountManager.get(ctx);
    int accounts;

    try {
        accounts = am.getAccounts().length;
    } catch (Exception e) {
        Log.e("EmailComposer", "Missing GET_ACCOUNTS permission.");
        return true;
    }

    return accounts > 0;
}

From source file:io.hypertrack.sendeta.view.Profile.java

private String getName() {
    AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
        return null;
    }/*from  w w w  . j  a va  2 s. c o  m*/

    Account[] list = manager.getAccounts();

    for (Account account : list) {
        if (account.type.equalsIgnoreCase("com.google")) {
            return account.name;
        }
    }
    return null;
}

From source file:com.einzig.ipst2.activities.MainActivity.java

/**
 * Get user account if the user has already logged in.
 *
 * @return Account user logged in on./* w w w . j  av a2 s .  c  o  m*/
 */
private Account getAccount() {
    PreferencesHelper helper = new PreferencesHelper(getApplicationContext());
    String email = helper.get(helper.emailKey());
    Logger.i("Getting account " + email);
    AccountManager manager = AccountManager.get(this);
    for (Account account : manager.getAccounts()) {
        if (account.name.equalsIgnoreCase(email) && account.type.equalsIgnoreCase("com.google"))
            return account;
    }
    Logger.d("returning null account");
    return null;
}