如何检测Android中是否存在麦克风?

ach*_*hie 8 android

我的应用程序中有一个语音识别部分来捕获用户的语音输入.

这就是我的工作

Intent voiceIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
startActivityForResult(voiceIntent, REQUEST_CODE);
Run Code Online (Sandbox Code Playgroud)

这在大多数设备上运行良好,但现在由于平板电脑越来越受欢迎,其中一些没有麦克风,它会引发错误

W/dalvikvm(408):threadid = 1:线程退出,未捕获异常(组= 0x40015560)E/AndroidRuntime(408):致命异常:主E/AndroidRuntime(408):android.content.ActivityNotFoundException:找不到要处理的活动Intent {act = android.speech.action.RECOGNIZE_SPEECH(有额外内容)} E/AndroidRuntime(408):在android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1408).....

所以我想在让用户访问语音输入功能之前检测麦克风是否存在.如何检测设备上是否有麦克风.

谢谢.

Mar*_*ouf 8

PackageManager pm = getPackageManager();
boolean micPresent = pm.hasSystemFeature(PackageManager.FEATURE_MICROPHONE);
Run Code Online (Sandbox Code Playgroud)

Android API参考:hasSystemFeature


ach*_*hie 1

我添加了另一个答案,但这只是一个在一段时间后被破坏的链接,但这是包含代码的正确答案。

这是您需要用来启动语音识别器意图的代码。这会检查是否有任何意图可用于处理语音识别意图。

PackageManager pm = getPackageManager();
List<?> activities = pm.queryIntentActivities(
                      new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() > 0) {
    Intent voiceIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
    startActivityForResult(voiceIntent, REQUEST_CODE);

    Toast toast = Toast.makeText(this, "Loading Voice recognizer...", Toast.LENGTH_SHORT);
    toast.show();
} else { 
    Toast.makeText(this, 
                   "This action is not available on this device.", 
                   Toast.LENGTH_SHORT).show();
}
Run Code Online (Sandbox Code Playgroud)

除此之外,您还可以进行另一项检查,看看设备上是否存在麦克风本身。

if (getPackageManager().hasSystemFeature( "android.hardware.microphone")) {
    //Microphone is present on the device
}
Run Code Online (Sandbox Code Playgroud)