Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use GoogleAPIClient (deprecated) with SMSRetriver API in Android

I am trying to implement SMS Retriever API for SMS verification. The official way mentioned in the documentation says to use GoogleApiClient along with HintRequest to retrieve the mobile number from the device

HintRequest hintRequest = new HintRequest.Builder()
            .setPhoneNumberIdentifierSupported(true)
            .build();

PendingIntent intent = Auth.CredentialsApi.getHintPickerIntent(
            googleApiClient, hintRequest);
try {
    startIntentSenderForResult(intent.getIntentSender(),
                RESOLVE_HINT, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
    e.printStackTrace();
}

But the GoogleAPIClient is deprecated and replaced by GoogleApi interface, such as GoogleSignInClient. I tried to use GoogleSignInClient but getHintPickerIntent does not accept it. Is it safe to use the old API even after being deprecated or is there a way to use the latter with SMSRetriver API?

like image 268
Dev Sharma Avatar asked Mar 15 '20 05:03

Dev Sharma


People also ask

Is GoogleApiClient deprecated?

GoogleApiClient' is deprecated. New! Save questions or answers and organize your favorite content. Learn more.

What is GoogleApiClient?

The GoogleApiClient.Builder class provides methods that allow you to specify the Google APIs you want to use and your desired OAuth 2.0 scopes. Here is a code example that creates a GoogleApiClient instance that connects with the Google Drive service: GoogleApiClient mGoogleApiClient = new GoogleApiClient.


2 Answers

To remove the deprecated GoogleApiClient, replace your intent with the following:

// Kotlin
val intent = Credentials.getClient(this).getHintPickerIntent(hintRequest)
// Java
PendingIntent intent = Credentials.getClient(this).getHintPickerIntent(hintRequest);

Credentials is found in this package: com.google.android.gms.auth.api.credentials.Credentials.


Full working example which calls buttonClicked when a button is pressed:

// Kotlin

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
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.HintRequest

class MyActivity : AppCompatActivity() {

    // ... onCreate Functions, etc

    // Arbitrary number to identify the request for crednetials
    private val iRequestCodePhoneNumber = 100

    // Button click listener
    fun buttonClicked(@Suppress("UNUSED_PARAMETER") view: View) {
        val hintRequest = HintRequest.Builder()
            .setPhoneNumberIdentifierSupported(true)
            .build()

        val intent = Credentials.getClient(this).getHintPickerIntent(hintRequest)

        startIntentSenderForResult(
            intent.intentSender,
            iRequestCodePhoneNumber, null, 0, 0, 0
        )
    }

    // Parse the result of the HintPicker (i.e., get the selected phone number)
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // resultCode:
        //   Activity.RESULT_OK (-1) = number selected
        //   Activity.RESULT_CANCELED (0) = user touched outside the HintPicker (do nothing)
        //   CredentialsApi.ACTIVITY_RESULT_OTHER_ACCOUNT (1001) = "None of the above" (do nothing; treat as same use case as 'Cancelling')
        //   CredentialsApi.ACTIVITY_RESULT_NO_HINTS_AVAILABLE (1002) = no numbers found, probably no SIM card
        if (requestCode == iRequestCodePhoneNumber && resultCode == Activity.RESULT_OK) {
            val credential: Credential? = data?.getParcelableExtra(Credential.EXTRA_KEY)
            val phoneNumber = credential?.id

            // *** Do something with the phone number here ***

        } else if (
            requestCode == iRequestCodePhoneNumber &&
            resultCode == CredentialsApi.ACTIVITY_RESULT_NO_HINTS_AVAILABLE
        ) {
            // *** No phone numbers available ***
            Toast.makeText(this, "No phone numbers found", Toast.LENGTH_LONG).show()
        }
    }
}

This will generate a popup like this:

User selecting phone number available on their device

UPDATED :

The upper code is also deprecated as of now
Step 1 :

Getting GetPhoneNumberHintIntentRequest

val request: GetPhoneNumberHintIntentRequest = GetPhoneNumberHintIntentRequest.builder().build()

        Identity.getSignInClient(requireActivity())
            .getPhoneNumberHintIntent(request)
            .addOnSuccessListener {
                phoneNumberHintIntentResultLauncher.launch(
                    IntentSenderRequest.Builder(it.intentSender).build()
                )
            }
            .addOnFailureListener {
                Log.d(TAG, it.message)
            }
Step 2 :

Setting up ActivityResultLauncher IntentSenderRequest

private val phoneNumberHintIntentResultLauncher: ActivityResultLauncher<IntentSenderRequest> = registerForActivityResult(
        ActivityResultContracts.StartIntentSenderForResult()
    ) { result ->
        try {
            val phoneNumber = Identity.getSignInClient(requireActivity()).getPhoneNumberFromIntent(result.data)
            //Do more stuff with phoneNumber
        } catch (e: Exception) {
            Log.d(TAG, it.message)
        }
    }

Image Description : Mobile Number

For official google documentation : Click Here

like image 95
Christopher Bull Avatar answered Oct 21 '22 10:10

Christopher Bull


Use this function requestHint() when you want to request for phone number hint.

private void requestHint() {
    HintRequest hintRequest = new HintRequest.Builder()
            .setPhoneNumberIdentifierSupported(true)
            .build();
    PendingIntent intent = Credentials.getClient(this).getHintPickerIntent(hintRequest);
    IntentSenderRequest.Builder intentSenderRequest = new IntentSenderRequest.Builder(intent.getIntentSender());
    hintLauncher.launch(intentSenderRequest.build());
}

Here, we use this to handle the result (previously, we used onActivityResult() for this).

ActivityResultLauncher<IntentSenderRequest> hintLauncher = registerForActivityResult(new ActivityResultContracts.StartIntentSenderForResult(),
    result -> {
        if(result!=null && result.getData()!=null){
                Intent data = result.getData();
                Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
                String phoneNum = credential.getId();
                if (phoneNum.contains("+91"))
                    phoneNum = phoneNum.replace("+91", "");
                mPhoneEditText.setText(phoneNum);
        }
});
like image 2
Aman Raj Sundram Avatar answered Oct 21 '22 11:10

Aman Raj Sundram