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:mobile.tiis.appv2.LoginActivity.java

/**
 * This method will get called when the user presses the login
 * button.//  www. jav a  2s  .c o m
 *
 * <p>This method will check with checkRequiredFields to make
 * sure if it will process the click.
 */

public void onClick(View v) {
    Log.d(TAG, "clicked login");
    //get inserted username and password
    username = usernameEditText.getText().toString().trim();
    password = passwordEditText.getText().toString().trim();

    //check if required fields are not empty
    if (checkRequiredFields()) {
        Log.d(TAG, "check passed");
        progressDialog.setMessage("Signing in. \nPlease wait ...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();

        loginButton.setEnabled(false);
        //continue with device online
        if (Utils.isOnline(LoginActivity.this)) {

            boolean loggedIn = false;
            if (databaseHandler.getAllUsers().size() != 0) {
                //Checking if the user had once logged in
                //check if user is already registered with AccountManager
                AccountManager accountManager = AccountManager.get(LoginActivity.this);
                Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE);

                //go through all accounts found in Account Manager
                for (Account account : accounts) {
                    //if there is a match set login as true and go to Home Activity
                    if (account.name.equalsIgnoreCase(username)
                            && accountManager.getPassword(account).equals(password)) {
                        //Activity mobile.tiis.app.LoginActivity has leaked window error was showing
                        //this piece of code handles it, nonetheless in prod time the error  would not show
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        SharedPreferences.Editor editor = PreferenceManager
                                .getDefaultSharedPreferences(getApplicationContext()).edit();
                        editor.putBoolean("secondSyncNeeded", true);
                        editor.commit();

                        Intent intent = new Intent(LoginActivity.this, LotSettingsActivity.class);

                        Log.d(TAG, "initiating offline for " + username + " password = " + password);
                        app.initializeOffline(username, password);

                        Log.d(TAG, "initiating offline for " + username + " password = " + password);

                        app.setUsername(username);
                        Log.d("supportLog", "call the loggin first time before the account was found");
                        startActivity(intent);
                        loggedIn = true;
                    }
                }
            } else {
                SharedPreferences preferenceManager = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext());
                preferenceManager.edit().putBoolean("synchronization_needed", true);
            }
            if (!loggedIn) {

                //build webservice url
                StringBuilder webServiceLoginURL = createWebServiceLoginURL(username, password, regId);

                //call web service to pull user info and send to account manager
                try {
                    startWebService(webServiceLoginURL, username, password);
                } catch (NullPointerException e) {
                    startWebService(webServiceLoginURL, username, password);
                }
            }

        } else {

            //check if user is already registered with AccountManager
            AccountManager accountManager = AccountManager.get(LoginActivity.this);
            Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE);
            boolean loggedIn = false;
            if (databaseHandler.getAllUsers().size() != 0) {

                //go through all accounts found in AM
                for (Account account : accounts) {
                    //if there is a match set login as true and go to Home Activity
                    if (account.name.equalsIgnoreCase(username)
                            && accountManager.getPassword(account).equals(password)) {
                        //Activity mobile.tiis.app.LoginActivity has leaked window error was showing
                        //this piece of code handles it, nonetheless in prod time the error  would not show
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        SharedPreferences.Editor editor = PreferenceManager
                                .getDefaultSharedPreferences(getApplicationContext()).edit();
                        editor.putBoolean("secondSyncNeeded", true);
                        editor.commit();

                        Intent intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                        app.setUsername(username);
                        Log.d(TAG, "initiating offline for " + username + " password = " + password);
                        app.initializeOffline(username, password);
                        startActivity(intent);
                        loggedIn = true;
                    }
                }
            } else {
                SharedPreferences preferenceManager = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext());
                preferenceManager.edit().putBoolean("synchronization_needed", true);
            }
            //if login failed, show error
            if (!loggedIn) {
                progressDialog.dismiss();
                toastMessage("Login failed.\nPlease check your details or be online for first login!");
                loginButton.setEnabled(true);
            }
        }
    }
}

From source file:org.andstatus.app.account.MyAccount.java

