android开机耳机检测,android耳机状态的检测

在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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值