要检测耳机插头与 USB 检测一样简单,您需要使用操作 android:name="android.intent.action.ACTION_HEADSET_PLUG" />注册接收器,并且接收器将处于活动状态
公共类 PhoneUsbReceiver 扩展 BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (intent.getAction().equalsIgnoreCase(
"android.intent.action.UMS_CONNECTED")){
Toast.makeText(context, "Usb-connected..", Toast.LENGTH_SHORT)
.show();
Log.i("Arpit", "USB connected..");
}
if (intent.getAction().equalsIgnoreCase(
"android.intent.action.UMS_DISCONNECTED")) {
Toast.makeText(context, "USB dis-connected..", Toast.LENGTH_SHORT)
.show();
Log.i("Arpit", "USB dis-connected..");
}
if (intent.getAction().equalsIgnoreCase(
"android.intent.action.ACTION_HEADSET_PLUG")) {
Toast.makeText(context, "HEADSET_PLUG-connected..",
Toast.LENGTH_SHORT).show();
Log.i("Arpit", "HEADSET_PLUG-connected..");
}
if (intent.getIntExtra("state", 0) == 0) {
Toast.makeText(context, "HEADSET_PLUG-connected..",
Toast.LENGTH_SHORT).show();
Log.i("Arpit", "HEADSET_PLUG-connected..");
} else if (intent.getIntExtra("state", 0) == 1) {
Toast.makeText(context, "HEADSET_PLUG-dis-connected..",
Toast.LENGTH_SHORT).show();
Log.i("Arpit", "HEADSET_PLUG-dis-connected..");
}
}
}
现在在清单中声明接收者:
<receiver android:name=".PhoneUsbReceiver" >
<intent-filter >
<action android:name="android.intent.action.UMS_CONNECTED" />
<action android:name="android.intent.action.UMS_DISCONNECTED" />
<action android:name="android.intent.action.ACTION_HEADSET_PLUG" />
</intent-filter>
</receiver>