AccountManager: How to let the user select an Acco

2020-04-10 03:39发布

In the AccountManager tutorial Remembering Your User, it's recommended:

If there's more than one Account in the array, you should present a dialog asking the user to select one.

What's the best way to do this? I have a solution in mind, but if there are other good examples from the community, it seems like this is the kind of boilerplate code that could be shared and easily re-used by others.

2条回答
beautiful°
2楼-- · 2020-04-10 04:18

I use this code. It show an dialog, so enduser can choose one of the google account.

ArrayList<String> gUsernameList = new ArrayList<String>();
AccountManager accountManager = AccountManager.get(this);
Account[] accounts = accountManager.getAccountsByType("com.google");

gUsernameList.clear();
//loop
for (Account account : accounts) {
    gUsernameList.add(account.name);
}

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose you gmail-account");

ListView lv = new ListView(this);

ArrayAdapter<String> adapter = new ArrayAdapter<String> 
(this,android.R.layout.simple_list_item_1, android.R.id.text1, 
gUsernameList);

lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {    

public void onItemClick(AdapterView<?> parent,View view,int position,long 
id) 
{
    Log.d("You-select-gmail-account", gUsernameList.get(position)) );
}
});

builder.setView(lv);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        dialog.dismiss();
    }
});

final Dialog dialog = builder.create();
dialog.show();
查看更多
【Aperson】
3楼-- · 2020-04-10 04:25

From Android 4.0 (API level 14) onwards, launching an activity with an intent shown below, shows account chooser.

Intent intent = AccountManager.newChooseAccountIntent(null, null,
        new String[] { acc_type }, true, null, null,
        null, null);
startActivityForResult(intent, CHOOSE_ACCOUNT);

For devices older than 4.0,
use https://github.com/frakbot/Android-AccountChooser

查看更多
登录 后发表回答