private Account getExisingAndroidAccount() {
    Account androidAccount = null;//from  www  .  ja va 2s  .  co m
    // Let's check if there is such an Android Account already
    android.accounts.AccountManager am = AccountManager.get(MyContextHolder.get().context());
    android.accounts.Account[] aa = am.getAccountsByType(AuthenticatorService.ANDROID_ACCOUNT_TYPE);
    for (android.accounts.Account account : aa) {
        if (getAccountName().equals(account.name)) {
            androidAccount = account;
            break;
        }
    }
    return androidAccount;
}

From source file:com.raceyourself.android.samsung.ProviderService.java

private void authorize() {
    UserDetail me = Helper.getUser();/*from ww  w. j  a  va2s  . c o m*/
    if (me != null && me.getApiAccessToken() != null)
        return;

    AccountManager mAccountManager = AccountManager.get(this);
    List<Account> accounts = new ArrayList<Account>();
    accounts.addAll(Arrays.asList(mAccountManager.getAccountsByType("com.google")));
    accounts.addAll(Arrays.asList(mAccountManager.getAccountsByType("com.googlemail")));
    String email = null;
    for (Account account : accounts) {
        if (account.name != null && account.name.contains("@")) {
            email = account.name;
            break;
        }
    }
    // Potential fault: Can there be multiple accounts? Do we need to sort or provide a selector?

    // hash email so we don't send user's identity to server
    // can't guarantee uniqueness but want very low probability of collisions
    // using SHA-256 means we'd expect a collision on approx. our 1-millionth user
    // TODO: make this more unique before Samsung sell 1m Gear IIs.
    MessageDigest messageDigest;
    try {
        messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(email.getBytes());
        String hash = new String(messageDigest.digest());
        hash = new String(Base64.encode(hash.getBytes(), Base64.DEFAULT)).replace("@", "_").replace("\n", "_"); //base64 encode and substitute @ symbols
        hash += "@hashed.raceyourself.com"; // make it look like an email so it passes server validation
        Helper.login(hash, SERVER_TOKEN);
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Implementation of SHA-256 algorithm not found. Authorisation failed. Exiting.");
        throw new RuntimeException();
    }
}

From source file:org.tigase.mobile.TigaseMobileMessengerActivity.java

