首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

获得手机下绑定的Google账号

2012-09-02 
获得手机上绑定的Google账号1.5和1.6的系统里没有现成的方法,因而需要用到第三方的库/** * use 3rd packag

获得手机上绑定的Google账号
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();}}


返回值需要用下面的方法获得
@Overrideprotected 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 AccountManagerClass MyAccountManager = Class.forName("android.accounts.AccountManager");// declare method getAccounts of AccountManagerMethod mGetAccounts = MyAccountManager.getDeclaredMethod("getAccounts");for (Method ele : MyAccountManager.getMethods()) {try {if (ele.getName().equals("get")) {// call AccountManager.get to create an instanceObject 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 AccountField 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();}}


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

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

热点排行