最近有一個需求,當用戶在用我們的application提交請求的時候,需要得到用戶的一個標示
幾經考量,發現ip address或者去找到一個android device的唯一標示都不是很理想
最終選中從用戶機器中的郵件地址入手:比如用戶用於登入android market的gmail account,或者用戶配置在機器上面的mail 地址
我們就可以利用這些email地址主動聯繫用戶if necessary。
習慣性的google了一圈,找到一個獲取android device primary email address和獲取android owner's email address兩個有用的鏈接
發現如果要獲取機器上面的賬戶信息其實很簡單,關鍵就是AccountManager的使用 (Android 2.0+)
第一: 要申明權限
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
第二:獲取AccountManager對象,查詢account type爲com.google的account
AccountManager accountManager = AccountManager.get(context);
Account[] accounts = accountManager.getAccountsByType("com.google");
或者獲取全部的account,循環之並按照自己的條件查找符合的account
Account[] accounts = AccountManager.get(this).getAccounts();
for (Account account : accounts) {
// TODO: Check possibleEmail against an email regex or treat
// account.name as an email address only for certain account.type values.
String possibleEmail = account.name;
String emailType = accoun.type;
}