Home > Enterprise >  Android cancel Task<void>
Android cancel Task<void>

Time:03-10

I have a task I need to cancel. "client.startSmsRetriever()" returns Task. There are no methods like cancel(), remove() and so on. How can I do that?

val task = client.startSmsRetriever()
    
    task.addOnSuccessListener {
        Log.d("TEST VERIFICATION", "startRetriever: Success")
        val smsBroadcastReceiver = SmsBroadcastReceiver()
        smsBroadcastReceiver.setSMSListener(object : SmsBroadcastReceiver.SmsReceiverListener {
            override fun onSMSReceived(verificationCode: String) {
                binding.verificationCodeEditText.setText(verificationCode)
                cachedActivity.unregisterReceiver(smsBroadcastReceiver)
            }
        })
        val filter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
        cachedActivity.registerReceiver(smsBroadcastReceiver, filter)
    }

    task.addOnFailureListener { ex ->
        Log.e("TEST retrieveSMS", ex.message.toString())
    }

CodePudding user response:

Unfortunately, there is no way of cancelling a task once you have started. The API documentation mentions no such method.

If you're planning to cancel it for some reason, I'd suggest you look into why it needs cancellation and not start the task in first place in such a scenario. Or in worst case you'd have to undo the thing once the task has completed.

https://developers.google.com/android/reference/com/google/android/gms/auth/api/phone/SmsRetrieverClient

You can check the API guide, the best you can do is add a failure listener which you already have to decide your next steps.

  • Related