How to Obtain the Phone Number of the Android Phone Programmatically?
While creating an android app, many times we need authentication by mobile number. To enhance the user experience, we can auto-detect the mobile number in a mobile system. So let’s start an android project! We will create a button, when clicked it will get a mobile number and display it in TextView.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. You can either choose Java or Kotlin Language.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Create a TextView to display the mobile number. Below is the code for the activity_main.xml file.
Note: android:backgroundTint used to change the color of the button.
Step 3: Add permission in the manifest file
Now about permission, we are doing detection using the ‘Telephony’ class. You should ask the user for 2 permissions
- Read phone state
- Read Mobile Numbers
Add above code in manifest.xml file. It is mandatory to add above these two lines to obtain the phone numbers.
Now let’s get towards the working of the app.
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. About telephony class: Enables the app to access information about the telephony services on the android device. We can determine telephony services and states, as well as access some types of subscriber information. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Below is the Kotlin Implementation of above code. Go to the MainActivity.kt file and refer below code.
Please Login to comment...