This is what I use...
The onCallStateChanged()
function gets called in all PhoneStateListeners anytime the call state has changed, so that's what you need to handle.
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
//Makes sure the audio is paused for incoming/outgoing phone calls
public class ListenToPhoneState extends PhoneStateListener {
private boolean pausedForPhoneCall = false;
private UIManager uiManager;
ListenToPhoneState(UIManager manager){
uiManager = manager;
}
@Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
resumeInAndroid();
return;
case TelephonyManager.CALL_STATE_OFFHOOK:
pauseInAndroid();
return;
case TelephonyManager.CALL_STATE_RINGING:
pauseInAndroid();
return;
}
}
private void resumeInAndroid(){
if(pausedForPhoneCall == true) {
pausedForPhoneCall=false;
uiManager.waitForPhoneCall(false);
}
}
private void pauseInAndroid(){
if(pausedForPhoneCall == false){
pausedForPhoneCall=true;
uiManager.waitForPhoneCall(true);
}
}
String stateName(int state) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE: return "Idle";
case TelephonyManager.CALL_STATE_OFFHOOK: return "Off hook";
case TelephonyManager.CALL_STATE_RINGING: return "Ringing";
}
return Integer.toString(state);
}
}
If you want to add this to your current Activity, do this..
ListenToPhoneState listener = new ListenToPhoneState(userInterface);
TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if(tManager != null)
tManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
Wouldn't you rather just pause your current activity? If you pass your class an instance of the current activity, you could call finish() and create a new activity right in the switch statement if you really want to.