private boolean onOptionsItemSelected(int id) {
    if (id == R.id.showChatsButton) {
        Intent chatListActivity = new Intent(this, ChatListActivity.class);
        this.startActivityForResult(chatListActivity, TigaseMobileMessengerActivity.REQUEST_CHAT);
        return true;
    } else if (id == R.id.joinMucRoom) {
        JoinMucDialog newFragment = JoinMucDialog.newInstance();
        AsyncTask<Room, Void, Void> r = new AsyncTask<Room, Void, Void>() {

            @Override/*from w  ww .  ja va2  s. c o m*/
            protected Void doInBackground(Room... params) {
                final long roomId = params[0].getId();

                viewPager.post(new Runnable() {

                    @Override
                    public void run() {
                        final Integer idx = findRoom(roomId);
                        // this should be done on receiving RoomJoined event
                        viewPager.getAdapter().notifyDataSetChanged();
                        setVisiblePage(idx + (helper.isXLarge() ? 1 : 2));
                    }
                });
                return null;
            }
        };
        newFragment.setAsyncTask(r);
        newFragment.show(getSupportFragmentManager(), "dialog");
        return true;
    } else if (id == android.R.id.home) {
        setVisiblePage(1);
        return true;
    } else if (id == R.id.showHideOffline) {
        boolean x = mPreferences.getBoolean(Preferences.SHOW_OFFLINE, Boolean.TRUE);
        Editor editor = mPreferences.edit();
        editor.putBoolean(Preferences.SHOW_OFFLINE, !x);
        editor.commit();
        Uri insertedItem = Uri.parse(RosterProvider.CONTENT_URI);
        getApplicationContext().getContentResolver().notifyChange(insertedItem, null);
        return true;
        // insertedItem =
        // Uri.parse("content://org.tigase.mobile.db.providers.RosterProvider");
        // getApplicationContext().getContentResolver().notifyChange(insertedItem,
        // null);
    } else if (id == R.id.contactAdd) {
        AccountManager accountManager = AccountManager.get(this);
        final Account[] accounts = accountManager.getAccountsByType(Constants.ACCOUNT_TYPE);

        if (accounts != null && accounts.length > 1) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            Fragment prev = getSupportFragmentManager().findFragmentByTag("account:select:dialog");
            if (prev != null) {
                ft.remove(prev);
            }
            ft.addToBackStack(null);
            AccountSelectorDialogFragment newFragment = AccountSelectorDialogFragment.newInstance();
            newFragment.show(ft, "account:select:dialog");
            return true;
        } else if (accounts != null && accounts.length == 1) {
            Intent intent = new Intent(this, ContactEditActivity.class);
            intent.putExtra("account", accounts[0].name);
            startActivityForResult(intent, 0);
            return true;
        }
    } else if (id == R.id.aboutButton) {
        showDialog(ABOUT_DIALOG);
        return true;
    } else if (id == R.id.propertiesButton) {
        Intent intent = new Intent().setClass(this, MessengerPreferenceActivity.class);
        this.startActivityForResult(intent, 0);
        return true;
    } else if (id == R.id.disconnectButton) {
        mPreferences.edit().putBoolean(Preferences.SERVICE_ACTIVATED, false).commit();
        stopService(new Intent(TigaseMobileMessengerActivity.this, JaxmppService.class));
        return true;
    } else if (id == R.id.connectButton) {
        mPreferences.edit().putBoolean(Preferences.SERVICE_ACTIVATED, true).commit();

        Intent intent = new Intent(TigaseMobileMessengerActivity.this, JaxmppService.class);
        intent.putExtra("focused", true);
        startService(intent);
        return true;
    } else if (id == R.id.bookmarksShow) {
        Intent intent = new Intent(TigaseMobileMessengerActivity.this, BookmarksActivity.class);
        startActivityForResult(intent, REQUEST_CHAT);
        return true;
    }
    return false;
}

From source file:edu.mit.mobile.android.locast.net.NetworkClient.java

/**
 * Perform an offline check to see if there is a pairing stored for this client. Does not block
 * on network connection.// w  ww  .  java  2s.c  om
 *
 * @return true if the client is paired with the server.
 */
@Deprecated
public boolean isPaired() {
    final AccountManager am = AccountManager.get(mContext);
    final Account[] accounts = am.getAccountsByType(AuthenticationService.ACCOUNT_TYPE);
    return accounts.length >= 1;
}

From source file:org.tigase.mobile.TigaseMobileMessengerActivity.java

