Get Phone Number and IMEI number - android with example


How to get phone and IMEI number in Android?
         Before we start article let us take a step back and think how will we get phone Number , IMEI number from an android phone, it sure looks complicated enough.
So how do we tackle it, Fortunately Google provides with class called TelephonyManager class,please go through this. (link “this” word with this link here -https://developer.android.com/reference/android/telephony/TelephonyManager.html link to learn more about TelephonyManager class.

How to create TelephonyManager object?
          Before we go to android docs and get panicked about how to use TelephonyManager class, let us think what is TelephonyManager? 
It is an Object, this may seem too cheesy but it is true, it is nothing but an object, How would you create an object in java, like this!!
MyObject objectname = new MyObject();

But if you go through the link you can see some code like this.
TelephonyManager telephone = Context.getSystemService(Context.TELEPHONY_SERVICE);
Now you are probably very confused, I will try to answer your questions below!!!

Why didn’t they(Android Developers) use “new” keyword while creating TelephonyManager Object?
         Because they want to restrict how many objects will be created from TelephonyManager class generally to one, but how do they do this?   By making the constructor of the TelephonyManager class private, you cannot create objects of this class as you don’t have access to its constructor.       
         Let me explain with an analogy you have blueprint for your new car, blueprint being your class, if you want to make cars, our objects, we need a constructor in order to build our car, imagine we build only one car, and made the car constructor disappear,  by declaring it private, we cannot build any more cars, we should use car that we created earlier for our use. This example may be too cheesy but I hope that I got my point through.

If they made TelephonyManager class’s constructor private then how did we created an Object?
         They created an object from the TelephonyManager class when the constructor was available and then the object was placed in the getSystemService() method of the Context class and they are returning reference to TelephonyManager object, this is equivalent to pointing us where the car is in our above analogy.
So now we have TelephonyManager object, we can apply the methods that were listed in Google Android developer docs. If you go through the page you would see getLine1Number() and getServiceId() methods which are used to extract phonenumber and IMEI number respectively.

Note: Please note that if your device doesn’t know the phone number, you cannot extract phone Number, Inorder to check whether a device has phone number please go to
 settings->About Phone->status if you don’t see your phone number then you cannot get the phone number programmatically. However we will discuss how to write android program.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.rkchi.phonenum.MainActivity"
    android:background="@color/colorPrimary">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get Phone Number ,IMEI"
        android:id="@+id/button"
        android:layout_marginBottom="103dp"
        android:background="#ffffff"
        android:textColor="@color/colorAccent"
        android:layout_alignParentBottom="true"
        android:layout_margin="15dp"
        android:layout_alignParentEnd="true"
        android:textSize="18sp" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp"
        android:textColor="@color/colorAccent"
        android:layout_below="@+id/linearLayout"
        android:layout_alignParentStart="true"
        android:weightSum="1"
        android:elevation="2dp"
        android:layout_margin="25dp"
        android:padding="15dp"
        android:background="#ffffff">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="IMEI:"
            android:id="@+id/textView4"
            android:textSize="22sp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="1234567890"
            android:id="@+id/textView"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:textSize="22sp"/>
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:id="@+id/linearLayout"
        android:layout_marginTop="78dp"
        android:textColor="@color/colorAccent"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:weightSum="1"
        android:elevation="2dp"
        android:layout_margin="25dp"
        android:padding="15dp"
        android:background="#ffffff">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:text="Phone Number:"
            android:id="@+id/textView3"
            android:textSize="22sp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="1234567890"
            android:id="@+id/textView2"
            android:layout_centerVertical="true"
            android:layout_alignStart="@+id/textView"
            android:textSize="22sp" />
    </LinearLayout>


</RelativeLayout>

As you can see in the above XML code that we used RelativeLayout  as our parent layout and two Horizontal linear layout as the child layout of our parent layout, horizontal linear layouts contain two TextView that we will use in order to display our phone number, okay enough the UI let us get into the real stuff, add below code to .gradle file of the app module.
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Let us get into the brain of our App, MainActivity.java.

package com.example.rkchi.phonenum;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {    
    String pnumber, imei;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView phoneview = (TextView) findViewById(R.id.textView2);
        final TextView IMEIview = (TextView) findViewById(R.id.textView);
        Button button = (Button) findViewById(R.id.button);
        if (button != null) {
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getPhoneNumber();
                    if (pnumber.equals(new String("")))
                        pnumber = "No Number Available";
                    phoneview.setText(pnumber);
                    IMEIview.setText(imei);
                }
            });
        }

    }

    public void getPhoneNumber() {
        TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        String phonenum, IMEI;
        try {
            phonenum = telephonyManager.getLine1Number();
  IMEI = telephonyManager.getDeviceId();
        } catch (Exception e) {
            phonenum = "Error!!";
  IMEI = "Error!!";
        }
        
        pnumber = phonenum;
        imei = IMEI;
    }
}

I get it, you won’t understand the above code. Let me explain it with a bunch of questions.

Why did you declare pnumber, imei as Class variables rather than member variables?
          If you go through the above code, you can see that we have two functions onCreate() and getPhoneNumber() method, In order to enable variable access to the getPhoneNumber(), as you can see getPhoneNumber() function changes phonenum, imei variables and this changes are reflected in the onCreate() function.

Why did you declare phoneview, IMEIview as final?
         Since we are using these variables inside anonymous object, we need to declare them final, WHY? let us first ask ourselves what is final and why it is used in java? final keyword is used inorder to make an object immutable i.e., make an object pointer point to one and only object that it was made to point initially. Ok, this is good, why do we need this inside an anonymous object? Because we don’t want our variables that we used inside our anonymous object to change, WHY? because we don’t have name of our anonymous object that we created(that’s why it is called anonymous!!) so you will not be able to get the new value that has been given to our variables inside anonymous object.

What does “this” keyword mean when we are creating TelephonyManager Object?
         I told you that, Android developers created an TelephonyManager object and placed in getSystemService() method of Context class and our Activity class extends Context class, so getSystemService() method that is present inside our context class is inherited to our Activity class that means we have getSystemService() method right inside our Main_Activity.java, you have your AHA!!! Moment right!!! , now its basic java, you call one method from a different method using this keyword the following piece of code will illustrate this very well!!

public class test {
    public void methodA()
    {
        //inorder to call methodB from methodA
        this.methodB();
    }
    public void methodB()
    {
     //inorder to call methodA from methodB
        this.methodA();
    }
}


so this.getSystemService() means you are calling getSystemService() method from getPhoneNumber() method.
Hope you enjoyed this article. The final result of the above code will be like this, Ofcourse Numbers were changed for security purposes.

Get Phone Number and IMEI Number Android
Hope this tutorial gives sufficient information to get Phone Number and IMEI number of Android phone programatically. If there are any issues in retreiving the phone number, refer the below link..

http://stackoverflow.com/questions/5134398/telephonymanager-getline1number-failing




Reactions:

1 comment :