0

I'm trying to create an application that will only let you in a another activity if you plug in your headphones. I got a code, that works, but the problem is that it's checking the headphone is plugged in or not when the activity starts only. I want the application to always check the headphone state. Not only when the activity creates. How to do this?

  AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        if(audioManager.isWiredHeadsetOn()) {
            Intent intent1= new Intent(this,Main2Activity.class);
            startActivity(intent1);
        }

Here's the code, it's fully functional, but how to make it to always check the state of the headphones if you in the activity? Because the app only checks the state of the headset when it's starts, so you have to plug in your headphone at first, and then start the application to make the new intent work.

Thanks for every answer.

Tin_Ram
  • 99
  • 1
  • 11
  • What if you check for this in the code of the other activity? – Andrew V Nov 09 '15 at 23:03
  • Yeah i thought about that, but that's the easy way, I want to learn it how to exactly do it right. Because I'm beginner in Android programming, and everything new knowledge is good. But what you wrote is a good way also to do it of course. – Tin_Ram Nov 09 '15 at 23:07
  • 1
    You can dynamically register a `BroadcastReceiver` for the `"android.intent.action.HEADSET_PLUG"` action. – Mike M. Nov 09 '15 at 23:43
  • Just realised `isWiredHeadsetOn()` is deprecated. [This answer](http://stackoverflow.com/questions/13610258/how-to-detect-when-a-user-plugs-headset-on-android-device-opposite-of-action-a?answertab=oldest#tab-top) looks relevant to your situation. – PPartisan Nov 09 '15 at 23:45

0 Answers0