3

Android 11中,当targetSdk设置为30并启用语音搜索时,麦克风图标不会显示在SearchView. 但是,如果targetSdk设置为 29 ,它可以正常工作。它Android 10也适用于带有targetSdk 30.
有什么额外的事情需要做的30吗?

菜单.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>

清单.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>

可搜索的.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"/>

主要活动

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)
    }
4

1 回答 1

7

Android 11不允许检查所有已安装的应用程序,因此我们需要添加一个queries块以允许该应用程序看到该voice search应用程序。

将此添加到麦克风图标AndroidManifest.xml的标签下方manifest以显示:

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

Android 11 中的包可见性

注意:如果您收到构建错误(不是 lint 警告)提示queries element not allowed,请确保更新构建工具版本:

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

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

于 2020-09-16T06:47:18.760 回答