Hi everyone, I'm working on implementing the auto-...
# android
a
Hi everyone, I'm working on implementing the auto-fetch feature for mobile numbers and OTP in the Kotlin Android s, but it's not functioning as expected. Sometimes it doesn't fetch correctly, and other times the app crashes unexpectedly. I've attached the code snippet and the package I'm currently using for reference. Previously we are using the targetSDK version
33
and after upgrading the targetSDK version
33
to
34
this not workink. Can anyone please help me here how I can resolved this so that it's working we the targetSDK
34
.
Copy code
import com.google.android.gms.auth.api.credentials.Credential
import com.google.android.gms.auth.api.credentials.Credentials
import com.google.android.gms.auth.api.credentials.CredentialsApi
import com.google.android.gms.auth.api.credentials.CredentialsOptions
import com.google.android.gms.auth.api.credentials.HintRequest
import com.google.android.gms.auth.api.phone.SmsRetriever
import com.google.android.gms.common.api.Status

private var smsBroadcastReceiver: SmsBroadcastReceiver? = null

private fun phoneSelection() {
    val hintRequest = HintRequest.Builder()
        .setPhoneNumberIdentifierSupported(true)
        .build()

    val options = CredentialsOptions.Builder()
        .forceEnableSaveDialog()
        .build()

    val credentialClient = Credentials.getClient(applicationContext, options)
    val intent = credentialClient.getHintPickerIntent(hintRequest)
    try {
        val intentSenderRequest = IntentSenderRequest.Builder(intent.intentSender).build()
        phonePickIntentResultLauncher.launch(intentSenderRequest)
    } catch (e: IntentSender.SendIntentException) {
        e.printStackTrace()
    }
}

private val phonePickIntentResultLauncher =
    registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        when {
            result.resultCode == Activity.RESULT_OK -> {
                val data = result.data
                val credential: Credential? = data?.getParcelableExtra(Credential.EXTRA_KEY)
                credential?.apply {
                    binding?.etPhone?.setText(
                        credential.id.subSequence(3, credential.id.length).toString()
                    )
                    binding?.ivCheck?.visibility = View.VISIBLE
                }
            }

            result.resultCode == CredentialsApi.ACTIVITY_RESULT_NO_HINTS_AVAILABLE -> {
                Toast.makeText(this, "No phone numbers found", Toast.LENGTH_LONG).show()
            }

            SmsRetriever.SMS_RETRIEVED_ACTION == intent.action -> {
                val extras = intent.extras
                val status: Status? = extras!![SmsRetriever.EXTRA_STATUS] as Status?
                val message = extras[SmsRetriever.EXTRA_SMS_MESSAGE] as String?

            }
        }
    }

override fun onBackPressed() {
    if (binding?.llOtp?.visibility == View.VISIBLE) {
        showOtpView(false)
        binding?.otpView?.setOTP("")
        startSmsUserConsent()
    } else {
        super.onBackPressed()
    }
}


// Otp
private fun startSmsUserConsent() {
    val client = SmsRetriever.getClient(this)
    client.startSmsUserConsent(null).addOnSuccessListener {
    }.addOnFailureListener {
    }
}

private fun getOtpFromMessage(message: String?) {
    // This will match any 6 digit number in the message
    val pattern: Pattern = Pattern.compile("(|^)\\d{5}")
    val matcher: Matcher = pattern.matcher(message)
    if (matcher.find()) {
        matcher.group(0)?.let { binding?.otpView?.setOTP(it) }
    }
}


private fun registerBroadcastReceiver() {
    smsBroadcastReceiver = SmsBroadcastReceiver()
    smsBroadcastReceiver?.smsBroadcastReceiverListener =
        object : SmsBroadcastReceiver.SmsBroadcastReceiverListener {
            override fun onSuccess(intent: Intent) {
                otpPickIntentResultLauncher.launch(intent)
            }

            override fun onFailure() {

            }
        }
    val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
    registerReceiver(smsBroadcastReceiver, intentFilter)
}

private val otpPickIntentResultLauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                val data = result.data
                val message = data?.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
                getOtpFromMessage(message)
            }
        }
    }



override fun onStart() {
    super.onStart()
    registerBroadcastReceiver()
}

override fun onStop() {
    super.onStop()
    unregisterReceiver(smsBroadcastReceiver)
}
These are the packages which I'm using
Copy code
//otp view
implementation 'com.github.aabhasr1:OtpView:v1.1.2-ktx'

implementation 'com.google.android.gms:play-services-auth:20.4.0'
🧵 9
not kotlin but kotlin colored 9
c
Please don’t post long code snippets in the channel. Put them in here, the thread. Also your question is not Kotlin related so should be asked in a different forum.
👍 1