我需要检测插入的有线耳机是否有麦克风。
我可以使用isWiredHeadSetOn()检查耳机是否已插入,但在AudioManager类中,麦克风似乎不是这样的方法。
我发现了一些使用ACTION_HEADSET_PLUG的建议,但我很想了解这些信息,即使在打开我的应用程序之前已经插入了耳机,在我的应用的生命周期内也不会触发此事件。
关于这个问题有什么想法吗?提前谢谢。
更新:继续并在活动的onResume()
中注册ACTION_HEADSET_PLUG
。若用户在启动后插入/拔出了耳机,平台将在活动恢复时为您的活动提供最新状态。
以下测试代码有效:
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);
}
}