瞭解自定義帳戶身份驗證

以下示例是關鍵概念和基本骨架設定的高階別覆蓋: -

  1. 從使用者收集憑據(通常來自你建立的登入螢幕)
  2. 使用伺服器驗證憑據(儲存自定義身份驗證)
  3. 在裝置上儲存憑據

擴充套件 AbstractAccountAuthenticator (主要用於檢索身份驗證並重新驗證它們)

public class AccountAuthenticator extends AbstractAccountAuthenticator {

  @Override
  public Bundle addAccount(AccountAuthenticatorResponse response, String accountType,
      String authTokenType, String[] requiredFeatures, Bundle options) {
    //intent to start the login activity
  }

  @Override
  public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) {
  }

  @Override
  public Bundle editProperties(AccountAuthenticatorResponse response, String accountType) {
  }

  @Override
  public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType,
      Bundle options) throws NetworkErrorException {
    //retrieve authentication tokens from account manager storage or custom storage or re-authenticate old tokens and return new ones
  }

  @Override
  public String getAuthTokenLabel(String authTokenType) {
  }

  @Override
  public Bundle hasFeatures(AccountAuthenticatorResponse response, Account account, String[] features)
      throws NetworkErrorException {
    //check whether the account supports certain features
  }

  @Override
  public Bundle updateCredentials(AccountAuthenticatorResponse response, Account account, String authTokenType,
      Bundle options) {
    //when the user's session has expired or requires their previously available credentials to be updated, here is the function to do it.
  }
}

建立服務 (Account Manager 框架通過服務介面連線到擴充套件的 AbstractAccountAuthenticator)

public class AuthenticatorService extends Service {

    private AccountAuthenticator authenticator;

    @Override
    public void onCreate(){
        authenticator = new AccountAuthenticator(this);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return authenticator.getIBinder();
    }
}

Authenticator XML 配置 (帳戶管理器框架需要。這是你在設定 - > Android 帳戶中看到的內容)

<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android"
    android:accountType="rename.with.your.applicationid"
    android:icon="@drawable/app_icon"
    android:label="@string/app_name"
    android:smallIcon="@drawable/app_icon" />

對 AndroidManifest.xml 的更改 (將所有上述概念放在一起,使其可通過 AccountManager 以程式設計方式使用)

<application
...>
    <service
        android:name=".authenticator.AccountAuthenticatorService"
        android:exported="false"
        android:process=":authentication">
        <intent-filter>
            <action android:name="android.accounts.AccountAuthenticator"/>
        </intent-filter>
        <meta-data
            android:name="android.accounts.AccountAuthenticator"
            android:resource="@xml/authenticator"/>
    </service>
</application>

下一個示例將包含如何使用此設定。