您需要收听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);
}
}
}
清单中不需要任何内容来侦听此广播事件。