检测耳机是否插入Android设备.

Cod*_*LaY 28 audio android android-intent

如何确定耳机是否插入Android设备?

cmc*_*nce 46

您可以使用广播接收器.

所以,您可以在"AndroidManifest.xml"中编写此代码

<receiver android:name="com.juno.brheadset.HeadsetStateReceiver">
    <intent-filter>
        <action android:name="android.intent.action.HEADSET_PLUG"/>
    </intent-filter>
</receiver>-->
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用.当OS发送此"HEADSET_PLUG"意图时,OS会设置标志"Intent.FLAG_RECEIVER_REGISTERED_ONLY"因此,您应该在Activity或Service类中编写如下代码,而不是"AndroidManifest".

public class BRHeadsetActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    HeadsetStateReceiver receiver = new HeadsetStateReceiver();
    registerReceiver( receiver, receiverFilter );


}
Run Code Online (Sandbox Code Playgroud)

我希望这篇文章可以帮到你.再见!

这是"HeadsetObserver.java",Android SDK Source的一部分.

private final void sendIntent(int headset, int headsetState, int prevHeadsetState, String headsetName) {
    if ((headsetState & headset) != (prevHeadsetState & headset)) {
        //  Pack up the values and broadcast them to everyone
        Intent intent = new Intent(Intent.ACTION_HEADSET_PLUG);

        **intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);**

        int state = 0;
        int microphone = 0;

        if ((headset & HEADSETS_WITH_MIC) != 0) {
            microphone = 1;
        }
        if ((headsetState & headset) != 0) {
            state = 1;
        }
        intent.putExtra("state", state);
        intent.putExtra("name", headsetName);
        intent.putExtra("microphone", microphone);

        if (LOG) Slog.v(TAG, "Intent.ACTION_HEADSET_PLUG: state: "+state+" name: "+headsetName+" mic: "+microphone);
        // TODO: Should we require a permission?
        ActivityManagerNative.broadcastStickyIntent(intent, null);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 什么是"HeadsetStateReceiver"是SDK类还是自定义类? (2认同)
  • @shim它是一个自定义类,它扩展了BroadcastReceiver,并有一个方法onReceive (2认同)

Ebo*_*ike 31

当你说"耳机"时,你的意思是"有线耳机"吗?如果是这样,就有意识到是否插入或拔出插头:ACTION_HEADSET_PLUG.

要检查状态,您可以使用AudioManager.isWiredHeadsetOn(),但如果还有蓝牙耳机可能会返回false,并且音频将路由到该状态.

  • @ChadSchultz您需要在清单中添加权限MODIFY_AUDIO_SETTINGS,然后才会返回正确的状态. (4认同)
  • 你好Mike,如果有人使用Blutooth耳机怎么办? (3认同)
  • 已弃用函数 API21 (2认同)

小智 15

AudioManager.isWiredHeadsetOn()总是返回,false因为它需要用户权限MODIFY_AUDIO_SETTINGS.

我花了几天时间找到答案.官方文档中没有关于此的信息.这bug已经注册了BugTracker.