在Android下实现检测耳机插入和拔出,也即建立一个Broadcast Receiver,监听“android.intent.action.HEADSET_PLUG”广播
但直接在AndroidManifest.xml中添加一个标签是无效的,如:
- <receiver android:name=".HeadsetPlugReceiver">
- <intent-filter>
- <action android:name="android.intent.action.HEADSET_PLUG" android:enabled="true">action>
- intent-filter>
- receiver>
你会发现Receiver的onReceive事件永远不会被触发,解决方法就是手动编写代码注册该广播。
首先,创建一个BroadcastReceiver的子类,用于监听耳机插入和拔出:
- public class HeadsetPlugReceiver extends BroadcastReceiver {
-
- private static final String TAG = "HeadsetPlugReceiver";
-
- @Override
- public void onReceive(Context context, Intent intent) {
- if (intent.ha***tra("state")){
- if (intent.getIntExtra("state", 0) == 0){
- Toast.makeText(context, "headset not connected", Toast.LENGTH_LONG).show();
- }
- else if (intent.getIntExtra("state", 0) == 1){
- Toast.makeText(context, "headset connected", Toast.LENGTH_LONG).show();
- }
- }
-
- }
-
- }
然后,在需要监听该事件的Activity中的onCreate()中注册监听该广播,同时不要忘记在onDestroy()中注销监听该广播:
- public class TestHeadSetPlugActivity extends Activity {
-
- private HeadsetPlugReceiver headsetPlugReceiver;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
-
- registerHeadsetPlugReceiver();
- }
-
- private void registerHeadsetPlugReceiver() {
- headsetPlugReceiver = new HeadsetPlugReceiver();
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addAction("android.intent.action.HEADSET_PLUG");
- registerReceiver(headsetPlugReceiver, intentFilter);
- }
-
- @Override
- public void onDestroy() {
- unregisterReceiver(headsetPlugReceiver);
- super.onDestroy();
- }
- }
如上这样就可以实现检测耳机插入和拔出了。
阅读(2388) | 评论(0) | 转发(0) |