2

I am fairly new to android and I would like my app to be able to retrieve the phone number of caller while ringing and store it. How can I do this?

Shishir Gupta
  • 1,512
  • 2
  • 17
  • 32
waa1990
  • 2,365
  • 9
  • 27
  • 33

3 Answers3

1

You need to use a BroadcastReceiver. It should look something like this:

public class CallReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
    if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
        Intent i = new Intent(context, IncomingCallPopup.class);
        i.putExtras(intent);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        context.startActivity(i);

    }
}
harwalan
  • 847
  • 2
  • 9
  • 12
1

Need to Extend BroadcastReceiver

public class CallReceiver extends BroadcastReceiver {
   
    @Override
    public final void onReceive(Context context, Intent intent){

            try {
                String state =intent.getStringExtra(TelephonyManager.EXTRA_STATE);             

                 String number=intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
                        
                    }

                 catch (Exception e) {
                        Log.e(TAG," Exception "+e);
                    }
            }
    }
Ajeett
  • 814
  • 2
  • 7
  • 18
0

you should register broadcast receiver and get the phone state and get incoming phone call number as:

public class CallReceiver extends BroadcastReceiver {
    String state,number,message;
    @Override
    public void onReceive(Context context, Intent intent) {
        state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
            number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
            message = "phone is ringing";
            Toast.makeText(context, "Incoming Call From:"+number, Toast.LENGTH_SHORT).show();
        }
        if ((state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))){
            Toast.makeText(context, "Call Received", Toast.LENGTH_SHORT).show();
        }
        if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
            message += "phone is idled";
            Toast.makeText(context, "Idled", Toast.LENGTH_SHORT).show();
        }
    }
}
K_Chandio
  • 558
  • 1
  • 7
  • 16