Search code examples
androidsearchviewandroid-11

Android 11 Voice search button doesn't show


In Android 11, when targetSdk is set to 30 and voice search is enabled, the microphone icon doesn't show on the SearchView. However, it works correctly if targetSdk is set to 29. It works on Android 10 devices also with targetSdk 30.
Is there anything extra which needs to be done for 30?

menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_search"
        android:title="Search"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        app:showAsAction="always" />
</menu>

Manifest.xml

<activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />

            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
</activity>

searchable.xml

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="Search"
    android:imeOptions="actionSearch"
    android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"/>

MainActivity

override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.search, menu)

        val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
        val searchView: SearchView = menu.findItem(R.id.action_search).actionView as SearchView
        val searchableInfo = searchManager.getSearchableInfo(componentName)
        Log.d(TAG, "onCreateOptionsMenu: ${searchableInfo.voiceSearchEnabled}, ${searchableInfo.voiceSearchLaunchRecognizer}")

        searchView.setSearchableInfo(searchableInfo)
        searchView.setIconifiedByDefault(false)
        return super.onCreateOptionsMenu(menu)
    }

Solution

  • Android 11 doesn't allow checking all the installed applications, so we need to add a queries block to allow the app to see the voice search app.

    Add this in AndroidManifest.xml below the manifest tag for microphone icon to show up:

     <queries>
            <intent>
                <action android:name="android.speech.action.RECOGNIZE_SPEECH" />
            </intent>
     </queries>
    

    Package visiblility in Android 11

    Note: If you get build error(not lint warning) saying queries element not allowed, make sure to update build tools version:

    https://android-developers.googleblog.com/2020/07/preparing-your-build-for-package-visibility-in-android-11.html

    Image taken from https://android-developers.googleblog.com/2020/07/preparing-your-build-for-package-visibility-in-android-11.html