### Build and Install Sample Apps Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Build and install various sample applications included in the SDK. ```bash ./gradlew :samples:quickstart:installDebug ``` ```bash ./gradlew :samples:custom-flows:installDebug ``` ```bash ./gradlew :samples:linear-clone:installDebug ``` ```bash ./gradlew :samples:prebuilt-ui:installDebug ``` -------------------------------- ### Install Debug Build via Gradle Source: https://github.com/clerk/clerk-android/blob/main/samples/quickstart/README.md Use the Gradle command line to install the debug build of the quickstart application onto your connected device or emulator. ```bash ./gradlew :samples:quickstart:installDebug ``` -------------------------------- ### Install Debug Build via Gradle Source: https://github.com/clerk/clerk-android/blob/main/samples/linear-clone/README.md Install the debug version of the linear-clone sample application using the Gradle command line. ```bash ./gradlew :samples:linear-clone:installDebug ``` -------------------------------- ### Install Debug Build via Gradle Source: https://github.com/clerk/clerk-android/blob/main/samples/prebuilt-ui/README.md Use the Gradle command line to install the debug build of the prebuilt UI sample onto your Android device or emulator. ```bash ./gradlew :samples:prebuilt-ui:installDebug ``` -------------------------------- ### Install Debug Build using Gradle Source: https://github.com/clerk/clerk-android/blob/main/samples/custom-flows/README.md Install the debug build of the custom-flows sample application using the Gradle command line. This is an alternative to running via Android Studio. ```bash ./gradlew :samples:custom-flows:installDebug ``` -------------------------------- ### Sign up with OAuth Source: https://context7.com/clerk/clerk-android/llms.txt Starts an OAuth sign-up flow. If the account already exists, it automatically transfers to the sign-in flow. ```kotlin viewModelScope.launch { val result = Clerk.auth.signUpWithOAuth(OAuthProvider.GITHUB) when (result) { is ClerkResult.Success -> navigateHome() is ClerkResult.Failure -> showError(result.errorMessage) } } ``` -------------------------------- ### Initialize Clerk SDK in Application Source: https://context7.com/clerk/clerk-android/llms.txt Bootstrap the Clerk SDK by calling `Clerk.initialize` in your `Application.onCreate()` method. This configures the API client and starts loading authentication state. Observe `Clerk.isInitialized` to know when the SDK is ready. ```kotlin class MyApp : Application() { override fun onCreate() { super.onCreate() Clerk.initialize(this, "pk_test_your_publishable_key") Clerk.initialize( context = this, publishableKey = "pk_test_your_publishable_key", options = ClerkConfigurationOptions( enableDebugMode = BuildConfig.DEBUG, proxyUrl = null, telemetryEnabled = true, ), theme = ClerkTheme( colors = ClerkColors( primary = Color(0xFF6C47FF), background = Color.White, ), ), ) } } ``` ```kotlin lifecycleScope.launch { combine(Clerk.isInitialized, Clerk.initializationError) { ready, error -> when { ready -> showApp() error != null -> showRetryScreen(error) else -> showSplash() } }.collect() } ``` ```kotlin if (Clerk.initializationError.value != null && !Clerk.isInitialized.value) { Clerk.reinitialize() } ``` -------------------------------- ### Auth.signUp Source: https://context7.com/clerk/clerk-android/llms.txt Starts a sign-up flow for creating a new user account. Depending on dashboard settings, further verification steps might be required. ```APIDOC ## `Auth.signUp` — Create a new user account Starts a sign-up flow with the provided fields. Depending on your Clerk Dashboard settings, additional verification steps may follow. ```kotlin viewModelScope.launch { val result = Clerk.auth.signUp { email = "newuser@example.com" password = "SecurePassword1!" firstName = "Jane" lastName = "Doe" legalAccepted = true // if ToS/Privacy is required } when (result) { is ClerkResult.Success -> { val signUp = result.value when (signUp.status) { SignUp.Status.COMPLETE -> navigateHome() SignUp.Status.MISSING_REQUIREMENTS -> { // Send verification code to email signUp.sendEmailCode() } else -> { /* handle */ } } } is ClerkResult.Failure -> showError(result.errorMessage) } } ``` ``` -------------------------------- ### Run Code Style and Lint Checks Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Execute these commands to ensure code adheres to style guides and linting rules before committing. ```bash ./gradlew spotlessCheck detekt ``` -------------------------------- ### Initiate Sign-in with Identifier Source: https://context7.com/clerk/clerk-android/llms.txt Start a sign-in attempt using an identifier like email, phone, or username. This method does not automatically send a verification code; you must call `SignIn.sendEmailCode()` or `SignIn.sendPhoneCode()` separately. ```kotlin viewModelScope.launch { when (val result = Clerk.auth.signIn { email = "user@example.com" }) { is ClerkResult.Success -> { val signIn = result.value // Send email code signIn.sendEmailCode() } is ClerkResult.Failure -> { val msg = result.errorMessage // human-readable message showError(msg) } } } ``` -------------------------------- ### Auth.signInWithEnterpriseSso Source: https://context7.com/clerk/clerk-android/llms.txt Starts an Enterprise Single Sign-On (SSO) redirect flow for users with corporate email domains. ```APIDOC ## `Auth.signInWithEnterpriseSso` — Enterprise SSO sign-in Initiates an Enterprise SSO redirect flow for a corporate email domain. ```kotlin viewModelScope.launch { val result = Clerk.auth.signInWithEnterpriseSso { email = "employee@corp.com" } when (result) { is ClerkResult.Success -> navigateHome() is ClerkResult.Failure -> showError(result.errorMessage) } } ``` ``` -------------------------------- ### OAuthProvider Enum Usage Source: https://context7.com/clerk/clerk-android/llms.txt Use OAuthProvider to interact with supported social login providers. Convert strategy strings to providers, get display names, and list configured social providers for UI elements. ```kotlin // All available providers: // FACEBOOK, GOOGLE, GITHUB, GITLAB, DISCORD, TWITTER, TWITCH, // LINKEDIN, LINKEDIN_OIDC, MICROSOFT, APPLE, SPOTIFY, SLACK, // DROPBOX, ATLASSIAN, BITBUCKET, NOTION, BOX, XERO, LINEAR, // HUBSPOT, TIKTOK, INSTAGRAM, COINBASE, HUGGING_FACE, VERCEL, CUSTOM // Convert from strategy string (e.g. from environment config) val provider = OAuthProvider.fromStrategy("oauth_google") // → GOOGLE // Get display name val name = OAuthProvider.GITHUB.providerName // → "GitHub" // Display configured social providers in UI val socialButtons = Clerk.socialProviders.toOAuthProvidersList() socialButtons.forEach { provider -> SocialButton( name = provider.providerName, logoUrl = provider.logoUrl, onClick = { viewModel.signInWithOAuth(provider) }, ) } ``` -------------------------------- ### Build Entire Project Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Use this command to build the entire Clerk Android project. ```bash ./gradlew build ``` -------------------------------- ### Sign in with Email and Password Source: https://context7.com/clerk/clerk-android/llms.txt Perform a one-step sign-in when both the user's identifier (email, username, or phone) and password are known. ```kotlin viewModelScope.launch { val result = Clerk.auth.signInWithPassword { identifier = "user@example.com" // or username / phone number password = "s3cr3tP@ssw0rd" } when (result) { is ClerkResult.Success -> navigateHome() is ClerkResult.Failure -> showError(result.errorMessage) } } ``` -------------------------------- ### Sign up with Email and Password Source: https://context7.com/clerk/clerk-android/llms.txt Initiates a sign-up flow for new users. Depending on dashboard settings, further verification steps like email code sending may be required. ```kotlin viewModelScope.launch { val result = Clerk.auth.signUp { email = "newuser@example.com" password = "SecurePassword1!" firstName = "Jane" lastName = "Doe" legalAccepted = true // if ToS/Privacy is required } when (result) { is ClerkResult.Success -> { val signUp = result.value when (signUp.status) { SignUp.Status.COMPLETE -> navigateHome() SignUp.Status.MISSING_REQUIREMENTS -> { // Send verification code to email signUp.sendEmailCode() } else -> { /* handle */ } } } is ClerkResult.Failure -> showError(result.errorMessage) } } ``` -------------------------------- ### Running All Pre-Commit Checks Source: https://github.com/clerk/clerk-android/blob/main/CLAUDE.md Execute all necessary checks, including spotless, detekt, lint, and unit tests, before submitting code for review. ```bash spotlessCheck detekt lint relevant test tasks ``` -------------------------------- ### Auth.signUpWithOAuth Source: https://context7.com/clerk/clerk-android/llms.txt Initiates an OAuth sign-up flow. If the account already exists, it automatically transfers to the sign-in flow. ```APIDOC ## `Auth.signUpWithOAuth` — OAuth-based sign-up Initiates an OAuth sign-up flow; transfers automatically to sign-in if the account already exists. ```kotlin viewModelScope.launch { val result = Clerk.auth.signUpWithOAuth(OAuthProvider.GITHUB) when (result) { is ClerkResult.Success -> navigateHome() is ClerkResult.Failure -> showError(result.errorMessage) } } ``` ``` -------------------------------- ### Run UI Snapshot Tests (Paparazzi) with Gradle Source: https://github.com/clerk/clerk-android/blob/main/CLAUDE.md Execute UI snapshot tests using the Paparazzi library. This helps ensure UI consistency across different devices and configurations. ```bash ./gradlew :source:ui:testDebug ``` ```bash ./gradlew :source:ui:recordPaparazziDebug ``` -------------------------------- ### Generate Dokka API Documentation Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Generate API documentation using Dokka. The output will be placed in the `docs/` directory. ```bash ./gradlew dokkaGenerate ``` ```bash ./gradlew dokkaGenerateHtml ``` -------------------------------- ### SignUp — Manual sign-up flow with verification Source: https://context7.com/clerk/clerk-android/llms.txt Represents an in-progress registration, exposing methods to prepare and attempt verification, and update user details. ```APIDOC ## SignUp Represents an in-progress registration, exposing `prepareVerification`, `attemptVerification`, `update`, and convenience helpers. ### Methods - `create(CreateParams)`: Initiates a new sign-up attempt. - `sendEmailCode()`: Sends an email verification code. - `attemptVerification(AttemptVerificationParams)`: Attempts to verify the provided code. - `update(UpdateParams)`: Updates user profile information during sign-up. ### Status - `COMPLETE`: Sign-up is successful. - `MISSING_REQUIREMENTS`: Additional fields are required. ### Example Usage ```kotlin viewModelScope.launch { val result = SignUp.create( SignUp.CreateParams.Standard( emailAddress = "newuser@example.com", password = "StrongPass!1", firstName = "John", ) ) val signUp = (result as ClerkResult.Success).value signUp.sendEmailCode() val verify = signUp.attemptVerification(SignUp.AttemptVerificationParams.EmailCode(code = "987654")) val updated = (verify as ClerkResult.Success).value when (updated.status) { SignUp.Status.COMPLETE -> navigateHome() SignUp.Status.MISSING_REQUIREMENTS -> { val nextField = updated.firstFieldToCollect } else -> handleError() } } ``` ``` -------------------------------- ### Clerk.initialize Source: https://context7.com/clerk/clerk-android/llms.txt Initializes the Clerk SDK with a publishable key. This function must be called before any other SDK function, typically in your Application's onCreate() method. You can also provide additional configuration options and a custom theme. ```APIDOC ## Clerk.initialize — SDK initialization Bootstraps the Clerk SDK, configures the API client, and begins loading authentication state. Must be called before any other SDK function, typically in `Application.onCreate()`. ```kotlin // Basic initialization Clerk.initialize(this, "pk_test_your_publishable_key") // With options and custom theme Clerk.initialize( context = this, publishableKey = "pk_test_your_publishable_key", options = ClerkConfigurationOptions( enableDebugMode = BuildConfig.DEBUG, proxyUrl = null, // set if behind a reverse proxy telemetryEnabled = true, ), theme = ClerkTheme( colors = ClerkColors( primary = Color(0xFF6C47FF), background = Color.White, ), ), ) ``` Observe `Clerk.isInitialized` to know when the SDK is ready. Retry after network failure using `Clerk.reinitialize()` if `Clerk.initializationError` is not null. ``` -------------------------------- ### Run All Tests Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Execute all unit tests across the Clerk Android project. ```bash ./gradlew test ``` -------------------------------- ### Add Clerk Publishable Key Source: https://github.com/clerk/clerk-android/blob/main/samples/prebuilt-ui/README.md Configure your Clerk publishable key in the `gradle.properties` file. Ensure you replace the placeholder with your actual key. ```properties PREBUILT_UI_CLERK_PUBLISHABLE_KEY=pk_test_your_publishable_key_here ``` -------------------------------- ### Configure Clerk Publishable Key Source: https://github.com/clerk/clerk-android/blob/main/samples/quickstart/README.md Add your Clerk publishable key to the `gradle.properties` file. Ensure you replace the placeholder with your actual key from the Clerk dashboard. ```properties QUICKSTART_CLERK_PUBLISHABLE_KEY=pk_test_your_publishable_key_here ``` -------------------------------- ### Auth.signInWithOtp Source: https://context7.com/clerk/clerk-android/llms.txt Creates a sign-in and immediately sends a One-Time Password (OTP) via email or phone. The code must then be verified. ```APIDOC ## `Auth.signInWithOtp` — One-tap OTP sign-in Creates a sign-in **and** immediately sends the verification code. Caller only needs to collect the code and call `verifyCode`. ```kotlin viewModelScope.launch { // Via email val result = Clerk.auth.signInWithOtp { email = "user@example.com" } // Via phone // val result = Clerk.auth.signInWithOtp { phone = "+14155552671" } when (result) { is ClerkResult.Success -> { val signIn = result.value // Collect code from user then: when (val verify = signIn.attemptFirstFactor( SignIn.AttemptFirstFactorParams.EmailCode(code = "123456") )) { is ClerkResult.Success -> navigateHome() is ClerkResult.Failure -> showError(verify.errorMessage) } } is ClerkResult.Failure -> showError(result.errorMessage) } } ``` ``` -------------------------------- ### Manual Multi-Step Sign-In Flow with Clerk Android Source: https://context7.com/clerk/clerk-android/llms.txt Implement a multi-step sign-in process including first and second factor authentication. Ensure the `SignIn` object is successfully created before proceeding with factor attempts. ```kotlin viewModelScope.launch { // Step 1: Create val createResult = SignIn.create(SignIn.CreateParams.Strategy.EmailCode("user@example.com")) val signIn = (createResult as ClerkResult.Success).value // Step 2: Prepare first factor (send code) signIn.sendEmailCode() // or: signIn.sendPhoneCode() // Step 3: Attempt first factor val attempt = signIn.attemptFirstFactor( SignIn.AttemptFirstFactorParams.EmailCode(code = "654321") ) val updated = (attempt as ClerkResult.Success).value when (updated.status) { SignIn.Status.COMPLETE -> navigateHome() SignIn.Status.NEEDS_SECOND_FACTOR -> { // Step 4 (MFA): prepare second factor updated.prepareSecondFactor() // Step 5: attempt second factor val mfa = updated.attemptSecondFactor( SignIn.AttemptSecondFactorParams.PhoneCode(code = "112233") ) if ((mfa as? ClerkResult.Success)?.value?.status == SignIn.Status.COMPLETE) { navigateHome() } } else -> handleError() } } ``` -------------------------------- ### Run UI Snapshot Tests Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Execute UI snapshot tests using Paparazzi for the UI module. Use `recordPaparazziDebug` to update snapshots. ```bash ./gradlew :source:ui:testDebug ``` ```bash ./gradlew :source:ui:recordPaparazziDebug # Update snapshots ``` -------------------------------- ### Assemble Without Tests Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Assemble the project artifacts without running any tests. ```bash ./gradlew assemble ``` -------------------------------- ### Manage Organizations: Create, Update, and Invite Source: https://context7.com/clerk/clerk-android/llms.txt Full lifecycle management for organizations, including creation, updating names/slugs, uploading logos, inviting members (single and bulk), managing domains, and deleting organizations. Uses `viewModelScope`. ```kotlin viewModelScope.launch { // Create val result = Organization.create(name = "Acme Corp", slug = "acme-corp") val org = (result as ClerkResult.Success).value // Update name/slug org.update(name = "Acme Corporation") // Upload logo org.updateLogo(File(cacheDir, "logo.png")) // Get members (paginated) val members = org.getOrganizationMemberships(limit = 50, offset = 0) // Invite someone org.createInvitation(emailAddress = "new@example.com", role = "org:member") // Bulk invite org.bulkCreateInvitations( emailAddresses = listOf("a@example.com", "b@example.com"), role = "org:member", ) // Manage domains (auto-enroll users by email domain) org.createDomain(name = "acme.com") val domains = org.getDomains() // Remove member org.removeMember(userId = "user_abc") // Delete org org.delete() } ``` -------------------------------- ### Format Code Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Apply code formatting rules to the entire project. This must pass before committing. ```bash ./gradlew spotlessApply ``` -------------------------------- ### Authentication Flow Diagrams Source: https://github.com/clerk/clerk-android/blob/main/CLAUDE.md Illustrates the high-level architecture for sign-in and sign-up flows, detailing the sequence of views and operations. ```plaintext AuthStartView → SignIn.create(identifier) → First Factor (password/code/passkey) → Optional Second Factor (MFA) → Session Created ``` ```plaintext AuthStartView → SignUp.create(fields) → Collect Required Fields → Verify Email/Phone → Complete Profile → Session Created ``` -------------------------------- ### Auth.signUpWithGoogleOneTap Source: https://context7.com/clerk/clerk-android/llms.txt Uses the native Google One Tap credential flow for sign-up. It automatically transitions to sign-in if an existing Google account is detected. ```APIDOC ## `Auth.signUpWithGoogleOneTap` — Google One Tap sign-up Uses the native Google One Tap credential flow, starting from sign-up and auto-transferring to sign-in if an existing Google account is detected. ```kotlin viewModelScope.launch { val result = Clerk.auth.signUpWithGoogleOneTap() when (result) { is ClerkResult.Success -> navigateHome() is ClerkResult.Failure -> showError(result.errorMessage) } } ``` ``` -------------------------------- ### One-tap OTP Sign-in Source: https://context7.com/clerk/clerk-android/llms.txt Initiates a sign-in and immediately sends a One-Time Password (OTP) via email or phone. You then collect the code from the user and call `attemptFirstFactor` to verify. ```kotlin viewModelScope.launch { // Via email val result = Clerk.auth.signInWithOtp { email = "user@example.com" } // Via phone // val result = Clerk.auth.signInWithOtp { phone = "+14155552671" } when (result) { is ClerkResult.Success -> { val signIn = result.value // Collect code from user then: when (val verify = signIn.attemptFirstFactor( SignIn.AttemptFirstFactorParams.EmailCode(code = "123456") )) { is ClerkResult.Success -> navigateHome() is ClerkResult.Failure -> showError(verify.errorMessage) } } is ClerkResult.Failure -> showError(result.errorMessage) } } ``` -------------------------------- ### Add Clerk Publishable Key Source: https://github.com/clerk/clerk-android/blob/main/samples/linear-clone/README.md Add your Clerk publishable key to the gradle.properties file. Replace the placeholder with your actual key. ```properties LINEAR_CLONE_CLERK_PUBLISHABLE_KEY=pk_test_your_publishable_key_here ``` -------------------------------- ### Manual Sign-Up Flow with Verification in Clerk Android Source: https://context7.com/clerk/clerk-android/llms.txt Handles the user sign-up process, including sending verification codes and attempting verification. This flow supports collecting additional user information if requirements are missing. ```kotlin viewModelScope.launch { // Step 1: Create val result = SignUp.create( SignUp.CreateParams.Standard( emailAddress = "newuser@example.com", password = "StrongPass!1", firstName = "John", ) ) val signUp = (result as ClerkResult.Success).value // Step 2: Send email verification signUp.sendEmailCode() // Step 3: Attempt verification val verify = signUp.attemptVerification( SignUp.AttemptVerificationParams.EmailCode(code = "987654") ) val updated = (verify as ClerkResult.Success).value when (updated.status) { SignUp.Status.COMPLETE -> navigateHome() SignUp.Status.MISSING_REQUIREMENTS -> { // More fields needed; inspect updated.missingFields val nextField = updated.firstFieldToCollect } else -> handleError() } } ``` -------------------------------- ### SignIn — Manual multi-step sign-in flow Source: https://context7.com/clerk/clerk-android/llms.txt Represents an in-progress authentication attempt, exposing methods to prepare and attempt first and second factors for sign-in. ```APIDOC ## SignIn Represents an in-progress authentication attempt, exposing `prepareFirstFactor`, `attemptFirstFactor`, `prepareSecondFactor`, `attemptSecondFactor`, and convenience helpers. ### Methods - `create(CreateParams)`: Initiates a new sign-in attempt. - `sendEmailCode()`: Sends an email verification code. - `sendPhoneCode()`: Sends an SMS verification code. - `attemptFirstFactor(AttemptFirstFactorParams)`: Attempts to verify the first factor (e.g., email code). - `prepareSecondFactor()`: Prepares for the second factor authentication. - `attemptSecondFactor(AttemptSecondFactorParams)`: Attempts to verify the second factor. ### Status - `COMPLETE`: Sign-in is successful. - `NEEDS_SECOND_FACTOR`: Requires second-factor authentication. ### Example Usage ```kotlin viewModelScope.launch { val createResult = SignIn.create(SignIn.CreateParams.Strategy.EmailCode("user@example.com")) val signIn = (createResult as ClerkResult.Success).value signIn.sendEmailCode() val attempt = signIn.attemptFirstFactor(SignIn.AttemptFirstFactorParams.EmailCode(code = "654321")) val updated = (attempt as ClerkResult.Success).value when (updated.status) { SignIn.Status.COMPLETE -> navigateHome() SignIn.Status.NEEDS_SECOND_FACTOR -> { updated.prepareSecondFactor() val mfa = updated.attemptSecondFactor(SignIn.AttemptSecondFactorParams.PhoneCode(code = "112233")) if ((mfa as? ClerkResult.Success)?.value?.status == SignIn.Status.COMPLETE) { navigateHome() } } else -> handleError() } } ``` ``` -------------------------------- ### Sign in with Ticket Source: https://context7.com/clerk/clerk-android/llms.txt Use this method to sign in a user with a pre-generated authentication ticket. Ensure the ticket is correctly extracted from the intent data. ```kotlin viewModelScope.launch { val ticket = intent.data?.getQueryParameter("__clerk_ticket") ?: return@launch val result = Clerk.auth.signInWithTicket(ticket) when (result) { is ClerkResult.Success -> navigateHome() is ClerkResult.Failure -> showError(result.errorMessage) } } ``` -------------------------------- ### Clone Clerk Android Repository Source: https://github.com/clerk/clerk-android/blob/main/samples/custom-flows/README.md Clone the Clerk Android repository to your local machine. This is the first step to setting up the custom flows sample. ```bash git clone https://github.com/clerk/clerk-android.git cd clerk-android ``` -------------------------------- ### OAuth / Social Sign-in Source: https://context7.com/clerk/clerk-android/llms.txt Launches a browser-based OAuth redirect flow for social providers like Google. Handles the callback via deep linking in your Activity. ```kotlin viewModelScope.launch { val result = Clerk.auth.signInWithOAuth(OAuthProvider.GOOGLE) when (result) { is ClerkResult.Success -> { val oauthResult = result.value // oauthResult.signIn or oauthResult.signUp depending on transfer } is ClerkResult.Failure -> showError(result.errorMessage) } } // Handle the deep-link callback in your Activity/Fragment override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) Clerk.auth.handle(intent.data) } ``` -------------------------------- ### Run Android Lint Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Perform Android lint checks on the project. ```bash ./gradlew lint ``` ```bash ./gradlew :source:api:lintDebug ``` -------------------------------- ### Run Tests for Specific Module Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Execute unit tests for a particular module, like the API or UI. ```bash ./gradlew :source:api:test ``` ```bash ./gradlew :source:ui:test ``` -------------------------------- ### Run Detekt Static Analysis Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Execute Detekt for static code analysis. The configuration is located at `config/detekt/detekt.yml`. ```bash ./gradlew detekt ``` -------------------------------- ### Integrate AuthView for Sign-in/Sign-up Source: https://context7.com/clerk/clerk-android/llms.txt Use AuthView as a self-contained Composable for complete sign-in and sign-up flows. It handles internal navigation and calls onAuthComplete upon successful authentication. You can pre-fill the identifier field and configure options like Google One Tap. ```kotlin @Composable fun LoginScreen(onAuthenticated: () -> Unit) { AuthView( modifier = Modifier.fillMaxSize(), clerkTheme = ClerkTheme( colors = ClerkColors(primary = Color(0xFF6C47FF)), ), initialIdentifier = "user@example.com", // pre-fill identifier field persistIdentifiers = true, preferGoogleOneTap = true, startSocialOAuthAsSignUp = false, onAuthComplete = onAuthenticated, ) } // Typical integration in a NavHost: composable("login") { AuthView(onAuthComplete = { navController.navigate("home") }) } ``` -------------------------------- ### Check Code Formatting Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Check if the code adheres to the project's formatting standards without applying changes. ```bash ./gradlew spotlessCheck ``` -------------------------------- ### Manage User MFA: TOTP and Backup Codes Source: https://context7.com/clerk/clerk-android/llms.txt Set up and verify TOTP for multi-factor authentication, generate backup codes for account recovery, and disable TOTP. Also lists available phone numbers for SMS MFA enrollment. Requires `viewModelScope`. ```kotlin viewModelScope.launch { val user = Clerk.user ?: return@launch // Set up TOTP authenticator app val totpResult = user.createTotp() val totp = (totpResult as ClerkResult.Success).value // totp.secret — show to user or encode as QR // totp.uri — otpauth:// URI for QR scanning // Verify the TOTP code from the authenticator app val verifyResult = user.attemptTotpVerification(code = "123456") // Generate backup codes val backupResult = user.createBackupCodes() val codes = (backupResult as ClerkResult.Success).value.codes // Disable TOTP user.disableTotp() // Available phone numbers for SMS MFA enrollment val mfaPhones = user.phoneNumbersAvailableForMfa() } ``` -------------------------------- ### Sign up with Google One Tap Source: https://context7.com/clerk/clerk-android/llms.txt Utilizes the native Google One Tap credential flow for sign-up. It automatically transitions to sign-in if an existing Google account is detected. ```kotlin viewModelScope.launch { val result = Clerk.auth.signUpWithGoogleOneTap() when (result) { is ClerkResult.Success -> navigateHome() is ClerkResult.Failure -> showError(result.errorMessage) } } ``` -------------------------------- ### Build Specific Modules Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Build individual modules within the Clerk Android project, such as the API or UI components. ```bash ./gradlew :source:api:build ``` ```bash ./gradlew :source:ui:build ``` -------------------------------- ### Auth.signInWithOAuth Source: https://context7.com/clerk/clerk-android/llms.txt Launches a browser-based OAuth flow for social sign-in providers. Handles the callback after redirection. ```APIDOC ## `Auth.signInWithOAuth` — OAuth / social sign-in Launches browser-based OAuth redirect for the given provider and returns the result after the callback is handled. ```kotlin viewModelScope.launch { val result = Clerk.auth.signInWithOAuth(OAuthProvider.GOOGLE) when (result) { is ClerkResult.Success -> { val oauthResult = result.value // oauthResult.signIn or oauthResult.signUp depending on transfer } is ClerkResult.Failure -> showError(result.errorMessage) } } // Handle the deep-link callback in your Activity/Fragment override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) Clerk.auth.handle(intent.data) } ``` ``` -------------------------------- ### Publish UI to Maven Central Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Publish the UI module to Maven Central. This command is intended for maintainers only. ```bash ./gradlew :source:ui:publishToMavenCentral ``` -------------------------------- ### Auth.signInWithPasskey Source: https://context7.com/clerk/clerk-android/llms.txt Initiates passkey authentication using the Android Credential Manager, requiring a foreground Activity. ```APIDOC ## `Auth.signInWithPasskey` — Passkey authentication Triggers the Android Credential Manager to authenticate the user with a registered passkey (biometric / device PIN). Requires a foreground `Activity`. ```kotlin viewModelScope.launch { val result = Clerk.auth.signInWithPasskey() when (result) { is ClerkResult.Success -> navigateHome() is ClerkResult.Failure -> showError(result.errorMessage) } } ``` ``` -------------------------------- ### Auth.signInWithPassword Source: https://context7.com/clerk/clerk-android/llms.txt Performs a one-step sign-in using both the user's identifier and password. ```APIDOC ## `Auth.signInWithPassword` — Password authentication One-step sign-in when both identifier and password are known upfront. ```kotlin viewModelScope.launch { val result = Clerk.auth.signInWithPassword { identifier = "user@example.com" // or username / phone number password = "s3cr3tP@ssw0rd" } when (result) { is ClerkResult.Success -> navigateHome() is ClerkResult.Failure -> showError(result.errorMessage) } } ``` ``` -------------------------------- ### Update Paparazzi Snapshots Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Run this command to update UI snapshot tests after making changes to Compose components. ```bash ./gradlew :source:ui:recordPaparazziDebug ``` -------------------------------- ### Verify Maven Publishing Metadata Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Locally verify the Maven publishing metadata for the API module. ```bash ./gradlew :source:api:publishToMavenLocal ``` -------------------------------- ### Run Single Test Class Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Execute a specific test class within a module. ```bash ./gradlew :source:api:test --tests "com.clerk.sdk.SpecificTest" ``` -------------------------------- ### Auth.signIn Source: https://context7.com/clerk/clerk-android/llms.txt Initiates a sign-in attempt using an identifier (email, phone, or username). Requires a subsequent call to send a verification code. ```APIDOC ## `Auth.signIn` — Sign in with identifier Creates a sign-in attempt for a given identifier (email, phone, or username). Does **not** send a verification code automatically; call `SignIn.sendEmailCode()` or `SignIn.sendPhoneCode()` afterwards. ```kotlin viewModelScope.launch { when (val result = Clerk.auth.signIn { email = "user@example.com" }) { is ClerkResult.Success -> { val signIn = result.value // Send email code signIn.sendEmailCode() } is ClerkResult.Failure -> { val msg = result.errorMessage // human-readable message showError(msg) } } } ``` ``` -------------------------------- ### Register a Passkey for the User Source: https://context7.com/clerk/clerk-android/llms.txt Creates a new passkey credential for the current user using the Android Credential Manager. Handles success and failure outcomes. ```kotlin viewModelScope.launch { val user = Clerk.user ?: return@launch val result = user.createPasskey() when (result) { is ClerkResult.Success -> showSuccess("Passkey registered!") is ClerkResult.Failure -> showError(result.errorMessage) } } ``` -------------------------------- ### Manage User Emails and Phone Numbers Source: https://context7.com/clerk/clerk-android/llms.txt Add and verify email addresses and phone numbers for the current user. Lists all associated emails and phone numbers. Requires the `viewModelScope` for coroutine launching. ```kotlin viewModelScope.launch { val user = Clerk.user ?: return@launch // Add email val emailResult = user.createEmailAddress("second@example.com") val emailAddress = (emailResult as ClerkResult.Success).value // The email needs verification — use emailAddress extensions: // emailAddress.prepareVerification(...) // emailAddress.attemptVerification(...) // Add phone val phoneResult = user.createPhoneNumber("+14155551234") // List all emails / phones val emails = user.emailAddresses() val phones = user.phoneNumbers() // Get all sessions val activeSessions = user.activeSessions() val allSessions = user.allSessions() } ``` -------------------------------- ### Publish API to Maven Central Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Publish the API module to Maven Central. This command is intended for maintainers only. ```bash ./gradlew :source:api:publishToMavenCentral ``` -------------------------------- ### User - TOTP / Backup codes (MFA) Source: https://context7.com/clerk/clerk-android/llms.txt Manage Multi-Factor Authentication (MFA) settings for the user, including setting up TOTP, verifying codes, generating backup codes, and disabling TOTP. ```APIDOC ## `User` — TOTP / Backup codes (MFA) Create and verify TOTP, or generate backup codes for account recovery. ```kotlin viewModelScope.launch { val user = Clerk.user ?: return@launch // Set up TOTP authenticator app val totpResult = user.createTotp() val totp = (totpResult as ClerkResult.Success).value // totp.secret — show to user or encode as QR // totp.uri — otpauth:// URI for QR scanning // Verify the TOTP code from the authenticator app val verifyResult = user.attemptTotpVerification(code = "123456") // Generate backup codes val backupResult = user.createBackupCodes() val codes = (backupResult as ClerkResult.Success).value.codes // Disable TOTP user.disableTotp() // Available phone numbers for SMS MFA enrollment val mfaPhones = user.phoneNumbersAvailableForMfa() } ``` ``` -------------------------------- ### Run Android Instrumentation Tests Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Execute Android instrumentation tests on connected devices or emulators. ```bash ./gradlew connectedAndroidTest ``` ```bash ./gradlew :source:api:connectedDebugAndroidTest ``` -------------------------------- ### Custom Theming with ClerkTheme Source: https://context7.com/clerk/clerk-android/llms.txt Define a custom theme using ClerkTheme, ClerkColors, ClerkDesign, and ClerkTypography for global or scoped theming. This allows you to override colors, design properties like border radius and spacing, and typography. ```kotlin val brandTheme = ClerkTheme( // Applied to both light and dark modes: colors = ClerkColors( primary = Color(0xFF6C47FF), background = Color(0xFFF9F9F9), foreground = Color(0xFF0D0D0D), danger = Color(0xFFEF4444), success = Color(0xFF22C55E), mutedForeground = Color(0xFF6B7280), border = Color(0xFFE5E7EB), ), // Light-mode only overrides: lightColors = ClerkColors(background = Color.White), // Dark-mode only overrides: darkColors = ClerkColors(background = Color(0xFF1C1C1E)), design = ClerkDesign( borderRadius = ClerkBorderRadius(base = 8.dp), spacingUnit = 4.dp, ), typography = ClerkTypography( fontFamily = FontFamily(Font(R.font.inter_regular)), ), ) // Initialize globally Clerk.initialize(context, publishableKey, theme = brandTheme) // Or scope to a single composable AuthView(clerkTheme = brandTheme) UserButton(clerkTheme = brandTheme) ``` -------------------------------- ### Result Handling Pattern Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Demonstrates the pattern for handling results from Clerk SDK operations, using a sealed interface for success and failure states. ```kotlin when (val result = signIn.attemptFirstFactor(...)) { is ClerkResult.Success -> // Handle success is ClerkResult.Failure -> // Handle error } ``` -------------------------------- ### Enterprise SSO Sign-in Source: https://context7.com/clerk/clerk-android/llms.txt Initiates an Enterprise Single Sign-On (SSO) redirect flow for users with corporate email domains. This directs them to their organization's identity provider. ```kotlin viewModelScope.launch { val result = Clerk.auth.signInWithEnterpriseSso { email = "employee@corp.com" } when (result) { is ClerkResult.Success -> navigateHome() is ClerkResult.Failure -> showError(result.errorMessage) } } ``` -------------------------------- ### Add Clerk Android SDK Dependencies Source: https://context7.com/clerk/clerk-android/llms.txt Add the Clerk Android SDK artifacts to your app's `build.gradle.kts` file. Choose either the API-only version for custom UI or the version with prebuilt Compose UI components. ```kotlin dependencies { implementation("com.clerk:clerk-android-api:1.0.16") } ``` ```kotlin dependencies { implementation("com.clerk:clerk-android-ui:1.0.16") } ``` -------------------------------- ### Supply Foreground Activity to Clerk Source: https://context7.com/clerk/clerk-android/llms.txt Call `Clerk.attachActivity(this)` in your `Activity.onCreate()` to provide the current foreground `Activity`. This is necessary for Clerk to use Credential Manager for features like Google One Tap and passkeys. ```kotlin class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Clerk.attachActivity(this) } } ``` -------------------------------- ### Connect OAuth Account to Existing User Source: https://context7.com/clerk/clerk-android/llms.txt Links an external social account (e.g., GitHub) to an already signed-in user. Requires specifying the OAuth provider and a redirect URL. ```kotlin viewModelScope.launch { val user = Clerk.user ?: return@launch val result = user.createExternalAccount( User.CreateExternalAccountParams( provider = OAuthProvider.GITHUB, redirectUrl = "yourapp://oauth-callback", ) ) val externalAccount = (result as ClerkResult.Success).value // Redirect user to externalAccount.verification?.externalVerificationRedirectUrl } ``` -------------------------------- ### Add Clerk Android API Dependency Source: https://github.com/clerk/clerk-android/blob/main/README.md Include this dependency if you are building your own custom UI for authentication flows. ```kotlin dependencies { implementation("com.clerk:clerk-android-api:0.1.28") } ``` -------------------------------- ### Integrate OrganizationSwitcher for Organization Management Source: https://context7.com/clerk/clerk-android/llms.txt Use OrganizationSwitcher in your top app bar to display the active organization and allow users to switch between organizations via a bottom sheet. It can optionally render a UserButton. ```kotlin @Composable fun OrgTopBar() { TopAppBar( title = { OrganizationSwitcher( modifier = Modifier.fillMaxWidth(), clerkTheme = myTheme, showUserButton = true, onOrganizationChanged = { refreshData() }, ) } ) } ``` -------------------------------- ### Session.fetchToken Source: https://context7.com/clerk/clerk-android/llms.txt Fetches a JWT directly from a Session object, with options for template, cache control, and expiration buffer. ```APIDOC ## Session.fetchToken Extension function on `Session` to retrieve a fresh JWT, with optional template and cache control. ### Parameters - `template` (String, Optional): The JWT template to use. - `skipCache` (Boolean, Optional): Whether to skip the cache. - `expirationBuffer` (Int, Optional): The buffer in seconds before token expiration. ### Example Usage ```kotlin val session = Clerk.session ?: return val result = session.fetchToken( GetTokenOptions( template = "hasura", skipCache = false, expirationBuffer = 30, // seconds ) ) when (result) { is ClerkResult.Success -> { val jwt = result.value.jwt } is ClerkResult.Failure -> Log.e("Token", "Failed to fetch token") } ``` ``` -------------------------------- ### Handle ClerkResult with Pattern Matching Source: https://github.com/clerk/clerk-android/blob/main/AGENTS.md Use pattern matching with `when` to safely handle the success or failure of an API call returning a ClerkResult. Access the data on success or the error on failure. ```kotlin when (val result = apiCall()) { is ClerkResult.Success -> result.data // Access successful result is ClerkResult.Failure -> result.error // Handle error } ``` -------------------------------- ### Auth.events Source: https://context7.com/clerk/clerk-android/llms.txt Subscribe to authentication lifecycle events like SignedIn, SignedOut, SessionChanged, and Error for analytics or UI updates. ```APIDOC ## `Auth.events` — Authentication event stream A `SharedFlow` that emits lifecycle events: `SignedIn`, `SignedOut`, `SessionChanged`, and `Error`. Use this for analytics, navigation triggers, or toast notifications. ```kotlin lifecycleScope.launch { Clerk.auth.events.collect { event -> when (event) { is AuthEvent.SignedIn -> Log.i("Auth", "Signed in as ${event.user.primaryEmailAddress?.emailAddress}") is AuthEvent.SignedOut -> navController.navigate("login") is AuthEvent.SessionChanged -> Log.d("Auth", "Active session: ${event.session?.id}") is AuthEvent.Error -> showSnackbar(event.message ?: "Auth error") } } } ``` ``` -------------------------------- ### Organization - Create and manage organizations Source: https://context7.com/clerk/clerk-android/llms.txt Manage organizations, including creation, updates, logo uploads, member management, invitations, domain management, and deletion. ```APIDOC ## `Organization` — Create and manage organizations Companion object and extension functions for full organization lifecycle management. ```kotlin viewModelScope.launch { // Create val result = Organization.create(name = "Acme Corp", slug = "acme-corp") val org = (result as ClerkResult.Success).value // Update name/slug org.update(name = "Acme Corporation") // Upload logo org.updateLogo(File(cacheDir, "logo.png")) // Get members (paginated) val members = org.getOrganizationMemberships(limit = 50, offset = 0) // Invite someone org.createInvitation(emailAddress = "new@example.com", role = "org:member") // Bulk invite org.bulkCreateInvitations( emailAddresses = listOf("a@example.com", "b@example.com"), role = "org:member", ) // Manage domains (auto-enroll users by email domain) org.createDomain(name = "acme.com") val domains = org.getDomains() // Remove member org.removeMember(userId = "user_abc") // Delete org org.delete() } ``` ``` -------------------------------- ### User.createExternalAccount - Connect OAuth account to existing user Source: https://context7.com/clerk/clerk-android/llms.txt Link an external social account (OAuth) to an already signed-in user. ```APIDOC ## `User.createExternalAccount` — Connect OAuth account to existing user Links an external social account to an already signed-in user. ```kotlin viewModelScope.launch { val user = Clerk.user ?: return@launch val result = user.createExternalAccount( User.CreateExternalAccountParams( provider = OAuthProvider.GITHUB, redirectUrl = "yourapp://oauth-callback", ) ) val externalAccount = (result as ClerkResult.Success).value // Redirect user to externalAccount.verification?.externalVerificationRedirectUrl } ``` ``` -------------------------------- ### Add Clerk Android UI Dependency Source: https://github.com/clerk/clerk-android/blob/main/README.md Include this dependency to utilize the prebuilt Jetpack Compose UI components for a streamlined integration. ```kotlin dependencies { implementation("com.clerk:clerk-android-ui:0.1.3") } ``` -------------------------------- ### Set Active Session or Organization Source: https://context7.com/clerk/clerk-android/llms.txt Switches the active session or organization, essential for multi-session or multi-organization applications. ```kotlin viewModelScope.launch { // Switch to a different account session Clerk.auth.setActive(sessionId = otherSessionId) // Set the active organization on the current session Clerk.auth.setActive( sessionId = Clerk.session!!.id, organizationId = "org_abc123", ) } ``` -------------------------------- ### Auth.signInWithTicket Source: https://context7.com/clerk/clerk-android/llms.txt Signs in a user using a pre-generated authentication ticket. This is typically used after a magic link or backend-issued invitation. ```APIDOC ## `Auth.signInWithTicket` — Ticket-based sign-in Signs in using a pre-generated authentication ticket (e.g., from a magic link or backend-issued invitation). ```kotlin viewModelScope.launch { val ticket = intent.data?.getQueryParameter("__clerk_ticket") ?: return@launch val result = Clerk.auth.signInWithTicket(ticket) when (result) { is ClerkResult.Success -> navigateHome() is ClerkResult.Failure -> showError(result.errorMessage) } } ``` ``` -------------------------------- ### Integrate UserProfileView for Full Profile Management Source: https://context7.com/clerk/clerk-android/llms.txt Embed UserProfileView to provide comprehensive account, security, and profile management UI. It supports custom rows and destinations, allowing you to integrate app-specific sections like subscriptions. ```kotlin @Composable fun ProfileScreen(onDismiss: () -> Unit) { UserProfileView( clerkTheme = myTheme, onDismiss = onDismiss, onAddAccount = { /* navigate to add account flow */ }, customRows = listOf( UserProfileCustomRow( label = "Subscription", routeKey = "subscription", icon = painterResource(R.drawable.ic_subscription), placement = UserProfileCustomRowPlacement.AFTER_SECURITY, ) ), customDestination = { routeKey -> if (routeKey == "subscription") SubscriptionScreen() }, ) } ``` -------------------------------- ### User - Email and Phone Management Source: https://context7.com/clerk/clerk-android/llms.txt Manage email addresses and phone numbers for the current user, including adding, verifying, and listing them. ```APIDOC ## `User` — Email and phone management Extension functions add and verify email addresses and phone numbers on the current user. ```kotlin viewModelScope.launch { val user = Clerk.user ?: return@launch // Add email val emailResult = user.createEmailAddress("second@example.com") val emailAddress = (emailResult as ClerkResult.Success).value // The email needs verification — use emailAddress extensions: // emailAddress.prepareVerification(...) // emailAddress.attemptVerification(...) // Add phone val phoneResult = user.createPhoneNumber("+14155551234") // List all emails / phones val emails = user.emailAddresses() val phones = user.phoneNumbers() // Get all sessions val activeSessions = user.activeSessions() val allSessions = user.allSessions() } ``` ``` -------------------------------- ### Clerk.attachActivity Source: https://context7.com/clerk/clerk-android/llms.txt Provides the current foreground Activity to the Clerk SDK. This is necessary for features like Credential Manager (Google One Tap, passkeys) and is required if the SDK is initialized after the Activity's onResume() has already fired. ```APIDOC ## Clerk.attachActivity — Supply the foreground Activity Provides the current foreground `Activity` explicitly so Clerk can use Credential Manager (Google One Tap, passkeys). Required for React Native bridges or any host that calls `initialize()` after `onResume` has already fired. ```kotlin class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Ensure passkeys / Google One Tap can locate the activity Clerk.attachActivity(this) } } ``` ```