Android - 如何检测耳机是否有麦克风

时间:2016-05-31 06:14:56

标签: android broadcastreceiver

我想检查耳机是否有麦克风。目前我正在使用这个广播接收器代码,但我不确定它是否正确。

public class HeadSetMicrophoneStateReceiver extends BroadcastReceiver {

    private String pluggedState = null;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
            int state = intent.getIntExtra("microphone", -1);
            switch (state) {
                case 0:
                    //Headset does not have a Microphone
                    pluggedState = "0";
                    break;
                case 1:
                    //Headset have a Microphone
                    pluggedState = "1";
                    break;
                default:
                    pluggedState = "I have no idea what the headset state is";
            }
            EventBus.getDefault().post(new HeadSetMicrophoneEvent(pluggedState));
        }
    }
}

请帮帮我。

2 个答案:

答案 0 :(得分:1)

此方法返回麦克风是否可用。 如果它不可用,则会捕获异常。

public static boolean getMicrophoneAvailable(Context context) {
    MediaRecorder recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
    recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
    recorder.setOutputFile(new File(context.getCacheDir(), "MediaUtil#micAvailTestFile").getAbsolutePath());
    boolean available = true;
    try { 
        recorder.prepare();
    }
    catch (IOException exception) {
        available = false;
    }
    recorder.release();
    return available;
}

答案 1 :(得分:0)

尝试以下代码

ackage 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 MyActivity 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("MyActivity ", "state: " + intent.getIntExtra("state", -1));
            Log.d("MyActivity ", "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);
}
}