8

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

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

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

关于这个问题的任何想法?先感谢您。

4

1 回答 1

13

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

以下测试代码有效:

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);
    }
}
于 2013-02-05T14:03:09.097 回答