Вам необходимо прослушать ACTION_HEADSET_PLUG, который запускает события гарнитуры, а также, по-видимому, периодически, даже когда ничего не меняется.
Из моего существующего кода у меня это в onCreate
моего основного сервиса:
// 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);
А мой монитор выглядит так:
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);
}
}
}
Ничего не нужно в манифесте для прослушивания этого широковещательного события.