Check whether an auth of this type has been registered. - Android android.accounts

Android examples for android.accounts:Account

Description

Check whether an auth of this type has been registered.

Demo Code


//package com.java2s;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;

public class Main {
    /**/*from  w  w  w. jav a2  s .  c  om*/
     * Check whether an auth of this type has been registered. Assumption is that there
     * can only be one single auth of a type.
     *
     * @param context     A {@link Context} object
     * @param accountType Type of the auth
     * @return <code>true</code> if an auth of given type exists, <code>false</code> otherwise
     */
    public static boolean isAccountRegistered(Context context,
            String accountType) {
        return getAccount(context, accountType) != null;
    }

    /**
     * Retrieve the {@link Account} object for given <code>accountName</code> and <code>accountType</code>.
     *
     * @param context     A {@link Context} object
     * @param accountName Name of the auth
     * @param accountType Type of the auth
     * @return {@link Account} object with specified parameters, <code>null</code> if there is no
     * auth with such <code>accountName</code>, or there are no accounts of this
     * <code>accountType</code>
     */
    public static Account getAccount(Context context, String accountName,
            String accountType) {
        AccountManager accountManager = AccountManager.get(context);
        Account[] accounts = accountManager.getAccountsByType(accountType);
        for (Account account : accounts) {
            if (account.name.equals(accountName)) {
                return account;
            }
        }
        return null;
    }

    /**
     * Retrieve the {@link Account} object for given <code>accountType</code>, assuming that
     * there's one single auth of this type.
     *
     * @param context     A {@link Context} object
     * @param accountType Type of the auth
     * @return {@link Account} object with specified parameters, <code>null</code> if there
     * are no accounts of this <code>accountType</code>
     */
    public static Account getAccount(Context context, String accountType) {
        AccountManager accountManager = AccountManager.get(context);
        Account[] accounts = accountManager.getAccountsByType(accountType);
        if (accounts.length > 0) {
            return accounts[0];
        }
        return null;
    }
}

Related Tutorials