title: How to route default audio to ear piece when headphones are connected?
body: <p>I am developing an app in which we need to use the headphone jack as a button only.</p>
  
  <p>Requirement : Play the default audio (calling) via earpiece when headsets are connected (no need of audio through headphones)</p>
  
  <p>There are many example of routing audio through speaker and headphones and also bluetooth headsets but nothing about routing the audio through ear speakers of devices if headsets are connected.
  I have tried a lot and some links are </p>
  
  <p><a href="https://stackoverflow.com/questions/29969030/android-force-audio-routing">Android : Force audio routing</a> (not working in my scenario)</p>
  
  <p>I have checked SoundAbout(<a href="https://play.google.com/store/apps/details?id=com.woodslink.android.wiredheadphoneroutingfix&amp;hl=en" rel="nofollow noreferrer">https://play.google.com/store/apps/details?id=com.woodslink.android.wiredheadphoneroutingfix&amp;hl=en</a>)
  app and it is routing the audio to various port like headset, speakers and earpieces.</p>
  
  <p>I have got audio to speakers if headsets are connected:
  Here is my code</p>
  
  <pre><code>if (Build.VERSION.SDK_INT &gt;= 21) {
              ForegroundService.audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
              ForegroundService.audioManager.setSpeakerphoneOn(true);
              SplashScreen.preferences.edit().putBoolean("isKey", true).commit();
          } else {
              Class audioSystemClass = null;
              try {
                  audioSystemClass = Class.forName("android.media.AudioSystem");
                  Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);
                  setForceUse.invoke(null, FOR_MEDIA, FORCE_SPEAKER);
              } catch (ClassNotFoundException e) {
                  e.printStackTrace();
              } catch (NoSuchMethodException e) {
                  e.printStackTrace();
              } catch (IllegalAccessException e) {
                  e.printStackTrace();
              } catch (InvocationTargetException e) {
                  e.printStackTrace();
              }
  
  
              SplashScreen.preferences.edit().putBoolean("isKey", true).commit();
              ForegroundService.audioManager.setSpeakerphoneOn(true);
          }
  </code></pre>