Speech reorganization helper class I am working on a speech reorganization project. I have a util class that consists of three methods: check if a microphone exists, check microphone availability, and check text-to-speech availability. Can anyone review my code?

public class MediaUtil {

    //returns whether a microphone exists
    public boolean getMicrophoneExists(Context context) {
        PackageManager packageManager = context.getPackageManager();
        return packageManager.hasSystemFeature(PackageManager.FEATURE_MICROPHONE);
    }

    //returns whether the microphone is available
    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;
    }

    //returns whether text to speech is available
    public static boolean getTTSAvailable(Context context) {
        PackageManager packageManager = context.getPackageManager();
        Intent speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        List&lt;ResolveInfo&gt; speechActivities = packageManager.queryIntentActivities(speechIntent, 0);
        if (speechActivities.size() != 0) return true;
        return false;
    }
Returning boolean

A pattern

    if (condition) return true;
    return false


is to be avoided.

    return condition;


achieves the same in a much more transparent manner. In your case,

    return speechActivities.size() != 0;

Testing vs acquisition

Consider the situation: by the time you call getMicrophoneAvailable it might be available, but later on when your app actually needs it, it's been successfully claimed by some other app.

It means there is no point to test for availability. Acquire it as you need it:

    public static MediaRecorder getMicrophone(Context context) {
        ....
        try {
            recorder.prepare();
        } catch (IOException exception) {
            return null;
        }
        return recorder;
    }