/** Called when the activity is first created. */
@Override//w  ww  .j av  a  2 s.c om
public void onCreate(Bundle savedInstanceState) {
    if (DEBUG)
        Log.d(TAG, "onCreate()");

    IntentFilter filter = new IntentFilter(JaxmppService.MUC_ERROR_MSG);
    registerReceiver(mucErrorReceiver, filter);

    super.onCreate(savedInstanceState);
    this.mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    this.mPreferences.registerOnSharedPreferenceChangeListener(prefChangeListener);

    boolean autostart = mPreferences.getBoolean(Preferences.AUTOSTART_KEY, true);
    autostart &= mPreferences.getBoolean(Preferences.SERVICE_ACTIVATED, true);
    if (autostart && !JaxmppService.isServiceActive()) {
        Intent intent = new Intent(this, JaxmppService.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startService(intent);
    }

    AccountManager accountManager = AccountManager.get(this);
    Account[] accounts = accountManager.getAccountsByType(Constants.ACCOUNT_TYPE);
    String previouslyStartedVersion = mPreferences.getString(Preferences.LAST_STARTED_VERSION, null);
    mPreferences.edit()
            .putString(Preferences.LAST_STARTED_VERSION, getResources().getString(R.string.app_version))
            .commit();

    if (previouslyStartedVersion == null && (accounts == null || accounts.length == 0)) {
        Intent intent = new Intent(this, AuthenticatorActivity.class);
        intent.putExtra("new", true);
        startActivity(intent);
        // finish();
    }

    if (savedInstanceState != null && getCurrentPage() == -1) {
        // currentPage = savedInstanceState.getInt(STATE_CURRENT_PAGE_KEY,
        // -1);
        if (getChatByPageIndex(getCurrentPage()) == null)
            setCurrentPage(-1);
    }

    if (getCurrentPage() == -1) {
        // this should not happened as there is not valid position
        setCurrentPage(helper.isXLarge() ? 0 : 1);
    }

    if (helper.isXLarge()) {
        setContentView(R.layout.all);
    } else {
        setContentView(R.layout.roster_main);
    }

    this.drawerList = (ListView) findViewById(R.id.main_left_drawer);
    this.drawerLayout = (DrawerLayout) findViewById(R.id.roster_main);

    // creating list of items available in drawer menu
    final List<DrawerMenuItem> drawerMenuItems = new ArrayList<DrawerMenuItem>();
    drawerMenuItems
            .add(new DrawerMenuItem(R.id.joinMucRoom, R.string.join_muc_room, R.drawable.group_chat, true));
    drawerMenuItems.add(
            new DrawerMenuItem(R.id.bookmarksShow, R.string.bookmarks_show, android.R.drawable.star_off, true));
    drawerMenuItems.add(new DrawerMenuItem(R.id.propertiesButton, R.string.propertiesButton,
            android.R.drawable.ic_menu_preferences));
    drawerMenuItems.add(new DrawerMenuItem(R.id.aboutButton, R.string.aboutButton,
            android.R.drawable.ic_menu_info_details));

    this.drawerList.setAdapter(new DrawerMenuAdapter(this.getApplicationContext(),
            R.layout.main_left_drawer_item, drawerMenuItems));
    this.drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.accept,
            R.string.accept) {

    };
    drawerLayout.setDrawerListener(this.drawerToggle);
    this.drawerList.setOnItemClickListener(new ListView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            DrawerMenuItem item = drawerMenuItems.get(position);
            if (item != null) {
                drawerLayout.closeDrawers();
                onOptionsItemSelected(item.id);
            }
        }
    });

    this.viewRoster = (ViewPager) findViewById(R.id.viewRoster);
    this.viewPager = (ViewPager) findViewById(R.id.viewSwitcher);
    this.viewPager.setOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            if (DEBUG)
                Log.i(TigaseMobileMessengerActivity.TAG, "PageScrollStateChanged: " + state);
        }

        @Override
        public void onPageSelected(int position) {
            if (DEBUG)
                Log.i(TigaseMobileMessengerActivity.TAG, "PageSelected: " + position);

            setCurrentPage(position);
            notifyPageChange(position);
        }
    });

    if (viewRoster != null) {
        viewRoster.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return 1;
            }

            @Override
            public Fragment getItem(int i) {
                return createRosterFragment(mPreferences.getString(Preferences.ROSTER_LAYOUT_KEY, "flat"));
            }
        });
    }

    this.adapter = new MyFragmentPageAdapter(getSupportFragmentManager()) {

        @Override
        public int getCount() {
            if (helper.isXLarge())
                return 1 + getChatList().size();
            int n = 2 + getChatList().size();
            return n;
        }

        @Override
        public Fragment getItem(int i) {
            if (DEBUG)
                Log.i(TAG, "FragmentPagerAdapter.getItem(" + i + ")");
            if (i == 0) {
                return AccountsStatusFragment.newInstance();
            } else if (!helper.isXLarge() && i == 1) {
                Fragment f = createRosterFragment(
                        mPreferences.getString(Preferences.ROSTER_LAYOUT_KEY, "flat"));
                if (DEBUG)
                    Log.d(TAG, "Created roster with FragmentManager " + f.getFragmentManager());
                return f;

            } else {
                int idx = i - (!helper.isXLarge() ? 2 : 1);
                final ChatWrapper wrapper = getChatList().get(idx);
                if (wrapper.isChat()) {
                    return ChatHistoryFragment.newInstance(
                            wrapper.getChat().getSessionObject().getUserBareJid().toString(),
                            wrapper.getChat().getId());
                } else {
                    Room room = wrapper.getRoom();
                    Fragment fr = MucRoomFragment
                            .newInstance(room.getSessionObject().getUserBareJid().toString(), room.getId());
                    return fr;
                }
            }
        }

        @Override
        public int getItemPosition(Object object) {
            if (object instanceof AccountsStatusFragment) {
                return 0;
            } else if (refreshRoster && object instanceof RosterFragment) {
                return POSITION_NONE;
            } else if (object instanceof RosterFragment) {
                return 1;
            } else if (object instanceof MucRoomFragment) {
                Log.v(TAG, "got chat history fragment");
                Room room = ((MucRoomFragment) object).getRoom();
                if (room != null) {
                    Integer position = findRoom(room.getId());
                    if (position != null) {
                        if (helper.isXLarge())
                            return 1 + position;
                        return 2 + position;
                    }
                }
                return POSITION_NONE;
            } else if (object instanceof ChatHistoryFragment) {
                Log.v(TAG, "got chat history fragment");
                Chat chat = ((ChatHistoryFragment) object).getChat();
                if (chat != null) {
                    Integer position = findChat(chat.getId());
                    if (position != null) {
                        if (helper.isXLarge())
                            return 1 + position;
                        return 2 + position;
                    }
                }
                return POSITION_NONE;
            } else {
                return POSITION_NONE;
            }
        }

        @Override
        protected String makeFragmentName(int viewId, int index) {
            if (index == 0) {
                return "accounts";
            } else if (!helper.isXLarge() && index == 1) {
                return "roster";
            } else {
                int pos = index - (helper.isXLarge() ? 1 : 2);
                if (pos < getChatList().size() && pos > -1) {
                    return getChatList().get(pos).toString();
                } else {
                    return null;
                }
            }
        }

    };

    viewPager.setAdapter(this.adapter);

    if (getIntent().getData() instanceof Uri) {
        Uri uri = getIntent().getData();
        if (DEBUG)
            Log.d(TAG, "onCreate(" + uri + ")");

        JID jid = JID.jidInstance(uri.getPath().substring(1));
        for (JaxmppCore jaxmpp : ((MessengerApplication) getApplicationContext()).getMultiJaxmpp().get()) {
            RosterItem ri = jaxmpp.getRoster().get(jid.getBareJid());
            if (ri != null) {
                openChatWith(ri, jid.getResource());
            }
        }
    }

    processingNotificationIntent(getIntent());

    try {
        int codeC = getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode;
        int codeP = mPreferences.getInt("news_dialog_displayed_for", -1);
        if (codeC != codeP) {
            mPreferences.edit().putInt("news_dialog_displayed_for", codeC).commit();
            showNewsInfo();
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

}

From source file:xyz.template.material.menu.ui.BaseActivity.java

/**
 * Returns the default account on the device. We use the rule that the first account
 * should be the default. It's arbitrary, but the alternative would be showing an account
 * chooser popup which wouldn't be a smooth first experience with the app. Since the user
 * can easily switch the account with the nav drawer, we opted for this implementation.
 *///from  w w  w .  java  2  s.  c o m
private String getDefaultAccount() {
    // Choose first account on device.
    LOGD(TAG, "Choosing default account (first account on device)");
    AccountManager am = AccountManager.get(this);
    Account[] accounts = am.getAccountsByType("com.google");
    if (accounts.length == 0) {
        // No Google accounts on device.
        LOGW(TAG, "No Google accounts on device; not setting default account.");
        return null;
    }

    LOGD(TAG, "Default account is: " + accounts[0].name);
    return accounts[0].name;
}

From source file:fr.paug.droidcon.ui.BaseActivity.java

/**
 * Sets up the account box. The account box is the area at the top of the nav drawer that
 * shows which account the user is logged in as, and lets them switch accounts. It also
 * shows the user's Google+ cover photo as background.
 *//* w  w w  .j  a  va 2  s .c om*/
private void setupAccountBox() {
    mAccountListContainer = (LinearLayout) findViewById(R.id.account_list);

    if (mAccountListContainer == null) {
        //This activity does not have an account box
        return;
    }

    final View chosenAccountView = findViewById(R.id.chosen_account_view);
    Account chosenAccount = AccountUtils.getActiveAccount(this);
    if (chosenAccount == null) {
        // No account logged in; hide account box
        chosenAccountView.setVisibility(View.GONE);
        mAccountListContainer.setVisibility(View.GONE);
        return;
    } else {
        chosenAccountView.setVisibility(View.VISIBLE);
        mAccountListContainer.setVisibility(View.INVISIBLE);
    }

    AccountManager am = AccountManager.get(this);
    Account[] accountArray = am.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
    List<Account> accounts = new ArrayList<Account>(Arrays.asList(accountArray));
    accounts.remove(chosenAccount);

    ImageView coverImageView = (ImageView) chosenAccountView.findViewById(R.id.profile_cover_image);
    ImageView profileImageView = (ImageView) chosenAccountView.findViewById(R.id.profile_image);
    TextView nameTextView = (TextView) chosenAccountView.findViewById(R.id.profile_name_text);
    TextView email = (TextView) chosenAccountView.findViewById(R.id.profile_email_text);
    mExpandAccountBoxIndicator = (ImageView) findViewById(R.id.expand_account_box_indicator);

    String name = AccountUtils.getPlusName(this);
    if (name == null) {
        nameTextView.setVisibility(View.GONE);
    } else {
        nameTextView.setText(name);
    }

    String imageUrl = AccountUtils.getPlusImageUrl(this);
    if (imageUrl != null) {
        mImageLoader.loadImage(imageUrl, profileImageView);
    }

    String coverImageUrl = AccountUtils.getPlusCoverUrl(this);
    if (coverImageUrl != null) {
        mImageLoader.loadImage(coverImageUrl, coverImageView);
    } else {
        coverImageView.setImageResource(R.drawable.default_cover);
    }

    email.setText(chosenAccount.name);

    if (accounts.isEmpty()) {
        // There's only one account on the device, so no need for a switcher.
        mExpandAccountBoxIndicator.setVisibility(View.GONE);
        mAccountListContainer.setVisibility(View.GONE);
        chosenAccountView.setEnabled(false);
        return;
    }

    chosenAccountView.setEnabled(true);

    mExpandAccountBoxIndicator.setVisibility(View.VISIBLE);
    chosenAccountView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mAccountBoxExpanded = !mAccountBoxExpanded;
            setupAccountBoxToggle();
        }
    });
    setupAccountBoxToggle();

    populateAccountList(accounts);
}

