Monday, July 12, 2010

Listening to Phone calls using PhoneStateListener

When an incoming call is coming to your mobile, you can get the number of the incoming call, through the interface phoneStateListener. Then we can also get the state the mobile phone throught the same phoneStateListener. Here, I used two emulators to show the scenario.

For this, first install the application in two emulators.

The complete code is,


public class CaptureCall extends Activity {

TelephonyManager tm;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
tm.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}

private PhoneStateListener mPhoneListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
try {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
Toast.makeText(CaptureCall.this, "CALL_STATE_RINGING", Toast.LENGTH_SHORT).show();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Toast.makeText(CaptureCall.this, "CALL_STATE_OFFHOOK", Toast.LENGTH_SHORT).show();
break;
case TelephonyManager.CALL_STATE_IDLE:
Toast.makeText(CaptureCall.this, "CALL_STATE_IDLE", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(CaptureCall.this, "default", Toast.LENGTH_SHORT).show();
Log.i("Default", "Unknown phone state=" + state);
}
} catch (Exception e) {
Log.i("Exception", "PhoneStateListener() e = " + e);
}
}
};
}



Then of course, we need to give permission as,


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


The screenshots are,


1 comment:

Androidians