經過多次試驗和錯誤和研究,我找到了一個解決方案。因此,對於任何人誰可能有相同需求/問題:
首先,添加到您的build.gradle文件:
編譯「com.google.android.gms:發揮服務-auth的: 10.2.0'
然後,在需要獲得用戶的帳號ID添加此活動:
public class MainActivity extends AppCompatActivity{
private static final int REQUEST_CODE_EMAIL = 1;
TextView email, mAcctId;
Button getID;
String accountName;
String TAG = "test";
private static final int REQ_SIGN_IN_REQUIRED = 55664;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email = (TextView) findViewById(R.id.email);
mAcctId = (TextView)findViewById(R.id.accountID);
//Shows a popup allowing user to select email if more than one exists
try {
Intent intent = AccountPicker.newChooseAccountIntent(null, null,
new String[] { GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE }, false, null, null, null, null);
startActivityForResult(intent, REQUEST_CODE_EMAIL);
} catch (ActivityNotFoundException e) {
// TODO
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_EMAIL && resultCode == RESULT_OK) {
accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
email.setText(accountName);
//Call async task to get accountID for selected email
new RetrieveAccountID().execute(accountName);
}
}
private class RetrieveAccountID extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String accountName = params[0];
String token = null;
try {
token = GoogleAuthUtil.getAccountId(getApplicationContext(), accountName);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (UserRecoverableAuthException e) {
startActivityForResult(e.getIntent(), REQ_SIGN_IN_REQUIRED);
} catch (GoogleAuthException e) {
Log.e(TAG, e.getMessage());
}
return token;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
((TextView) findViewById(R.id.accountID)).setText("AccountID: " + s);
}
}
}
運行,這將使你的用戶選擇電子郵件在一個TextView中和另一個TextView中該電子郵件的accountID。現在可以使用它爲用戶電子郵件特有的應用程序創建令牌/密鑰。當用戶在不同的設備上使用應用時,這也可以用來驗證令牌/密鑰。