Android SharedPreferences Tutorial and Example

Implementing Voice Commands with Speech Recognition

Voice control can make an Android app faster to use when someone is cooking, driving, exercising, or carrying equipment. With Android’s SpeechRecognizer API, an application can convert spoken words into text and then map that text to actions such as creating a note, searching a list, or opening a screen.

This tutorial builds a small voice-command flow in Kotlin. The example listens for a spoken instruction, displays the recognised phrase, and responds to commands such as “add milk” or “show my shopping list”. The same pattern can be adapted for SQLite records, SharedPreferences settings, dialogs, and other Android projects.

Speech recognition depends on the device, installed services, microphone permission, network availability, and the speaker’s environment. A phone in a noisy Melbourne café may produce a different result from the same phone in a quiet room, so reliable apps should provide visible feedback and a manual alternative.

Android component Purpose Typical use
SpeechRecognizer Converts speech into text Listening for a command
RecognizerIntent Configures the recognition request Selecting language and free-form speech
RecognitionListener Receives results and errors Updating the interface
RECORD_AUDIO permission Grants microphone access Required before listening
Command parser Interprets recognised text Running an app action

Choosing A Voice Interaction Design

Start with a small set of predictable commands. For a shopping-list app, phrases such as “add bread”, “remove apples”, and “show the list” are easier to process than unrestricted conversation. Clear command patterns reduce errors and make the feature easier to test.

A useful interface usually has a microphone button, a status label, and a text view showing the recognised words. The user should know when the app is listening and whether the command was understood. A short message such as “Listening…” followed by “Added bread” is more helpful than silently changing the screen.

Voice commands should supplement touch controls rather than replace them. This matters for users with speech difficulties, people in quiet public spaces, and situations where a microphone is unavailable. It also gives users in places such as Sydney train stations a practical alternative when surrounding announcements make recognition unreliable.

Preparing The Android Project

Add the microphone permission to AndroidManifest.xml:

<uses-permission android:name="android.permission.RECORD_AUDIO" />

On Android 6.0 and later, declaring the permission is insufficient. The application must request it at runtime. In an Activity, check the permission before starting recognition:

private val audioPermission = Manifest.permission.RECORD_AUDIO
private val permissionRequestCode = 100

private fun checkAudioPermission() {
    if (ContextCompat.checkSelfPermission(this, audioPermission)
        != PackageManager.PERMISSION_GRANTED
    ) {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(audioPermission),
            permissionRequestCode
        )
    } else {
        startListening()
    }
}

Explain why the microphone is needed before showing the permission dialogue. Android users are more likely to allow access when the reason is clear. The app should handle denial gracefully by keeping typed input available instead of repeatedly requesting permission.

Capturing Speech Safely

Create a recogniser after checking that the device supports speech input. The following setup uses Australian English, which helps Android interpret local pronunciation and vocabulary:

private lateinit var speechRecognizer: SpeechRecognizer

private fun createRecognizer() {
    if (!SpeechRecognizer.isRecognitionAvailable(this)) {
        statusText.text = "Speech recognition is unavailable"
        return
    }

    speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this)
    speechRecognizer.setRecognitionListener(recognitionListener)
}

Configure an intent when the user presses the microphone button:

private fun startListening() {
    val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
        putExtra(
            RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
        )
        putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-AU")
        putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak a command")
    }

    statusText.text = "Listening..."
    speechRecognizer.startListening(intent)
}

en-AU is useful for Australian users, although recognition quality still varies by device and service. Some Android speech engines process audio remotely, while offline recognition may be limited. Do not assume that EXTRA_PREFER_OFFLINE will always work.

Converting Results Into Actions

Implement RecognitionListener to receive the final transcript. The result bundle can contain several possible interpretations, so the first item is commonly used for a simple command interface:

