Pages

Thursday, 22 August 2013

Android how to check earphone plugged in or not

Pls check following code to check earphone status

need to register broadcast receiver in activity


private BroadcastReceiver earPhoneStateReceiver = new BroadcastReceiver() {

  @Override
  public void onReceive(Context context, Intent intent) {
   if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {

    int state = intent.getIntExtra("state", -1);
    switch (state) {
    case 0:
     
     Log.d(TAG, "Headset is unplugged");
     break;
    case 1:
     
     Log.d(TAG, "Headset is plugged");
     break;
    default:
     
     Log.d(TAG, "I have no idea what the headset state is");
    }
   }
  }
 };


in On create of activity need to register above receiver
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.detail);


  // register receiver for ear phone
  IntentFilter receiverFilter = new IntentFilter(
    Intent.ACTION_HEADSET_PLUG);

  registerReceiver(earPhoneStateReceiver, receiverFilter);
  // end register receiver for ear phone

}

No comments :

Post a Comment