👨‍💻
Sagar R. Kothari
  • README
  • _posts
    • 2019-08-13-Start-apache-server
    • Preview
    • 2020-02-12-SwiftUICardView
    • 2019-04-10-12-Swift5
    • 2021-07-11-Android-Basic-Setup
    • 2021-01-25-Android-Retrofit
    • 2020-02-05-BinaryTree-PostOrder-Traversal
    • 2020-02-06-Array-Rotation
    • 2019-04-12-14-JekyllGenerateCategoriesPage
    • 2020-09-28-nodejs
    • 2020-07-03-Android-Kotlin-Clickable-RecyclerView
    • 2021-01-24-Android-Kotlin-hideKeyboard
    • 2020-07-17-Android-NavigationComponent-SafeArgs
    • 2020-01-31-SinglyLinkList-RemoveThoseTotalZero
    • 2020-02-18-SwiftJustDayValue
    • 2021-05-29-Android-BottomSheet
    • 2020-02-05-BinaryTree-Search
    • 2020-02-03-FontForNumbersAndCurrency
    • 2020-07-01-Anroid-Kotlin-ListView
    • 2020-01-30-SinglyLinkList-Display
    • 2020-01-31-SinglyLinkList-Delete-Head
    • 2020-07-03-Anroid-Kotlin-RecyclerView
    • MainActivity.kt
    • 2021-05-29-Android-DropDown
    • Example 1
    • 2020-02-20-Swift-Form-Data-Request
    • 2020-01-31-SinglyLinkList-Delete-Before
    • 2020-02-19-UndoLastCommit
    • 2020-02-24-Swift-UIImagePickerController
    • Sample Fastlane Script to upload to fabric/crashlytics
    • 2021-02-09-Android-Switch
    • 2020-02-13-SwiftUI-ListViewWithSwipeDelete
    • 2020-07-05-Anroid-Kotlin-RecyclerView-Retrofit
    • 2021-01-25-Android-Configs
    • Convert SVG to png macOS command
    • build.gradle (Module: app)
    • 2020-07-15-Android-Kotlin-NavDrawer
    • 2020-02-05-BinaryTree-InOrder-Traversal
    • 2021-01-25-Android-NavPop
    • 2019-04-10-16-XcodeShortCuts
    • 2021-02-10-Android-Button-icon
    • 2019-08-12-CloudKit-DataSync
    • 2020-02-10-DSLinkListSwapNodes
    • 2020-02-18-SwiftDarkOrLightMode
    • 2020-02-02-Swift-Array-Chunked-Stride
    • 2020-02-16-OpenShareSheet
    • 2020-07-19-Android-NavigationComponent-NavDrawer
    • 2019-04-12-13-Swift-SHA256
    • 2020-07-18-Android-Share-Intent-Text
    • 2021-07-11-Android-Read-SMS
    • 2020-07-10-Anroid-RootCheck
    • Important Folder Locations for iOS App Developer
    • 2021-01-25-Android-Navigation-Animation
    • Sample Fastlane Script to upload to MS App Center
    • 2021-01-25-Android-UDID
    • 2020-07-14-FCM-ForeBack
    • 2019-04-10-18-TimezoneFromISO8601Date
    • 2020-01-31-SinglyLinkList-Delete-After
    • MainActivity.kt
    • 2019-04-12-11-DateTimeFormatterJekyll
    • 2020-07-01-Anroid-Kotlin-ListView-ImageDownload
    • 2020-01-31-SinglyLinkList-Delete-End
    • 2020-01-31-Fastlane-build-ios-simulator
    • 2019-04-10-19-Useful-tools
    • Pre-commit script for iOS projects for automated code review
    • How do I Validate email address?
    • 2019-04-12-15-SwiftDateExtension
    • 2020-02-05-BinaryTree-PreOrder-Traversal
    • 2020-02-05-BinaryTree-HeightOfTree
    • 2019-04-12-12-FormattingDoubleAsCurrency
    • 2020-02-05-BinaryTree-LevelOrder-Traversal
    • 2020-07-13-Anroid-KillApp
    • 2020-07-20-Android-Share-Intent-Image
    • 2020-02-15-AskForAppReview
    • 2019-04-12-10-TableViewHideSearchBar
    • 2020-02-18-SwiftSizeClass
    • Preview
    • 2020-02-05-BinaryTree-Insert
    • 2021-02-07-Android-Device-Lock
    • How do I show or hide password?
    • 2020-01-30-SinglyLinkList-Middle
    • 2020-07-16-Android-NavigationComponent
    • 2021-02-12-Android-Regex
    • 2020-01-31-SinglyLinkList-Insert-Before
    • 2021-02-10-Android-Button-Background
    • 2020-01-30-SinglyLinkList-Insert-atEnd
    • 2019-05-24-codeSnipsForVue
    • 2020-07-12-Anroid-EventBus
    • 2020-07-11-Anroid-Background-Foreground-Check
    • 2020-02-19-macOSCatalyst-AvoidPods
    • 2021-02-07-Android-Is-Internet-connected
    • 2020-02-07-SwiftUI-ImagePicker
    • 2020-02-04-Swift-IAP-Receipt-Validation
    • 2021-02-08-Android-hard-space
    • 2020-01-30-SinglyLinkList-Inverse
    • 2020-01-29-Swift-iCloud-check
    • 2021-01-24-Android-Kotlin-FragmentLayoutBinding
    • 2019-08-08-Pods-I-use
    • 2019-04-12-18-AddAcknowledgement
    • 2020-02-17-macOSCatalyst-HideTitleBar
    • 2019-04-12-16-isLive
    • 2020-07-02-Anroid-Kotlin-Volley-Get-GitUsers
    • 2019-04-13-11-SwiftRelativeDate
    • 2019-04-12-19-ChangeBarButtonFont
    • 2020-02-09-Swift-Equatable
    • 2021-02-13-Android-show-hide-menu
    • 2020-02-12-SwiftUI-List-withCardView
    • 2020-02-12-SwiftUIFabAction
    • 2019-08-08-zsh-git-commands
    • 2020-07-04-Anroid-Kotlin-RecyclerView-SwipeRefresh
    • 2020-01-30-PlayVideo
    • 2020-02-08-Swift-Reduce-Example
    • Generating App Icons from Single image named 1024x1024.png
    • Mocking data with Mocky and randomuser
    • 2020-02-14-Swift-PerformTaskInBackground
    • 2020-01-31-Github-Actions-Fastlane
    • 2020-02-25-Swift-UIImage-Resize
    • Preview
    • 2020-02-11-macOS-Mouse-Hover-Highlight
    • 2021-01-26-Android-Secure-Pref
    • 2020-02-07-SwiftUI-List-RemoveSeparator
    • 2020-01-30-SinglyLinkList-Insert-atHead
    • 2020-01-31-SinglyLinkList-Insert-After
    • 2020-01-31-SinglyLinkList-RemoveLoop
    • 2020-02-10-DSRecursionReverse
    • 2020-02-01-Swift-Reachability
    • 2021-02-11-Android-Copy-to-Clipboard
    • 2019-04-12-17-UsingCocoaLumberjack
    • 2020-02-07-SwiftUI-Pop-Navigation
    • 2020-07-05-Anroid-Kotlin-RecyclerView-ScrollToEnd
    • 2020-09-26-nodejs
    • 2020-07-03-Android-Kotlin-RecyclerView-PullToRefresh
    • Sample fastlane script to upload your app to TestFlight
  • tag
    • code
    • jekyll
    • customizations
    • analytics
    • installation
    • tags
    • images
    • comments
  • Tags
  • MyBookmarks
  • admin
  • Some info
