从 Android 15 Beta 2 开始,与 androidx.credentials:1.5.0-alpha01 配合使用,开发者可以将特定视图(如用户名或密码字段)与凭据管理器请求关联。当用户将焦点放在这些视图之一上时,相应的请求将发送到凭据管理器。生成的凭据将在提供程序之间聚合,并在自动填充 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; } )