ITeye博客

获得手机上绑定的Google账号

dai_lm · 2010-10-21 14:21 · Android · 移动开发 · Google · XML · F# · Android · Markdown

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里增加

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();
	}
}

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

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。