在android检测耳机的状态,比如耳机的插入或拔出等是比较容易的。主要是对系统广播的接收和处理。
工作原理:
android系统在耳机插入和拔出的时候都会发送广播,所以我们要想检测耳机的状态只需要注册响应的BroadCastReceiver,对状态进行响应的判断就可以了。我们这里采用了在代码中动态注册的方式。
广播接收器类的代码:
ublic class HeadsetDetectReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.hasExtra("state")) {
if(intent.getIntExtra("state", 0)==0) {
Toast.makeText(context, "没有插入耳机", Toast.LENGTH_SHORT).show();
}
else if(intent.getIntExtra("state", 0)==1) {
Toast.makeText(context, "耳机已插入", Toast.LENGTH_SHORT).show();
}
}
}
}
程序Activity的代码:
/*
* 耳机状态检测
*
* 工作原理
* android系统在耳机插入和拔出的时候都会发送广播,所以我们要想检测耳机的状态只需要
* 注册响应的BroadCastReceiver,然后用IntentFilter对系统广播进行过滤,然后调用
* 广播接收器对符合过滤要求的Action,Data和Category进行处理。
*/
public class HeadsetDetectActivity extends Activity {
private HeadsetDetectReceiver mHeadsetDetectReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_headset_detect);
/*
* 实例化广播接收器对象
*/
mHeadsetDetectReceiver = new HeadsetDetectReceiver();
/*
* 实例化IntentFilter对象
*/
IntentFilter intentFilter = new IntentFilter();
/*
* 添加需要检查的Action
*/
intentFilter.addAction("android.intent.action.HEADSET_PLUG");
/*
* 注册广播接收器
*/
registerReceiver(mHeadsetDetectReceiver, intentFilter);
}
/*注销监听该广播
*
*/
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
unregisterReceiver(mHeadsetDetectReceiver);
super.onDestroy();
}
}