如何在 OnCreate() 中获取 ACTION_HEADSET_PLUG

How to get ACTION_HEADSET_PLUG in OnCreate()

所以,为 ACTION_HEADSET_PLUG 和实际上 processing the plug in/out events 注册广播接收器的技巧现在已经很清楚了。

但是...我的应用程序需要在 onCreate() 尽早知道耳机是否已插入(如果未插入,它应该只显示一个对话框并退出,因为这是一个耳机专用应用程序,不能与扬声器一起使用)。

然而,在我阅读的所有地方,都应该在 onStart() or onResume() 中注册接收者——这让 onCreate() 没有机会使用接收者设置的标志。

知道如何解决这个问题吗?

有没有办法轮询耳机插孔?

您可以使用 AudioManager's isWiredHeadsetOn() 来确定是否插入了耳机,但请注意,根据文档:

This is not a valid indication that audio playback is actually over the wired headset as audio routing depends on other conditions.

您还需要查看 isSpeakerphoneOn()isBluetoothA2dpOn()isBluetoothScoOn() 的值,以更好地了解当前启用的内容。