headset-监听有线耳机插拔
今天在做项目的时候,需要对耳机的插拔事件进行监听,所以就写了如下的一个小demo,对耳机监听事件进行验证。直接看代码
package com.example.alert; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class HeadsetPlugReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub int state = intent.getIntExtra("state", -1); int mic = intent.getIntExtra("microphone", -1); if(state==0 && mic ==0){ Log.e("123", "headset no microphone not connected"); Toast.makeText(context, "headset no microphone not connected", Toast.LENGTH_LONG).show(); } else if (state==0 && mic ==1) { Log.e("123", "headset with microphone not connected"); Toast.makeText(context, "headset with microphone not connected", Toast.LENGTH_LONG).show(); }else if(state==1 && mic ==0){ Log.e("123", "headset no microphone connected"); Toast.makeText(context, "headset no microphone connected", Toast.LENGTH_LONG).show(); } else if (state==1 && mic ==1) { Log.e("123", "headset with microphone connected"); Toast.makeText(context, "headset with microphone connected", Toast.LENGTH_LONG).show(); } } }
对于广播在activity中的注册什么的,我们就不写了,毕竟大家都知道
监听的广播是
filter.addAction("android.intent.action.HEADSET_PLUG");
直接看我们的打印log
1.进入应用->插入耳机->拔出耳机(带有麦克风)
1 09-17 10:43:02.815: E/123(32136): headset no microphone not connected 2 09-17 10:43:29.285: E/123(32136): headset no microphone connected 3 09-17 10:43:29.355: E/123(32136): headset with microphone connected 4 09-17 10:43:41.965: E/123(32136): headset with microphone not connected 5 09-17 10:43:42.995: E/123(32136): headset no microphone not connected
2.插入耳机->进入应用->拔出耳机(带有麦克风)
1 09-17 10:50:49.635: E/123(32136): headset with microphone connected 2 09-17 10:51:01.995: E/123(32136): headset with microphone not connected 3 09-17 10:51:03.025: E/123(32136): headset no microphone not connected
3.进入应用->插入耳机->拔出耳机(没有麦克风)
1 09-17 11:10:34.665: E/123(3542): headset no microphone not connected 2 09-17 11:10:38.985: E/123(3542): headset no microphone connected 3 09-17 11:10:49.945: E/123(3542): headset with microphone connected 4 09-17 11:10:50.635: E/123(3542): headset with microphone not connected 5 09-17 11:10:51.635: E/123(3542): headset no microphone not connected
4.插入耳机->进入应用->拔出耳机(没有麦克风)
1 09-17 11:03:27.815: E/123(2838): headset no microphone not connected 2 09-17 11:03:30.865: E/123(2838): headset no microphone connected
从上面的结果我们可以得出如下的结论
1)监听有线耳机(有无麦克风)的广播 是 Intent.ACTION_HEADSET_PLUG
2)刚进入这个应用,会对耳机进行监听的,不明白为什么,但至少可以作为一次初始条件判断
3)这个广播可以同时监听插入的耳机是有线还是无线。不过,似乎是有线跟无线插入都会对有线跟无线进行判断,会发两次广播
4)state-耳机插入状态0-拔出 1-插入
microphone-有无麦克风 0-没有 1-有