【问题标题】:how to detect plugging in and pulling out microphone in android如何在android中检测插入和拔出麦克风
【发布时间】:2018-03-03 08:09:21
【问题描述】:

如何检测我的设备中是否插入了麦克风? 另外,如果麦克风从设备中拔出,我如何收到通知?

我似乎无法在 android 文档中看到它如何做到这一点,在我的谷歌搜索中也没有。

谢谢!

【问题讨论】:

  • 我猜你需要先检测耳机,然后检查它是否有麦克风。见this question

标签: android


【解决方案1】:

你可以创建一个BroadcastReceiver来监听Intent.ACTION_HEADSET_PLUG,如果min sdk为21,建议使用另一个常量AudioManager.ACTION_HEADSET_PLUG

当您注册接收器时,您将收到一个“粘性”Intent,然后在插入/拔出麦克风时收到其他信息。 BroadcastReceiver 非常简单,找不到“状态”和“麦克风”键的文档,只是用调试器看到它​​们。所以这个类可能看起来像:

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()
        }
    }
}

然后你只需要注册(和注销)

val microphonePluggedReceiver = MicrophonePluggedInReceiver()

// ...

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

// ...

unregisterReceiver(microphonePluggedReceiver)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多