Get phone number of incoming call in all android versions

Dory picture Dory · Sep 25, 2013 · Viewed 8.2k times · Source

I am trying to fetch incoming number of incoming call. I searched and found this Retrieve incoming call's phone number in Android. My issue is that I am not able to "incoming number" in version above 4.0.3. Please guide me if I am doing anything wrong ,or how to get the incoming number in version above 4.0.3. Thanks in advance. Here is code :

TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener(){
   public void onCallStateChanged(int state, String incomingNumber) {
       super.onCallStateChanged(state, incomingNumber);
          switch (state) {
              // not getting incoming number in latest version of android
              Log.e(Utils.TAG, "incomingNumber: "+incomingNumber);
          }
    }
},PhoneStateListener.LISTEN_CALL_STATE);

Answer

Will R. picture Will R. · Nov 15, 2013

Create a receiver in your manifest:

<receiver android:name=".PhoneState">  
    <intent-filter>
         <action android:name="android.intent.action.PHONE_STATE"/> 
    </intent-filter>
</receiver>

add this permission:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

create the broadcast receiver:

public class PhoneState extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        TelephonyManager tm = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE); 

        switch (tm.getCallState()) {

            case TelephonyManager.CALL_STATE_RINGING:
                    String phoneNr= intent.getStringExtra("incoming_number");
                    Toast.makeText(context, phoneNr,Toast.LENGTH_LONG).show();
                    break;
        } 
    }
}