原理
其实android系统在耳机插入和拔出的时候都会发送广播,所以我们要想检测耳机的状态只需要注册响应的BroadCastReceiver,对状态进行响应的判断就ok了。
这个广播的名字叫做:android.intent.action.HEADSET_PLUG
Code
package com.yydcdut.ear; import android.os.Bundle; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.view.Menu; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //给广播绑定响应的过滤器 IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("android.intent.action.HEADSET_PLUG"); HeadsetReceiver headsetReceiver = new HeadsetReceiver(); registerReceiver(headsetReceiver, intentFilter); } //自己定义的广播接收器 public class HeadsetReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.hasExtra("state")) { if (0 == intent.getIntExtra("state", 0)) { Toast.makeText(context, "耳机未插入", Toast.LENGTH_SHORT).show(); } else if (1 == intent.getIntExtra("state", 0)) { Toast.makeText(context, "耳机已插入", Toast.LENGTH_SHORT).show(); } } } } }