android-检测耳机的插入和拔出动作

转载: http://blog.csdn.net/shaojie519/article/details/7341793

在android系统中,检测耳机的插入和拔出,也是通过广播实现的,可以建立一个Broadcast Receiver 监听"android.intent.action.HEADSET_PLUG" 这个Intent。

在这个Intent中包含以下几个值:

  • state ---      0代表拔出,1代表插入
  • name--- 字符串,代表headset的类型。
  • microphone --   1代表这个headset有麦克风,0则没有。
在使用的时候发现直接在AndroidManifest,xml文件中静态注册是无效的
[html] view plain copy print ?
  1. <receiver android:name=".HeadsetPlugReceiver">   
  2.         <intent-filter>   
  3.           <action android:name="android.intent.action.HEADSET_PLUG" android:enabled="true">           </action>   
  4.         </intent-filter>   
  5.   </receiver>   
解决办法是在代码中动态注册。
[java] view plain copy print ?
  1. import android.app.Activity; 
  2. import android.content.IntentFilter; 
  3. import android.os.Bundle; 
  4.  
  5. public class HeadSetActivity extends Activity { 
  6.     HeadsetPlugReceiver headsetPlugReceiver;  
  7.     /** Called when the activity is first created. */ 
  8.     @Override 
  9.     public void onCreate(Bundle savedInstanceState) { 
  10.         super.onCreate(savedInstanceState); 
  11.         setContentView(R.layout.main); 
  12.         registerHeadsetPlugReceiver(); 
  13.     } 
  14.     private void registerHeadsetPlugReceiver(){ 
  15.         headsetPlugReceiver  = new HeadsetPlugReceiver (); 
  16.         IntentFilter  filter = new IntentFilter(); 
  17.         filter.addAction("android.intent.action.HEADSET_PLUG"); 
  18.         registerReceiver(headsetPlugReceiver, filter); 
  19.     } 
  20. @Override 
  21. protected void onDestroy() { 
  22.     // TODO Auto-generated method stub 
  23.     super.onDestroy(); 
  24.     unregisterReceiver();  //注销监听 
  25. private void unregisterReceiver(){ 
  26.     this.unregisterReceiver(headsetPlugReceiver); 

在broadcast Receiver中监听事件:
[java] view plain copy print ?
  1. <pre class="java" name="code"
  2. import android.content.BroadcastReceiver; 
  3. import android.content.Context; 
  4. import android.content.Intent; 
  5. import android.widget.Toast; 
  6.  
  7. public class HeadsetPlugReceiver extends BroadcastReceiver { 
  8.  
  9.     @Override 
  10.     public void onReceive(Context context, Intent intent) { 
  11.         // TODO Auto-generated method stub 
  12.          
  13.             if(intent.hasExtra("state")){ 
  14.                 if(intent.getIntExtra("state", 0)==0){ 
  15.                     Toast.makeText(context, "headset not connected", Toast.LENGTH_LONG).show(); 
  16.                 } 
  17.                 else if(intent.getIntExtra("state", 0)==1){ 
  18.                     Toast.makeText(context, "headset  connected", Toast.LENGTH_LONG).show(); 
  19.                 } 
  20.             } 
  21.     } 
  22.  
  23. </pre><br> 
  24. <br> 
  25. <pre></pre> 
  26. <br> 

你可能感兴趣的:(java,android,filter,Class,action,import)