Android实现检测耳机插入和拔出

在Android下实现检测耳机插入和拔出,也即建立一个Broadcast Receiver,监听“android.intent.action.HEADSET_PLUG”广播


但直接在AndroidManifest.xml中添加一个标签是无效的,如:

			
	          
	            
	          
	         

你会发现Receiver的onReceive事件永远不会被触发,解决方法就是手动编写代码注册该广播。

首先,创建一个BroadcastReceiver的子类,用于监听耳机插入和拔出:

public class HeadsetPlugReceiver extends BroadcastReceiver {

	private static final String TAG = "HeadsetPlugReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {
		  if (intent.hasExtra("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;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        /* register receiver */
        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();
    }     
}

如上这样就可以实现检测耳机插入和拔出了。


参考:
http://code.google.com/p/android/issues/detail?id=4963

http://groups.google.com/group/android-developers/browse_thread/thread/6d0dda99b4f42c8f/a9c33e446db4f4d1?#a9c33e446db4f4d1



你可能感兴趣的:(Android)