android - 检测耳机是否带麦克风

标签 android audio android-audiomanager

我需要检测插入的有线耳机是否有麦克风。

我可以使用 isWiredHeadSetOn() 检查耳机是否已插入, 但对于麦克风在 AudioManager 类中似乎没有这样的方法。

我使用 ACTION_HEADSET_PLUG 找到了一些建议,但我有兴趣了解此信息,即使在打开我的应用程序之前已插入耳机,此事件也不会在我的应用程序的生命周期内触发。

关于这个问题有什么想法吗?提前谢谢你。

最佳答案

更新: 继续并在 Activity 的 onResume() 中注册 ACTION_HEADSET_PLUG。 如果用户在启动后插入/拔出耳机,平台将在恢复时为您的 Activity 提供最新状态。

以下测试代码有效:

package com.example.headsetplugtest;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;

public class HeadSetPlugIntentActivity extends Activity {

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
                Log.d("HeadSetPlugInTest", "state: " + intent.getIntExtra("state", -1));
                Log.d("HeadSetPlugInTest", "microphone: " + intent.getIntExtra("microphone", -1));
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();

        IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
        getApplicationContext().registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onStop() {
        super.onStop();

        getApplicationContext().unregisterReceiver(mReceiver);
    }
}

关于android - 检测耳机是否带麦克风,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14708636/

相关文章:

android - 位图始终为空,但文件路径正确

android - 这个ph参数是什么?

java - Android Audiomanager 中调节音量不准确

android - 我们可以在不影响设备音量的情况下将Android应用的音量设置为相对于设备的音量吗?

android - 如何应用于标准音频播放器?

java - 如何使 "bringToFront()"仅针对特定 View (按钮)?

Android:位图缩小质量低

android - 将房间数据库中的唯一约束添加到多列

audio - FFmpeg 桌面录制不适用于蓝牙音频源

audio - 具有同步播放功能的 mp3 网站播放器(非流式传输)