> ## Documentation Index
> Fetch the complete documentation index at: https://docs-staging-docs-event-stream-action-templates.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> Get started with Lock for Android, a widget that provides a frictionless login and signup experience for your native Android apps.

# Lock.Android: Get Started

export const AuthCodeBlock = ({filename, icon, language, highlight, children}) => {
  const [displayText, setDisplayText] = useState(children);
  const [copyText, setCopyText] = useState(children);
  const wrapperRef = React.useRef(null);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      if (!window.autorun || !window.rootStore) {
        return;
      }
      unsubscribe = window.autorun(() => {
        let processedChildrenForDisplay = children;
        let processedChildrenForCopy = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
          let displayValue = value;
          if (key === "{yourClientSecret}" && value !== "{yourClientSecret}") {
            displayValue = value.substring(0, 3) + "*****MASKED*****";
          }
          processedChildrenForDisplay = processedChildrenForDisplay.replaceAll(new RegExp(escapedKey, "g"), displayValue);
          processedChildrenForCopy = processedChildrenForCopy.replaceAll(new RegExp(escapedKey, "g"), value);
        }
        setDisplayText(processedChildrenForDisplay);
        setCopyText(processedChildrenForCopy);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  useEffect(() => {
    if (!wrapperRef.current) return;
    const originalWriteText = navigator.clipboard.writeText.bind(navigator.clipboard);
    let isOverriding = false;
    const handleClick = e => {
      const button = e.target.closest('[data-testid="copy-code-button"]');
      if (!button || !wrapperRef.current.contains(button)) return;
      isOverriding = true;
      navigator.clipboard.writeText = text => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
          return originalWriteText(copyText);
        }
        return originalWriteText(text);
      };
      setTimeout(() => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
        }
      }, 100);
    };
    const wrapper = wrapperRef.current;
    wrapper.addEventListener('click', handleClick, true);
    return () => {
      wrapper.removeEventListener('click', handleClick, true);
      if (navigator.clipboard.writeText !== originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
    };
  }, [copyText]);
  return <div ref={wrapperRef}>
      <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
        {displayText}
      </CodeBlock>
    </div>;
};

Lock for Android can integrate into your native Android apps to provide a beautiful way to log your users in and to sign them up in your app. It provides support for social <Tooltip tip="Identity Provider (IdP): Service that stores and manages digital identities." cta="View Glossary" href="/docs/glossary?term=identity+providers">identity providers</Tooltip> such as Facebook, Google, or X, as well as enterprise providers such as Active Directory.

