android - 如何在android中检测插入和拔出麦克风

标签 android

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

我似乎无法在 android 文档中看到有关如何执行此操作的信息,在我的谷歌搜索中也没有。

谢谢!

最佳答案

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

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

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)

关于android - 如何在android中检测插入和拔出麦克风,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49076246/

相关文章:

Android,无需模拟器或任何设备即可运行应用程序

java - 使用 Android Nanohttpd 轻量级服务器进行文件目录导航

android - 使用 android ndk 15c __signbit 在 vi​​sual studio 错误上编译 android .so 库

java - 使用单击“设置”按钮时阻止 DatePickerDialog 关闭

Android::Zoom:相机预览方向

android - 监控安卓应用程序

android - 从 Android 到 Sharepoint 2013 的基本身份验证不起作用

Android:如果图像不存在,返回 createFromPath 方法是什么?

java - 如何在viewpager android中保留1000个动态 fragment ?

android - 如何更改操作栏 NAVIGATION_MODE_LIST 中的 'little triangle color'