From source file:xyz.template.material.menu.ui.BaseActivity.java

private void signInOrCreateAnAccount() {
    //Get list of accounts on device.
    AccountManager am = AccountManager.get(BaseActivity.this);
    Account[] accountArray = am.getAccountsByType("com.google");
    if (accountArray.length == 0) {
        //Send the user to the "Add Account" page.
        Intent intent = new Intent(Settings.ACTION_ADD_ACCOUNT);
        intent.putExtra(Settings.EXTRA_ACCOUNT_TYPES, new String[] { "com.google" });
        startActivity(intent);/*  ww w  .j a  v  a 2  s  . c om*/
    } else {
        //Try to log the user in with the first account on the device.
        startLoginProcess();
        mDrawerLayout.closeDrawer(Gravity.START);
    }
}

From source file:com.google.samples.apps.sergio.ui.BaseActivity.java

/**
 * Returns the default account on the device. We use the rule that the first account
 * should be the default. It's arbitrary, but the alternative would be showing an account
 * chooser popup which wouldn't be a smooth first experience with the app. Since the user
 * can easily switch the account with the nav drawer, we opted for this implementation.
 *///from  www  . j a v a 2s  .c o  m
private String getDefaultAccount() {
    // Choose first account on device.
    LOGD(TAG, "Choosing default account (first account on device)");
    AccountManager am = AccountManager.get(this);
    Account[] accounts = am.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
    if (accounts.length == 0) {
        // No Google accounts on device.
        LOGW(TAG, "No Google accounts on device; not setting default account.");
        return null;
    }

    LOGD(TAG, "Default account is: " + accounts[0].name);
    return accounts[0].name;
}