CodeDoctorJL
CodeDoctorJL

Reputation: 1284

how to detect plugging in and pulling out microphone in android

How do I detect whether there is a microphone plugged into my device? Also, how do I get notification if the microphone is pulled out from the device?

I can't seem to see it in the android docs on how to do this, neither in my google searches.

Thanks!

Upvotes: 1

Views: 137

Answers (1)

lelloman
lelloman

Reputation: 14183

You can create a BroadcastReceiver that listens for Intent.ACTION_HEADSET_PLUG, if min sdk is 21, is recommended to use the other constant AudioManager.ACTION_HEADSET_PLUG.

You will receive a "sticky" Intent when you register the receiver, and then others when the mic is plugged in/out. The BroadcastReceiver is pretty simple, couldn't find a documentation for "state" and "microphone" keys, just saw them with the debugger. So the class could look like:

class MicrophonePluggedInReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == Intent.ACTION_HEADSET_PLUG) {
            val state = intent.getIntExtra("state", 0)
            val microphone = intent.getIntExtra("microphone", 0)
            val isMicrophonePluggedIn = state == 1 && microphone == 1
            Toast.makeText(context, "microphone plugged in $isMicrophonePluggedIn", Toast.LENGTH_LONG).show()
        }
    }
}

And then you just need to register (and unregister)

val microphonePluggedReceiver = MicrophonePluggedInReceiver()

// ...

context.registerReceiver(microphonePluggedReceiver, IntentFilter(Intent.ACTION_HEADSET_PLUG))    

// ...

unregisterReceiver(microphonePluggedReceiver)

Upvotes: 1

Related Questions