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. Note that select Java as the programming 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. Now let’s get toward the working of the app i.e. onclickListener of a button.
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.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.