從 Android 15 Beta 2 開始,搭配 androidx.credentials:1.5.0-alpha01,開發人員可以將特定檢視區塊 (例如使用者名稱或密碼欄位) 連結至 Credential Manager 要求。當使用者將焦點放在其中一個檢視區塊時,系統會將對應的要求傳送至憑證管理工具。系統會彙整各供應商提供的憑證,並顯示在自動填入 UI 中,例如鍵盤內嵌建議或下拉式建議。如果使用者不小心關閉憑證管理員帳戶選取器,然後輕觸相關欄位,這項功能就能做為備援。
開發人員應使用 Jetpack androidx.credentials 程式庫,做為這項功能的偏好端點。
圖 1:使用密碼、密碼金鑰和「使用 Google 帳戶登入」功能,自動填入憑證的結果。
實作
如要使用 Credential Manager 在自動填入結果中顯示憑證,請使用標準實作建構 GetCredentialRequest
,然後將其設為相關檢視畫面。無論回應來自 getCredential
API 呼叫或 PendingGetCredentialRequest
,處理方式都相同,如下列範例所示。
首先,請建構 GetCredentialRequest
:
// Retrieves the user's saved password for your app.
val getPasswordOption = GetPasswordOption()
// Get a passkey from the user's public key credential provider.
val getPublicKeyCredentialOption = GetPublicKeyCredentialOption(
requestJson = requestJson
)
val getCredRequest = GetCredentialRequest(
listOf(getPasswordOption, getPublicKeyCredentialOption)
)
接著,呼叫 getCredential
API。系統會顯示「憑證管理工具」選取器。
coroutineScope {
try {
val result = credentialManager.getCredential(
context = activityContext, // Use an activity-based context.
request = getCredRequest
)
handleSignIn(result);
} catch (e: GetCredentialException) {
handleFailure(e);
}
}
最後,啟用自動填入功能。將 getCredRequest
設為相關檢視畫面 (例如 username, password
),讓使用者與這些檢視畫面互動時,系統能在自動填入功能中顯示憑證結果。
usernameEditText.pendingGetCredentialRequest = PendingGetCredentialRequest(
getCredRequest) { response -> handleSignIn(response)
}
passwordEditText.pendingGetCredentialRequest = PendingGetCredentialRequest(
getCredRequest) { response -> handleSignIn(response)
}