在Android下实现检测耳机插入和拔出,需要建立一个BroadcastReceiver,用来监听"android.intent.action.HEADSET_PLUG"广播。
实现步骤:
1.创建一个BroadcastReceiver的子类,并重写onReceive()方法,在该方法中编写接收到广播后的处理逻辑;
2.创建一个Activity类,在onCreate()方法中使用registerReceiver()方法进行注册监听广播;
3.在Activity中重写onDestory()方法,使用unregisterReceiver()注销监听广播。
具体实现代码如下:
广播接收器类
package com.leigo.demo.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; /** * Created by Administrator on 2014/8/27. */ public class HeadsetDetectReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_HEADSET_PLUG.equals(action)) { if (intent.hasExtra("state")) { int state = intent.getIntExtra("state", 0); if (state == 1) { Toast.makeText(context, "插入耳机", Toast.LENGTH_SHORT).show(); } else if(state == 0){ Toast.makeText(context, "拔出耳机", Toast.LENGTH_SHORT).show(); } } } } }
package com.leigo.demo; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.leigo.demo.receiver.HeadsetDetectReceiver; public class MainActivity extends Activity { private BroadcastReceiver receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** * Broadcast Action: Wired Headset plugged in or unplugged * The intent will have the following extra values: * state - 0 for unplugged, 1 for plugged. * name - Headset type, human readable string * microphone - 1 if headset has a microphone, 0 otherwise */ receiver = new HeadsetDetectReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); registerReceiver(receiver, intentFilter); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }