TShopping

 找回密碼
 註冊
搜索
查看: 2167|回復: 0
打印 上一主題 下一主題

[教學] 取得 Android 手機上的帳號資訊

[複製鏈接]
跳轉到指定樓層
1#
發表於 2015-10-16 22:24:40 | 只看該作者 |只看大圖 回帖獎勵 |倒序瀏覽 |閱讀模式
 
Push to Facebook

通常使用 Android 手機的使用者都會把自己的 Google 帳號給設定在手機上,這樣一來才能使用 Google 提供的多種服務。像是 Marke、Gmail 或是 Google Talk 等等。

也有一些軟體開發者會用 Google 帳號來當做註冊的資訊使用,這樣使用者就算換了其它支 Android 手機的話,只要 Google 帳號不變就能繼續享有原先的權利。

Android SDK 2.0 中開始支援提供 AccountManager 來讓開發者能存取 Account 資訊:

  1. import android.accounts.Account;
  2. import android.accounts.AccountManager;
  3. import android.content.Context;

  4. AccountManager accountManager = AccountManager.get(context);
  5. Account[] accounts = accountManager.getAccounts();
  6. for(Account account : accounts){
  7.         Log.i("--Get Account Example--", account.name);
  8.         Log.i("--Get Account Example--", account.type);
  9. }
複製代碼

Account 中比較有用的資料是 nametype 兩個欄位:



如果手機上還有其它的帳號資料的時候,我們就能透過 type 來區分那些是 Google 的帳號資料了。剛剛是使用getAccounts() 來取得全部的帳號資訊。若筆者只想要取得 Google 帳號的資料時,那是不是得自己去判斷type 呢?

嘿~AccountManager 當然也有更快速的方式來針對 type 來存取帳號囉。從上一個範例中取得的帳號中可以看到屬於 Google 帳號的 type 會是 com.google,因此我們就能透過 getAccountsByType() 來取得指定 type 的帳號:

  1. import android.accounts.Account;
  2. import android.accounts.AccountManager;
  3. import android.content.Context;

  4. AccountManager accountManager = AccountManager.get(context);
  5. // 取得指定 type 的 Account
  6. Account[] accounts = accountManager.getAccountsByType("com.google");
  7. for(Account account : accounts){
  8.         Log.i("--Get Account Example--", account.name);
  9.         Log.i("--Get Account Example--", account.type);
  10. }
複製代碼


在發佈執行之前可別忘了要加上權限才行喔:



http://abgne.tw/android/android- ... t-account-info.html

 

臉書網友討論
*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-4-27 03:25 , Processed in 0.071773 second(s), 25 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表