Check out the [Lock.Android repository](https://github.com/auth0/Lock.Android) on GitHub.

## Requirements

To use Lock's UI or your own UI via the [Auth0.Android library](https://github.com/auth0/Auth0.Android) the minimum required Android API level is 21+ and Java version 8 or above. You will also require an Auth0 application of type "Native".

Here’s what you need in `build.gradle` to target Java 8 byte code for the Android and Kotlin plugins respectively.

```kotlin lines theme={null}
android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }
}
```

## Installation

Lock is available in [Maven Central](https://central.sonatype.com/). To start using Lock add these lines to your `build.gradle` dependencies file:

`implementation 'com.auth0.android:lock:3.+'`

You can check for the latest version on the repository [Readme](https://github.com/auth0/Lock.Android#install) or in [Maven](https://central.sonatype.com/artifact/com.auth0.android/lock).

After adding your Gradle dependency, remember to sync your project with Gradle files.

## Dashboard settings

You need to fill in a few settings in your [Auth0 Dashboard](https://manage.auth0.com/#) before you get started.

### Callback URL

Head over to your <Tooltip tip="Auth0 Dashboard: Auth0's main product to configure your services." cta="View Glossary" href="/docs/glossary?term=Auth0+Dashboard">Auth0 Dashboard</Tooltip> and go to the application's settings. Add the following URL to the application's **Allowed Callback URLs**:

`https://{yourDomain}/android/{yourAppPackageName}/callback`

Replace `{yourAppPackageName}` with your actual application's package name, available in your `app/build.gradle` file as the `applicationId` value.

### Keystores and key hashes

Android applications need to be signed before they can be installed on a device. For this purpose, the Android Studio IDE the first time it runs generates a default "Android Debug Keystore" that it will use to sign development builds. This [Keystore](https://developer.android.com/studio/publish/app-signing) will probably be different for your production build, as it will be used to identify you as the developer.

When using the Web Authentication feature (i.e. social connections), Lock will be set up by default to attempt to use Android App Links. This requires an additional setting in the Auth0 application's dashboard. Use our [Android Keystores and Key Hashes Guide](/docs/libraries/auth0-android/android-development-keystores-hashes) to complete this step.

## Implementing Lock (Social, Database, Enterprise)

The following instructions discuss implementing Classic Lock for Android. If you specifically are looking to implement <Tooltip tip="Passwordless: Form of authentication that does not rely on a password as the first factor." cta="View Glossary" href="/docs/glossary?term=Passwordless">Passwordless</Tooltip> Lock for Android, see [Lock.Android: Passwordless](/docs/libraries/lock-android/lock-android-passwordless).

### Configuring the SDK

In your `app/build.gradle` file add the [Manifest Placeholders](https://developer.android.com/build/manage-manifests) for the Auth0 Domain and the Auth0 Scheme properties, which are going to be used internally by the library to register an intent-filter that captures the authentication result.

```kotlin lines theme={null}
plugins {
    id "com.android.application"
    id "kotlin-android"
}

android {
    compileSdkVersion 30
    defaultConfig {
        applicationId "com.auth0.samples"
        minSdkVersion 21
        targetSdkVersion 30
        // ...

        // ---> Add the next line
        manifestPlaceholders = [auth0Domain: "@string/com_auth0_domain", auth0Scheme: "https"]
        // <---
    }
}
```

It's good practice to add these values to the `strings.xml` file as string resources that can be referenced later from the code. This guide will follow that practice.

export const codeExample = `<resources>
    <string name="com_auth0_client_id">{yourClientId}</string>
    <string name="com_auth0_domain">{yourDomain}</string>
</resources>`;

<AuthCodeBlock children={codeExample} language="xml" />

### SDK usage

In the activity where you plan to invoke Lock, create an instance of `Auth0` with your application's information. The easiest way to create it is by passing an Android Context. This will use the values previously defined in the `strings.xml` file. For this to work, the string resources must be defined using the same keys as the ones listed above.

```text lines theme={null}
val account = Auth0(context)
```

Declare an `AuthenticationCallback` implementation that will handle user authentication events. The `Credentials` object returned in successful authentication scenarios will contain the tokens that your application or API will end up consuming. See [Tokens](/docs/secure/tokens) for more specifics.

```kotlin lines theme={null}
private val callback = object : AuthenticationCallback() {
    override fun onAuthentication(credentials: Credentials) {
        // Authenticated
    }

    override fun onError(error: AuthenticationException) {
        // Exception occurred
    }
}
```

Prepare a new Lock instance by using the Builder class to configure it. Provide the account details and the callback implementation declared above. Values like <Tooltip tip="Audience: Unique identifier of the audience for an issued token. Named aud in a token, its value contains the ID of either an application (Client ID) for an ID Token or an API (API Identifier) for an Access Token." cta="View Glossary" href="/docs/glossary?term=audience">audience</Tooltip>, scope, and available connections can be configured here.

When done, build the Lock instance. This instance is meant to be reused and must be disposed of when it is no longer needed. A good place to do this is in your activity's `onDestroy` method.

```kotlin lines expandable theme={null}
// This activity will show Lock
class MyActivity : AppCompatActivity() {

    private lateinit var lock: Lock

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val account = Auth0(this)
        // Instantiate Lock once
        lock = Lock.newBuilder(account, callback)
            // Customize Lock
            .build(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        // Important! Release Lock and its resources
        lock.onDestroy(this)
    }

    private val callback = object : AuthenticationCallback() {
        override fun onAuthentication(credentials: Credentials) {
            // Authenticated
        }

        override fun onError(error: AuthenticationException) {
            // An exception occurred
        }
    }
}
```

Finally, launch the `Lock` widget from inside your activity.

```kotlin lines theme={null}
startActivity(lock.newIntent(this))
```

That's it! Lock will handle the rest for you.

#### Android App Links - Custom Scheme

The Callback URI scheme used in this article and by default by Lock is `https`. This works best for Android Marshmallow (API 23) or newer if you're using [Android App Links](https://developer.android.com/training/app-links), but in previous Android versions, this may show the intent chooser dialog prompting the user to chose either your application or the browser to resolve the intent. This is called the "disambiguation dialog". You can change this behavior by using a custom unique scheme so that the OS opens the link directly with your app.

1. Update the `auth0Scheme` Manifest Placeholder value in the `app/build.gradle` file or directly in the Intent Filter definition in the `AndroidManifest.xml` file by changing the existing scheme to the new one.
2. Update the "Allowed Callback URLs" in your Auth0 Dashboard Application's settings to match URLs that begin with the new scheme.
3. Call `withScheme()` when configuring Lock with the builder, passing the scheme you want to use.

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  The scheme value must be all lowercase. A warning message will be logged if this is not the case and authentication will never complete.
</Callout>

## Lock configuration

For a full list of Lock's configuration options, check out [Lock.Android: Configuration](/docs/libraries/lock-android/lock-android-configuration).

## Error messages

If your callback receives an `AuthenticationException` you can check [source](https://github.com/auth0/Auth0.Android/blob/main/auth0/src/main/java/com/auth0/android/authentication/AuthenticationException.kt) to learn how to identify each error scenario.

## Learn more

* [Lock.Android: Custom Theming](/docs/libraries/lock-android/lock-android-custom-theming)
* [Lock.Android: Configuration](/docs/libraries/lock-android/lock-android-configuration)
* [Lock.Android: Custom Fields at Signup](/docs/libraries/lock-android/lock-android-custom-fields-at-signup)
* [Lock.Android Internationalization](/docs/customize/internationalization-and-localization/lock-android-internationalization)
* [Logout](/docs/authenticate/login/logout)
