Thanks to some comments here, and after some search I finally found out how to do this.
My code below is called when I press a button. It sets up audio for activating speakers while calling, then calls the number.
Pay attention to the comments in my code regarding permissions.
buttonRep.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//1) we need to detect once the call has been established
//Note : this requires READ_PHONE_STATE permission in your manifest
final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(new PhoneStateListener()
{
@SuppressWarnings("unused")
@Override
public void onCallStateChanged (int state, String incomingNumber)
{
if(state == TelephonyManager.CALL_STATE_OFFHOOK) //Here we are
{
//2) we switch sound to speakers
//Note : this requires MODIFY_AUDIO_SETTINGS permission in your manifest
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_CALL);
am.setSpeakerphoneOn(true);
int i = state;
//3) we don't need this call listener anymore so we "destroy it"
tm.listen(this, PhoneStateListener.LISTEN_NONE);
}
}
}
, PhoneStateListener.LISTEN_CALL_STATE);
//4) we are ready to place our call now
//Note : this requires CALL_PHONE permission in your manifest
Intent action = new Intent();
action.setAction(Intent.ACTION_CALL);
action.setData(Uri.parse("tel:660")); //660 is my answering-machine number :)
MainActivity.this.startActivity(action);
}
});