5

I am trying get phone number using phone selector API, but get empty response, here my code.

GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Auth.CREDENTIALS_API)
            .addConnectionCallbacks(this) 
            .addOnConnectionFailedListener(this) 
            .build();
    googleApiClient.connect();

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();
    }

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RESOLVE_HINT) {
        if (resultCode == RESULT_OK) {
            Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
            // credential.getId();  <-- will need to process phone number string

        }
    }
}

Above resultCode always returns 0.

Sivakumar S
  • 81
  • 2
  • 5
  • I have the same problem. Did you get it working ? – A.s.ALI Nov 21 '17 at 04:58
  • @sharati No, Not able to get phone numbers. Any update on this? – Sivakumar S Feb 13 '18 at 07:31
  • I got phone number on S8. And on those users cell phone who have saved their phone number in their sim from settings – A.s.ALI Feb 13 '18 at 08:13
  • 1
    one should request hint phone numbers when the google api client gets connected. So, call the HintRequest in onConnected callback from GoogleApiClient.ConnectionCallbacks implementation. @Override public void onConnected(@Nullable Bundle bundle) { requestHint(); } – Sarthak Sharma Jan 30 '19 at 11:04
  • This API is now deprecated. Please see this answer: https://stackoverflow.com/questions/60690008/how-to-use-googleapiclient-deprecated-with-smsretriver-api-in-android – Chandrahas Aroori Jun 26 '21 at 11:29

3 Answers3

4

Here is what i did to get Number:

Note: I'm getting numbers inside Fragment.

1) get GoogleApiClient

private void getCreadenticalApiClient() {
        mCredentialsApiClient = new GoogleApiClient.Builder(getBaseContext())
                .addConnectionCallbacks(this)
                .enableAutoManage(getBaseContext(), this)
                .addApi(Auth.CREDENTIALS_API)
                .build();
    }

2) showHint method will show to popup with number:

private void showHint() {
        HintRequest hintRequest = new HintRequest.Builder()
                .setHintPickerConfig(new CredentialPickerConfig.Builder()
                        .setShowCancelButton(true)
                        .build())
                .setPhoneNumberIdentifierSupported(true)
                .build();

        PendingIntent intent =
                Auth.CredentialsApi.getHintPickerIntent(mCredentialsApiClient, hintRequest);
        try {
            startIntentSenderForResult(intent.getIntentSender(), RC_HINT, null, 0, 0, 0,new Bundle());
        } catch (IntentSender.SendIntentException e) {
            Log.e("Login", "Could not start hint picker Intent", e);
        }
    }

3) And this is where you assign number to View

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_HINT) {
            if (resultCode == RESULT_OK) {
                Credential cred = data.getParcelableExtra(Credential.EXTRA_KEY);
                etMobile.setText(cred.getId().substring(3));
            }
        }
    }

At last do not forget to implement these two interfaces inside fragment:

GoogleApiClient.ConnectionCallbacks
GoogleApiClient.OnConnectionFailedListener

dependencies:

    implementation 'com.google.android.gms:play-services-base:11.8.0'
    implementation 'com.google.android.gms:play-services-identity:11.8.0'
    implementation 'com.google.android.gms:play-services-auth:11.8.0'
    implementation 'com.google.android.gms:play-services-auth-api-phone:11.8.0'
chand mohd
  • 2,363
  • 1
  • 14
  • 27
4

I got success to get the mobile number by using mobile selector api with hint request for you need to add some following dependency in app level gradle

implementation 'com.google.android.gms:play-services-auth:17.0.0'
implementation 'com.google.android.gms:play-services-identity:17.0.0'
implementation 'com.google.android.gms:play-services-auth-api-phone:17.1.0'

After that you have to implement your activity with googleAiClient like following

 public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
 GoogleApiClient.OnConnectionFailedListener{{

after that put request and manage it in onActivityForresult like folowing

GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Auth.CREDENTIALS_API)
                .addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) MainActivity.this)
                .addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) MainActivity.this)
                .build();
        googleApiClient.connect();
        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();
        }

And handle it like folowwing

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESOLVE_HINT) {
            if (resultCode == RESULT_OK) {
                com.google.android.gms.auth.api.credentials.Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
                if (credential != null) {

                    mobNumber = credential.getId();
                    String newString = mobNumber.replace("+91", "");
                    Toast.makeText(this, "" + newString, Toast.LENGTH_SHORT).show();

                } else {
                    Toast.makeText(this, "err", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

for more visit phone Slector Api

rajeev ranjan
  • 222
  • 4
  • 10
2

The GoogleApiClient is now deprecated, please follow the following steps, to implement the same.

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()
        }
    }
}

Follow this question for more clarity: How to use GoogleAPIClient (deprecated) with SMSRetriver API in Android

Credit to: Christopher Bull

Chandrahas Aroori
  • 955
  • 2
  • 14
  • 27