從 Android 15 Beta 2 開始,搭配使用 androidx.credentials:1.5.0-alpha01,開發人員可以將特定檢視畫面 (例如使用者名稱或密碼欄位) 連結至 Credential Manager 要求。當使用者將焦點放在其中一個檢視畫面時,系統就會將對應的請求傳送至憑證管理工具。系統會從各個供應器匯總產生的憑證,並顯示在自動填入 UI 中,例如鍵盤內嵌建議或下拉式建議。當使用者不小心關閉憑證管理工具帳戶選取器,然後輕觸相關欄位時,這項功能可用作備用選項。
Jetpack androidx.credentials 程式庫是開發人員使用這項功能時的首選端點。
圖 1:使用密碼、密碼金鑰和「使用 Google 帳戶登入」功能的憑證,自動填入結果。
實作
如要使用憑證管理工具在自動填入結果中顯示憑證,請使用標準實作建立 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; } )