Gets the current active account as specified in the preferences. - Android Account

Android examples for Account:Account Information

Description

Gets the current active account as specified in the preferences.

Demo Code


import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.util.Log;

public class Main{
    /** TAG for logging */
    public static final String TAG = "AccountUtils";
    public static Account getActiveAccount(Context context, boolean set) {
        // Obtain the preference manager.
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(context);
        String accountName = prefs.getString("account", null);
        Account[] accounts = getAllAccounts(context);
        if (accountName != null) {
            for (Account account : accounts) {
                if (account.name.equals(accountName)) {
                    Log.v(TAG, "Using account found in preferences");
                    return account;
                }/*w w w . j  a  v a2 s  .  c  om*/
            }

            if (set && accounts.length != 0) {
                Editor prefsEditor = prefs.edit();
                prefsEditor.putString("account", accounts[0].name);
                prefsEditor.commit();
            }

            return (accounts.length == 0) ? null : accounts[0];

        } else {
            if (set && accounts.length != 0) {
                Editor prefsEditor = prefs.edit();
                prefsEditor.putString("account", accounts[0].name);
                prefsEditor.commit();
            }

            return (accounts.length == 0) ? null : accounts[0];

        }
    }
    public static Account getActiveAccount(Context context) {
        return getActiveAccount(context, false);
    }
    public static Account[] getAllAccounts(Context context) {
        AccountManager am = AccountManager.get(context
                .getApplicationContext());
        Account[] accounts = am.getAccountsByType(Constants.ACCOUNT_TYPE);
        return accounts;
    }
}

Related Tutorials