private val recognitionListener = object : RecognitionListener {
    override fun onResults(results: Bundle) {
        val matches = results.getStringArrayList(
            SpeechRecognizer.RESULTS_RECOGNITION
        )

        val phrase = matches?.firstOrNull().orEmpty()
        commandText.text = phrase
        processCommand(phrase)
    }

    override fun onError(error: Int) {
        statusText.text = "Could not understand that"
    }

    override fun onReadyForSpeech(params: Bundle?) {}
    override fun onBeginningOfSpeech() {}
    override fun onRmsChanged(rmsdB: Float) {}
    override fun onBufferReceived(buffer: ByteArray?) {}
    override fun onEndOfSpeech() {}
    override fun onPartialResults(partialResults: Bundle?) {}
    override fun onEvent(eventType: Int, params: Bundle?) {}
}

Normalise the recognised phrase before comparing it. Removing extra spaces and converting to lowercase makes matching more consistent:

private fun processCommand(input: String) {
    val command = input.trim().lowercase(Locale.UK)

    when {
        command == "show my shopping list" -> showShoppingList()
        command.startsWith("add ") -> {
            val item = command.removePrefix("add ").trim()
            if (item.isNotEmpty()) addItem(item)
        }
        command.startsWith("remove ") -> {
            val item = command.removePrefix("remove ").trim()
            if (item.isNotEmpty()) removeItem(item)
        }
        else -> statusText.text = "Command not recognised"
    }
}

Use a parser when the number of commands grows. A parser can recognise synonyms such as “display my list” and “what’s on my list”, while keeping the action code separate from the speech API.

Handling Australian Language And Noise

Language settings should match the audience. Australian users may say “thongs” rather than “flip-flops”, “capsicum” rather than “bell pepper”, or use local place names such as Parramatta and Wagga Wagga. These terms can be added to an application dictionary or mapped to a standard internal value.

The recording environment also affects results. Background traffic near Brisbane roads, wind around Perth beaches, and announcements in Adelaide shopping centres can produce incomplete transcripts. Use partial results for live feedback only, and trigger an action from final results so an unfinished phrase does not create an incorrect database entry.

Do not repeatedly restart the recogniser after every error. A rapid retry loop can annoy users and may consume battery or create unexpected microphone behaviour. Display a clear error, allow another deliberate tap, and provide a typed field for commands that require precision.

Providing Feedback And Fallbacks

The user interface should distinguish between ready, listening, processing, successful, and failed states. Disable the microphone button while a request is being processed if the recogniser does not support overlapping sessions. A progress indicator or changing button label can make the current state obvious.

Confirmation is valuable for destructive commands. For example, “remove all items” should open an AlertDialog or require a second spoken confirmation. Less risky commands, such as adding a shopping item, can be completed immediately and shown in a list backed by SQLite or a simple in-memory collection.

Text-to-speech can provide spoken feedback, but it should be optional. A user working in a public library or on a quiet tram may prefer visual messages. Store the preference with SharedPreferences, and allow users to mute spoken responses without disabling voice input.

Managing Lifecycle And Privacy

Release the recogniser when the Activity is destroyed:

override fun onDestroy() {
    if (::speechRecognizer.isInitialized) {
        speechRecognizer.stopListening()
        speechRecognizer.destroy()
    }
    super.onDestroy()
}

Stopping the session prevents the microphone from remaining active after the screen closes. Avoid retaining an Activity context in long-lived objects, and keep recognition-related work inside an appropriate lifecycle scope.

Tell users what happens to their audio and transcripts. Australian applications that collect personal information should consider the Australian Privacy Principles, especially when voice data or spoken names are sent to a third-party recognition service. Store only the text required for the feature, protect saved data, and avoid recording audio unless the app genuinely needs it.

Testing Recognition Before Release

Test with different microphones, accents, speaking speeds, and background conditions. Include short commands, empty speech, partial phrases, denied permissions, unavailable recognition services, and network failures. Test on an emulator for interface behaviour, then use physical devices because microphone performance differs substantially.

Automated tests can target the command parser without invoking the microphone. Pass phrases such as “add milk”, “ADD bread”, and “show my shopping list” into processCommand, then verify the expected action. This keeps business logic testable even when speech services are unavailable.

A production-ready voice feature treats speech as uncertain input. It validates recognised text, confirms risky actions, handles errors visibly, and always leaves the user in control. With that approach, voice commands can work naturally alongside Android screens, dialogs, local databases, and standard touch interactions.