Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Para integrar o Smart Lock para senhas ao seu app Android, adicione chamadas
à API Credentials
ao fluxo de inicialização e login do seu app. O diagrama a seguir mostra o fluxo de
um app Android típico que usa o Smart Lock para senhas.
Embora existam muitas maneiras de integrar o Smart Lock para senhas,
e as especificações de uma integração dependem da estrutura e da experiência do usuário
do app, mas o fluxo a seguir é recomendado para a maioria dos apps. Os apps que usam esse
fluxo têm estas vantagens na experiência do usuário:
Os usuários existentes do serviço que têm uma única credencial salva são
conectados imediatamente e vão diretamente para a visualização conectada ao
abrir o app.
Os usuários que têm várias credenciais salvas ou que desativaram o login
automático precisam responder a apenas uma caixa de diálogo antes de acessar a visualização de login
do app.
Os usuários que não têm credenciais salvas ou ainda não se inscreveram, podem escolher o nome e o e-mail com um único toque e ser enviados de maneira inteligente para a visualização de login ou de inscrição com essas informações pré-preenchidas.
Quando os usuários saem, o app garante que eles não sejam conectados
novamente automaticamente.
Recuperar credenciais
Quando o app for iniciado, se nenhum usuário já tiver feito login, chame
CredentialsClient.request().
Se o Task for bem-sucedido, acesse as credenciais do usuário com
getResult().getCredential() e use-as para fazer login.
Se Task falhar e
a exceção for uma instância de ResolvableApiException e
getStatusCode() retornar RESOLUTION_REQUIRED,
a entrada do usuário será necessária para escolher uma credencial. Chame
startResolutionForResult() para solicitar que o usuário selecione uma
conta salva. Em seguida, chame
getParcelableExtra(Credential.EXTRA_KEY) para receber as credenciais
do usuário e usá-las para fazer login.
Salvar credenciais
Se o Task falhar com um ApiException e
getStatusCode() retornar SIGN_IN_REQUIRED, o
usuário não terá credenciais salvas e precisará fazer login ou se inscrever manualmente usando
seu fluxo atual de inscrição ou login. Depois que o usuário concluir o login, ofereça a ele a oportunidade de salvar as credenciais para recuperação futura (etapa 5).
Para ajudar o usuário a fazer login ou se inscrever com mais rapidez e facilidade, recupere dicas, como o endereço de e-mail do usuário. O
usuário pode selecionar a dica e pular a etapa de digitar as credenciais. Se o app
exige que os usuários façam login, você pode optar por recuperar dicas imediatamente
após a falha na solicitação de credenciais iniciais. Caso contrário, pode esperar até
que o usuário inicie o fluxo de login ou inscrição.
Chame CredentialsClient.getHintPickerIntent() e inicie a
intent para solicitar que o usuário selecione uma conta. Em seguida, chame
getParcelableExtra(Credential.EXTRA_KEY) para receber a
dica de login.
Se o ID do usuário da dica corresponder a um usuário atual, preencha automaticamente o
formulário de login com ele e permita que o usuário insira a senha para
fazer login.
Se o ID do usuário da dica não corresponder a um usuário atual, preencha
automaticamente o formulário de inscrição com o ID e o nome do usuário e permita que o usuário
crie uma nova conta.
Depois que o usuário fizer login ou criar uma conta, salve o ID
do usuário e a senha com CredentialsClient.save().
Se o usuário tiver feito login com um provedor de identidade federado, como o Login do
Google, crie o objeto Credential com o endereço de e-mail
do usuário como o ID e especifique o provedor de identidade com
setAccountType.
Sair
Quando o usuário sair, chame CredentialsClient.disableAutoSignIn()
para evitar que ele seja conectado de novo imediatamente. Desativar
o login automático também permite que os usuários alternem entre contas com facilidade, por
exemplo, entre contas de trabalho e pessoais ou entre contas em dispositivos compartilhados,
sem precisar reinserir as informações de login.
[null,null,["Última atualização 2025-07-25 UTC."],[[["\u003cp\u003eSmart Lock for Passwords is deprecated; migrate to Credential Manager for enhanced security and user experience with passkeys, passwords, and federated identities.\u003c/p\u003e\n"],["\u003cp\u003eSmart Lock for Passwords integration involves adding the Credentials API to your app's startup and sign-in flow to retrieve and save user credentials.\u003c/p\u003e\n"],["\u003cp\u003eExisting users with saved credentials can experience automatic sign-in, while new users can benefit from pre-filled forms using sign-in hints.\u003c/p\u003e\n"],["\u003cp\u003eEnsure to disable auto-sign-in upon user sign-out to prevent immediate re-authentication and facilitate account switching.\u003c/p\u003e\n"]]],[],null,["# Android integration flow\n\n| **Deprecated:** Smart Lock for Passwords is deprecated. To ensure the continued security and usability of your app, [migrate to\n| Credential Manager](https://developer.android.com/training/sign-in/passkeys/) today. Credential Manager supports passkey, password, and federated identity authentication (such as Sign-in with Google), stronger security, and a more consistent user experience.\n\nTo integrate Smart Lock for Passwords into your Android app, you must add calls\nto the [Credentials API](/android/reference/com/google/android/gms/auth/api/credentials/package-summary)\nto your app's start-up and sign-in flow. The following diagram shows the flow of\na typical Android app that uses Smart Lock for Passwords.\n\nWhile there are many ways to successfully integrate Smart Lock for Passwords,\nand the specifics of an integration depend on the structure and user experience\nof the app, the following flow is recommended for most apps. Apps that use this\nflow have these user experience advantages:\n\n- Existing users of your service that have a single credential saved are immediately signed in, and they will go directly to the signed-in view when they open the app.\n- Users that have multiple credentials saved or that have disabled automatic sign-in need to respond to only one dialog before they go to the app's signed-in view.\n- Users that have no saved credentials or haven't signed up yet can pick their name and email with a single tap and be intelligently sent to either the sign-in or sign-up view, with this information pre-filled.\n- When users sign out, the app ensures they are not automatically signed back in.\n\n[](/static/identity/smartlock-passwords/android/images/smartlock-passwords-flow.png)\n\n### Retrieve credentials\n\n1. When the app starts, if no user is already signed in, call `CredentialsClient.request()`.\n2. If the `Task` is successful, get the user's credentials with `getResult().getCredential()` and use them to sign in.\n3. If the `Task` fails and the exception is an instance of `ResolvableApiException` and `getStatusCode()` returns `RESOLUTION_REQUIRED`, user input is required to pick a credential. Call `startResolutionForResult()` to prompt the user to select a saved account, then call `getParcelableExtra(Credential.EXTRA_KEY)` to get the user's credentials and use them to sign in. If signing in with the retrieved credentials fails because the password is incorrect or the account doesn't exist, delete the credentials from Smart Lock with `CredentialsClient.delete()`.\n\n### Save credentials\n\n4. If the `Task` fails with an `ApiException` and\n `getStatusCode()` returns `SIGN_IN_REQUIRED`, the\n user has no saved credentials and must sign in or sign up manually using\n your current sign-in or sign-up flow. After the user successfully\n completes sign in, you can provide an opportunity for the user to save\n their credentials for future retrieval (step 5).\n\n You can help the user sign in or sign up faster and more\n easily by retrieving sign-in hints, such as the user's email address. The\n user can select the hint and skip typing their credentials. If your app\n requires users to sign in, you might choose to retrieve hints immediately\n after the initial credentials request fails (otherwise, you can wait until\n the user starts the sign-in or sign-up flow).\n 1. Call `CredentialsClient.getHintPickerIntent()` and start the intent to prompt the user to select an account, then call `getParcelableExtra(Credential.EXTRA_KEY)` to get the sign-in hint.\n 2. If the user ID of the hint matches an existing user, pre-fill the sign-in form with it and let the user enter the password to sign in.\n 3. If the user ID of the hint doesn't match an existing user, pre-fill the sign-up form with the user's ID and name, and let the user create a new account.\n5. After the user successfully signs in or creates an account, save the user\n ID and password with `CredentialsClient.save()`.\n\n If the user signed in with a federated identity provider such as Google\n Sign-In, create the `Credential` object with the user's email\n address as the ID and specify the identity provider with\n `setAccountType`.\n\n### Sign out\n\n6. When the user signs out, call `CredentialsClient.disableAutoSignIn()` to prevent the user from being immediately signed back in. Disabling auto-sign-in also enables users to switch between accounts easily---for example, between work and personal accounts, or between accounts on shared devices---without having to re-enter their sign-in information.\n\nReady to integrate Smart Lock for Passwords into your app?\n[Get started](/identity/smartlock-passwords/android/get-started)."]]