Define
boolean callFromApp=false;
// To control the call has been made from the application boolean callFromOffHook=false;
// To control the change to idle state is from the app call
start call :
PhoneCallListener phoneListener = new PhoneCallListener();
TelephonyManager telephonyManager =
(TelephonyManager).getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+phoneNumber));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(callIntent);
callFromApp= true ;
and
In PhoneStateListener class
class PhoneCallListener extends PhoneStateListener {
private boolean isPhoneCalling = false;
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (TelephonyManager.CALL_STATE_RINGING == state) {
// phone ringing
if (callFromApp)
{
AudioManager audioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(true);
}
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
// active
isPhoneCalling = true;
if (callFromApp)
{
AudioManager audioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(true);
}
}
if (TelephonyManager.CALL_STATE_IDLE == state) {
// run when class initial and phone call ended, need detect flag
if (isPhoneCalling) {
isPhoneCalling = false;
callFromApp = false;
AudioManager audioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_NORMAL); //Deactivate loudspeaker
// Remove listener
PhoneCallListener phoneListener = new PhoneCallListener();
TelephonyManager telephonyManager = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener,PhoneStateListener.LISTEN_NONE);
}
}
}
}
Hope .. This will help you. Its working perfectly without affecting other :)