You need to listen for ACTION_HEADSET_PLUG which fires on headset events and also apparently fires periodically even when nothing changes.
From my existing code I have this in onCreate
of my main service:
// listen for headphone events so we can auto switch the audio output when headphones are plugged in
myHeadphoneMonitor = new HeadphoneMonitor();
android.content.IntentFilter headphone_filter = new
android.content.IntentFilter(Intent.ACTION_HEADSET_PLUG);
registerReceiver(myHeadphoneMonitor, headphone_filter);
And my monitor looks like this:
package com.myname.foo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.os.Message;
public class HeadphoneMonitor extends BroadcastReceiver
{
public boolean headphonesActive=false;
@Override
public void onReceive(final Context context, final Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG))
{
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Log.d("HeadphoneMonitor", "Headset is unplugged");
headphonesActive=false;
break;
case 1:
Log.d("HeadphoneMonitor", "Headset is plugged in");
headphonesActive=true;
break;
default:
Log.d("HeadphoneMonitor", "I have no idea what the headset state is");
break;
}
// push this event onto the queue to be processed by the Handler
Message msg = MyApp.uiHandler.obtainMessage(MyApp.HEADPHONE_EVENT);
MyApp.uiHandler.sendMessage(msg);
}
}
}
Nothing is needed in the manifest to listen for this broadcast event.