Home » Android » How to detect if a microphone is present in android?

How to detect if a microphone is present in android?

Posted by: admin June 15, 2020 Leave a comment


I have a voice recognition part in my application to capture users voice input.

This is what I do

Intent voiceIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
startActivityForResult(voiceIntent, REQUEST_CODE);

This works fine on most of the devices but now since the tablets are getting popular and some of them do not have a mic, it throws an error

W/dalvikvm( 408): threadid=1: thread
exiting with uncaught exception
(group=0x40015560) E/AndroidRuntime(
E/AndroidRuntime( 408):
No Activity found to handle Intent {
(has extras) } E/AndroidRuntime(
408): at

So I want to detect if the microphone is present before I let the user access the voice input feature. How can I detect if a microphone is present on the device.

Thank you.

How to&Answers:
PackageManager pm = getPackageManager();
boolean micPresent = pm.hasSystemFeature(PackageManager.FEATURE_MICROPHONE);

Android API Reference: hasSystemFeature


I added another answer but that is just a link that was broken after some time but here is the correct answer which includes the code.

This is the code that you would need to use to start the voice recognizer intent. This checks if there are any intents available to handle the speech recognition intent.

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);
} else { 
                   "This action is not available on this device.", 

On the top of that you ay also do another check to see if the microphone itself is present on the device.

if (getPackageManager().hasSystemFeature( "android.hardware.microphone")) {
    //Microphone is present on the device