Android: Detect when a headset/headphones is connected/unconnected and determine if it has a microphone

Here's a handy little snippet if you're working on an app which requires headphones. It allows you to detect when users connect/remove a headset but also determine if there is a microphone or not, as not all hands free kits are created equal.

On your activity, add this little snippet to your onCreate().

public HeadsetPlugReceiver headsetPlugReceiver;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

headsetPlugReceiver = new HeadsetPlugReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.intent.action.HEADSET_PLUG");
registerReceiver(headsetPlugReceiver, intentFilter);
}

By registering the listener/filter we bypass the need to specify it in the manifest file.

And then onDestroy(), remember to unregister it.

@Override
protected void onDestroy() {
if (headsetPlugReceiver != null) {
unregisterReceiver(headsetPlugReceiver);
headsetPlugReceiver = null;
}

super.onDestroy();
}

That should be enough to manage the handler during the activity lifecycle.

Lastly, implement the receiver logic.

public class HeadsetPlugReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
return;
}

boolean connectedHeadphones = (intent.getIntExtra("state", 0) == 1);
boolean connectedMicrophone = (intent.getIntExtra("microphone", 0) == 1) && connectedHeadphones;
String headsetName = intent.getStringExtra("name");

// ...
}
}

Now that we've got headphone and microphone detection working ...

gLkSz
SINGSTAR BATTAL BITCHES!

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog