I am creating and android app that does an audio/video calls (like whatsapp). whenever a call is received/made, user can click a button to switch the voice from the low speaker to loud speaker.
on the onViewCreated() (I have the call in a fragment) function Icheck first if the call is a video or audio and toggle speakerphone accordingly
AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
audioManager.setSpeakerphoneOn(!mAudioOnly);
mToggleSpeakerphoneBtn.setImageResource(mAudioOnly ? R.drawable.ic_volume_off : R.drawable.ic_volume_up); //Set icon to turn on/off speaker
then i have an onclick listener for the button to toggle it back as follows:
mToggleSpeakerphoneBtn.setOnClickListener(v0 ->
toggleSpeakerphone((FloatingActionButton) v0));
with toggleSpeakerphone as follows:
private void toggleSpeakerphone(FloatingActionButton b) {
AudioManager audioManager = (AudioManager) b.getContext().getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) {
boolean enabled = audioManager.isSpeakerphoneOn();
audioManager.setSpeakerphoneOn(!enabled);
b.setImageResource(enabled ? R.drawable.ic_volume_off : R.drawable.ic_volume_up);
}
}
The issue is here when I receive the audio call, voice is correctly coming from ear speaker. when I try to toggle loudspeaker the icon change as if loud speaker is active (which is never the case voice is always from the ear speaker) and for the remainder of the time trying to “deactivate” loudspeaker (which is already not running) fails as audioManager.isSpeakerphoneOn(); is always false.
what am i missing?
Manifest has the following permissions:
<uses-permission android:name="android.permission.MANAGE_OWN_CALLS" />
<uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />