Method of opening speaker by default for Android call

  • 2021-10-15 11:29:11
  • OfStack

When making a phone call, if you want to use the speaker for audio output by default when the phone is connected, that is, turn on hands-free. The specific method is to make the following modifications in the InCallService file.

Document: frameworks-base/telecomm/java/android/telecom/InCallService. java

Add oncreate method and listener for phone status monitoring.


  @Override
  public void onCreate() {
     super.onCreate();
    MyPhoneStateListener phonehoneStateListener=new MyPhoneStateListener();
    TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    mTelephonyManager.listen(phonehoneStateListener,PhoneStateListener.LISTEN_CALL_STATE);
  }

Increase destruction incidents


  @Override
  public void onDestroy() {
    super.onDestroy();
  }

Adds the definition of the event.


  private class MyPhoneStateListener extends PhoneStateListener{
    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
      switch (state) {
      case TelephonyManager.CALL_STATE_IDLE:
        setAudioRoute(CallAudioState.ROUTE_EARPIECE);
        break;
      case TelephonyManager.CALL_STATE_RINGING:
        setAudioRoute(CallAudioState.ROUTE_SPEAKER);
        break;
      case TelephonyManager.CALL_STATE_OFFHOOK:
      setAudioRoute(CallAudioState.ROUTE_SPEAKER);
      default:
        break;
      }
      super.onCallStateChanged(state, incomingNumber);
    }
  }

If it is MTK platform, you can open the following macro, and you can also achieve the desired effect


MTK_TB_APP_CALL_FORCE_SPEAKER_ON = yes

Android handset handset and speaker switching


 AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
 private void setSpeakerphoneOn(boolean on) {
         if(on) {
             audioManager.setSpeakerphoneOn(true);
         } else {
             audioManager.setSpeakerphoneOn(false);// Turn off the speaker 
             audioManager.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
             setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
             // Set the sound to Earpiece (The receiver) comes out and is set to be on call 
             audioManager.setMode(AudioManager.MODE_IN_CALL);
         }
 }

Related articles: