3

I am developing a simple app , that should toggle between speaker phone and wired headset to play audio on a button click event. I am trying to make use of isWiredHeadsetOn() function, but it says that this is deprecated for Android API lvl 5 onwards. So how do I check if currently audio is playing or not through wired headset so that I can redirect it to the phone speaker?

Note: I start my app with the headphone plugged to the 3.5mm jack of the phone.

This is my attempt at the code so far:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_audio_re_direct);
    redirect = (Button)findViewById(R.id.redirect);
    final AudioManager audio =(AudioManager)getApplicationContext().getSystemService(AUDIO_SERVICE);

    redirect.setOnClickListener(new View.OnClickListener() {

        @SuppressWarnings("deprecation")
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(audio.isWiredHeadsetOn())
            {
                audio.setWiredHeadsetOn(false);
                audio.setSpeakerphoneOn(true);
                Toast.makeText(getApplicationContext(), "SpeakerPhone On", Toast.LENGTH_LONG).show();
                redirect.setText("Turn on headset");

            }
            else 
            {
                audio.setSpeakerphoneOn(false);
                audio.setWiredHeadsetOn(true);
                Toast.makeText(getApplicationContext(), "Wired Headset On", Toast.LENGTH_LONG).show();
                redirect.setText("Turn off headset");
            }

            }

    });
        }

But the app is not toggling at all. Initially it detects that the wired headset is present, shows the Toast message SpeakerPhone On and that's it. It does not toggle between the two.

Someone please help me to make this work. Thanks.

SoulRayder
  • 5,072
  • 6
  • 47
  • 93
  • Well, `setWiredHeadsetOn` has been deprecated since API level 5 so it won't work. – ChuongPham Jan 07 '14 at 05:24
  • Any alternative to this? Please post if you know – SoulRayder Jan 07 '14 at 05:24
  • You can browse the source codes for the `AudioManager` and `TelephonyManager` classes and then use Reflection to do what you want. I don' t have an example of Reflection utilising these classes but you can search SO for an example. – ChuongPham Jan 07 '14 at 05:53

1 Answers1

1

you have to register a receiver for ACTION_HEADSET_PLUG intent and make a receiver class to catch that broadcast from that you can implement your own logic please check this

Community
  • 1
  • 1
Digit
  • 1,929
  • 1
  • 14
  • 17