Powered by GitBook
On this page
  • Module specific build.bradle
  • A function to perform Touch ID or Device Auth
  • A function to setup buttons
  • An object to handle Authentication

Was this helpful?

  1. _posts

2021-02-07-Android-Device-Lock

Module specific build.bradle

implementation "androidx.biometric:biometric-ktx:1.2.0-alpha02"

A function to perform Touch ID or Device Auth

private fun performBioAuth() {
    // Here this is a fragment
    BioAuth.performAuth(this) { success, errCode, errString ->
        if (success) {
            Log.d("BioAuth", "Complete. ToDo Next")
            // let's say perform login!
        } else {
            // oops. show error to user
            Log.d("BioAuth", "Failed ${errCode ?: 0}, ${errString ?: ""}")
        }
    }
}

A function to setup buttons

  • To show Touch ID button or not

  • To show Device passcode button or not

private fun setupAutoLoginButtons() {
    val canBioAuth = BioAuth.doWeHaveFingerPrintAuth(requireContext())
    val canDeviceAuth = BioAuth.doWeHaveDeviceAuth(requireContext())
    // Touch ID button visibility
    binding.imageViewBio.isVisible = canBioAuth
    // Device Passcode button visibility
    binding.imageViewDeviceLock.isVisible = !canBioAuth and canDeviceAuth
}

An object to handle Authentication

import android.content.Context
import android.os.Build
import android.util.Log
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricManager.Authenticators.*
import androidx.biometric.BiometricManager.BIOMETRIC_SUCCESS
import androidx.biometric.BiometricPrompt
import androidx.fragment.app.Fragment

object BioAuth {
    fun doWeHaveFingerPrintAuth(context: Context): Boolean {
        return when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.P -> {
                BiometricManager.from(context).canAuthenticate(
                    BIOMETRIC_STRONG
                ) == BIOMETRIC_SUCCESS
            }
            else -> {
                false
            }
        }
    }

    fun doWeHaveDeviceAuth(context: Context): Boolean {
        return when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
                BiometricManager.from(context).canAuthenticate(DEVICE_CREDENTIAL) == BIOMETRIC_SUCCESS
            }
            else -> {
                false
            }
        }
    }

    fun performAuth(fragment: Fragment, onResult: (Boolean, Int?, String?) -> Unit) {
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.P -> {
                val prompt = BiometricPrompt(fragment, object : BiometricPrompt.AuthenticationCallback() {
                    override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
                        super.onAuthenticationError(errorCode, errString)
                        onResult(false, errorCode, errString.toString())
                    }

                    override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                        super.onAuthenticationSucceeded(result)
                        Log.d("BioAuth", "Success")
                        onResult(true, null, null)
                    }

                    override fun onAuthenticationFailed() {
                        super.onAuthenticationFailed()
                        Log.d("BioAuth", "failed")
                        onResult(false, 404, "Auth failed")
                    }
                })
                val promptInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    BiometricPrompt.PromptInfo.Builder()
                        .setAllowedAuthenticators(BIOMETRIC_STRONG or DEVICE_CREDENTIAL)
                        .setTitle("Authenticate")
                        .setSubtitle("Log in using Touch ID or Device Passcode")
                        .build()
                } else {
                    BiometricPrompt.PromptInfo.Builder()
                        .setAllowedAuthenticators(BIOMETRIC_STRONG)
                        .setTitle("Authenticate")
                        .setSubtitle("Log in using Touch ID")
                        .setNegativeButtonText("Use account password")
                        .build()
                }
                prompt.authenticate(promptInfo)
            }
            else -> {
                onResult(false, 404, "No Auth available")
            }
        }
    }
}
Previous2020-02-05-BinaryTree-InsertNextHow do I show or hide password?

Last updated 4 years ago

Was this helpful?