Home » Android 程式片段

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

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

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

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

1
2
3
4
5
6
7
8
9
10
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
 
AccountManager accountManager = AccountManager.get(context);
Account[] accounts = accountManager.getAccounts();
for(Account account : accounts){
	Log.i("--Get Account Example--", account.name);
	Log.i("--Get Account Example--", account.type);
}

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



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

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

1
2
3
4
5
6
7
8
9
10
11
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
 
AccountManager accountManager = AccountManager.get(context);
// 取得指定 type 的 Account
Account[] accounts = accountManager.getAccountsByType("com.google");
for(Account account : accounts){
	Log.i("--Get Account Example--", account.name);
	Log.i("--Get Account Example--", account.type);
}

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

1
<uses-permission android:name="android.permission.GET_ACCOUNTS" />

也許您對這些文章也有興趣

  • [Android]使用自訂的字型
  • [Android]基本的 Widget 元件介紹 (二)
  • [Android]基本的 Widget 元件介紹 (一)
  • [Android]取得 Android 系統的 SDK 版本
  • [Android]取得 Android 系統的設備資訊
  • [Android]利用 TelephonyManager 取得電信網路資訊

2 筆針對 [Android]取得 Android 手機上的帳號資訊 的迴響

  1. 請教一下
    如果不想用手機綁定的帳號,而是想讓使用者另外輸入google帳號去驗證
    應該可行吧? 網路上這部份的資源好少...
    畢竟榜定的不太安全,想讓使用者用完就可以登出這樣。

發表迴響

您的電子郵件位址並不會被公開。 必要欄位標記為 *

*

您可以使用這些 HTML 標籤與屬性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>