获得手机上绑定的Google账号

本文介绍了在不同Android系统版本中获取Google账号的方法。对于1.5和1.6版本,需要使用第三方库并通过反射调用GoogleLoginServiceHelper的getAccount方法。而在2.0及更高版本,则可通过AccountManager直接获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.5和1.6的系统里没有现成的方法,因而需要用到第三方的库


/**
* use 3rd package to get Google Account
*
* @param activity
* @param requestCode
*/
private void getGoogleService(Activity activity, int requestCode) {
try {
for (Method ele : Class.forName(
"com.google.android.googlelogin.GoogleLoginServiceHelper")
.getMethods()) {
try {
if (ele.getName().equals("getAccount")) {
ele.invoke(null, activity, requestCode, true);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}


返回值需要用下面的方法获得

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_GOOGLE_ACCOUNT) {
String key = "accounts";
String accounts[] = data.getExtras().getStringArray(key);
if (accounts != null && accounts[0] != null) {
String account = accounts[0];
}
}
}


这个方法需要在AndroidManifest.xml里增加
<uses-permission android:name="com.google.android.googleapps.permission.GOOGLE_AUTH" />

2.0以后的版本,可以通过AccountManager来获得


/**
* use Account Manager to get Google Account
*
* @param activity
*/
private void getGoogleServiceWithAccountManager(Activity activity) {

try {
// declare class AccountManager
Class MyAccountManager = Class.forName("android.accounts.AccountManager");

// declare method getAccounts of AccountManager
Method mGetAccounts = MyAccountManager.getDeclaredMethod("getAccounts");

for (Method ele : MyAccountManager.getMethods()) {
try {
if (ele.getName().equals("get")) {
// call AccountManager.get to create an instance
Object obj = ele.invoke(null, activity);

// call AccountManager.getAccount to get Account[]
Object accounts[] = (Object[]) mGetAccounts.invoke(obj, null);
if (accounts.length > 0) {
// get the class member "name" of class Account
Field f = accounts[0].getClass().getDeclaredField("name");

// get the value of class member "name"
this.mAccount = (String) f.get(accounts[0]);
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} finally {
returnGoogleAccount();
}
}


考虑到程序可能在低版本的机器上运行,所以方法调用都使用了反射

附件为自己写的代码(包含第三方库文件),写得不好,请多包涵
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值