Open In App

Android Jetpack Compose – How to Use Phone Selector API

Improve
Improve
Like Article
Like
Save
Share
Report

In most android applications, we get to see that users don’t have to enter their phone numbers for authentication. A pop-up message is triggered automatically which displays the phone number of the user which is present on the device. This feature helps users to easily authenticate within the application and reduces the efforts. In this article, we will take a look at How to display that dialog using Phone selector API in android using Jetpack Compose. A sample video is given below to get an idea about what we are going to do in this article.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Adding dependency to use phone selector API

Navigate to app> build.gradle file and add the below dependency to it in the dependencies section. 

implementation 'com.google.android.gms:play-services-auth:19.0.0'

After adding that dependency simply sync your project to install it.

Step 3: Adding a new color in the Color.kt file

Navigate to app > java > your app’s package name > ui.theme > Color.kt file and add the below code to it. 

Kotlin




package com.example.newcanaryproject.ui.theme
 
import androidx.compose.ui.graphics.Color
 
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
 
// on below line we are
// adding different colors.
val greenColor = Color(0xFF0F9D58)


Step 4: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.example.gfgapp
 
import android.annotation.SuppressLint
import android.app.Activity
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.IntentSender
import android.media.AudioManager
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.ExperimentalUnitApi
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
import androidx.core.app.ActivityCompat.startIntentSenderForResult
import androidx.core.content.ContextCompat.startActivity
import com.example.gfgapp.ui.theme.GFGAppTheme
import com.example.gfgapp.ui.theme.greenColor
import com.google.android.gms.auth.api.credentials.*
 
class MainActivity : ComponentActivity() {
    @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            GFGAppTheme {
                // A surface container using the
                  // 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background
                ) {
                    Scaffold() {
                        // on below line calling
                          // method to display UI
                        phoneUI()
                    }
                }
            }
        }
    }
 
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1 && resultCode == RESULT_OK) {
             
            // get data from the dialog which is of type Credential
            val credential: Credential? = data?.getParcelableExtra(Credential.EXTRA_KEY)
 
            // displaying selected id in the form of toast message.
            Toast.makeText(
                applicationContext,
                "Selected phone number is : " + credential!!.id,
                Toast.LENGTH_SHORT
            ).show()
 
        } else if (requestCode == 1 && resultCode == CredentialsApi.ACTIVITY_RESULT_NO_HINTS_AVAILABLE) {
            // displaying toast message when no data found.
            Toast.makeText(this, "No phone numbers found", Toast.LENGTH_LONG).show();
        }
    }
}
 
@OptIn(ExperimentalUnitApi::class)
@Composable
fun phoneUI() {
 
    // on below line we are creating a
    // variable to get current context.
    var ctx = LocalContext.current
 
    // on below line we are creating a column
    Column(
        // on below line we are specifying modifier
        // for column to fill max height and width,
        modifier = Modifier.fillMaxWidth().fillMaxHeight(),
        // on below line we are specifying vertical
        // and horizontal arrangement to center.
        verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(20.dp))
        // on below line we are creating a simple text
        Text(
            // on below line we are specifying text
            text = "Phone Selector API Example",
 
            // on below line we are setting color.
            color = greenColor,
 
            // on below line we are setting font size.
            fontSize = TextUnit(value = 18F, type = TextUnitType.Sp)
        )
 
        // on the below line we are adding a spacer.
        Spacer(modifier = Modifier.height(20.dp))
 
        // on below line we are creating
        // a button  for vibrate mode.
        Button(
            // on below line we are adding width for the button
            modifier = Modifier.width(200.dp), onClick = {
                // on below line calling method to select phone number.
                phoneSelection(applicationContext = ctx)
            },
            // on below line we are setting color for our button
            colors = ButtonDefaults.buttonColors(containerColor = greenColor)
        ) {
            // on the below line we are setting text
            // for our button as vibrate mode.
            Text(text = "Select Phone Number", color = Color.White)
        }
    }
 
 
}
 
private fun phoneSelection(applicationContext: Context) {
   
    // To retrieve the Phone Number hints, first, configure
    // the hint selector dialog by creating a HintRequest object.
    val hintRequest = HintRequest.Builder().setPhoneNumberIdentifierSupported(true).build()
 
    // on below line creating options.
    val options = CredentialsOptions.Builder().forceEnableSaveDialog().build()
 
    // on below line creating a credentials client and initialising it.
    val credentialsClient = Credentials.getClient(applicationContext, options)
     
    // on below line creating a variable for our intent
    val intent = credentialsClient.getHintPickerIntent(hintRequest)
    try {
        // on below line calling start intent sender
        // for result to launch our id picker.
        startIntentSenderForResult(
            applicationContext as Activity, intent.intentSender, 1, null, 0, 0, 0, Bundle()
        )
    } catch (e: IntentSender.SendIntentException) {
        // on below line handling exception.
        e.printStackTrace()
    }
}


Now run your application to see the output of it. 

Output:



Last Updated : 13 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads