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