In Android how do you register to receive headset plug broadcasts?

android, android-intent, android-manifest, broadcastreceiver

Solution

Here are two sites that may help explain it in more detail:

- http://www.grokkingandroid.com/android-tutorial-broadcastreceiver/

- http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html

You have to define your intent; otherwise it won't access the system function. The broadcast receiver; will alert your application of changes that you'd like to listen for.

Every receiver needs to be subclassed; it must include a `onReceive()`. To implement the `onReceive()` you'll need to create a method that will include two items: Context & Intent.

More then likely a service would be ideal; but you'll create a service and define your context through it. In the context; you'll define your intent.

An example:

context.startService
      (new Intent(context, YourService.class));

Very basic example. However; your particular goal is to utilize a system-wide broadcast. You want your application to be notified of `Intent.ACTION_HEADSET_PLUG`.

How to subscribe through manifest:

<receiver
    android:name="AudioJackReceiver"
    android:enabled="true"
    android:exported="true" >
    <intent-filter>
        <action android:name="android.intent.action.HEADSET_PLUG" />
    </intent-filter>
</receiver>

Or you can simply define through your application; but. Your particular request; will require user permissions if you intend to detect Bluetooth `MODIFY_AUDIO_SETTINGS`.

Problem

I am working in Android 2.1, and I want to detect when the headset is plugged in/taken out. I'm pretty new to android. I think the way to do it is using a Broadcast receiver. I sublcassed this, and I also put the following in my AndroidManifest.xml. But do you have to register the receiver somehwere else, like in the activity? I'm aware there are lots of threads on this, but I don't really understand what they're talking about. Also, what's the difference between registering in AndroidManifest.xml versus registering dynamically in your activity? ``` <receiver android:enabled="true" android:name="AudioJackReceiver" > <intent-filter> <action android:name="android.intent.action.HEADSET_PLUG" > </action> </intent-filter> </receiver> ``` And this was the implementation of the class (plus imports) ``` public class AudioJackReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.w("DEBUG", "headset state received"); } ``` } I was just trying to see if it works, but nothing shows up when I unplug/plug in the headset while running the application. EDIT: the documentation doesn't say this, but is it possible that this one won't work if registered in the manifest? I was able to get it to respond when I registered the receiver in one of my applications (or do you have to do that anyway?)

Original source

Related problems