我有一个包含SearchView小部件的活动。我正在使用onQueryTextSubmit侦听器处理文本搜索的结果,这很好。 (活动本身被指定为可搜索活动)。
我最近决定通过在searchable.xml文件中添加“voiceSearchMode”属性来添加语音识别:
searchable.xml
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/app_name"
android:hint="@string/search_hint"
android:voiceSearchMode="showVoiceSearchButton|launchRecognizer">
</searchable>
当我添加语音识别时,在提供语音输入后不会调用onQueryTextSubmit侦听器(但是,在使用editText框提供文本输入后仍会调用它)。语音识别器将ACTION_SEARCH Intent发送回相同的Activity(可以在onCreate方法中处理)。有没有办法用语音识别器激活onQueryTextSubmit方法(或类似的东西,不需要重新创建活动?)我问的原因是因为如果识别器必须发送一个意图,我必须创建和使用APP_DATA发送额外的捆绑包,但似乎无法正常工作。
所以我的问题是:
(1)如何使用(或可以使用)启用了语音识别搜索的onQueryTextSubmit侦听器?(与使用常规基于文本的搜索的方式相同)
(2)如果(1)不可能,那么如何通过意图传递带语音识别搜索查询的附加数据?我尝试通过onSearchRequested()添加它,如下所示:< / p>
@Override
public boolean onSearchRequested() {
Bundle appData = new Bundle();
appData.putInt("testKey", 44);
this.startSearch(null, true, appData, false);
return true;
}
但是当我尝试在onCreate中访问它时,appData为null:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.overview_list);
Bundle extras = getIntent().getExtras();
Bundle appData = getIntent().getBundleExtra(SearchManager.APP_DATA);
// Receive search intents (from voice recognizer)
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//doMySearch(query);
}
}
(另外,当我添加onSearchRequested处理程序时,按放大镜图标可以将搜索小部件扩展两次 - 我想这是因为除了设置之外我手动启动搜索可搜索的xml配置。)
在相关的说明中,在同一活动中发送意图而不是使用侦听器有什么好处?我知道如果您的SearchableActivity是另一项活动,那么您可能希望向其发送意图;但是在SearchableActivity与包含搜索小部件的活动相同的情况下,使用意图的重点是什么?
任何意见和建议将不胜感激。如果我需要提供任何其他详细信息,请与我们联系。
答案 0 :(得分:11)
(1)据我所知,通过广泛调试onQueryTextSubmit,当我通过语音识别器按钮输入搜索查询时,永远不会调用它。但是,有一个简单的解决方法 - 见下文。
(2)我通过将活动启动模式设置为“singleTop”解决了我的问题 - 这意味着不是在语音搜索后重新创建活动,而是在现有的活动实例中处理新的ACTION_SEARCH意图。 onNewIntent()处理程序。因此,您可以访问现有活动的所有私有成员,并且您无需通过修改搜索意图来传递任何数据。
AndroidManifest.xml :将launchmode = singleTop属性添加到您的可搜索活动中:
<activity
android:name=".SearchableActivity"
android:label="@string/app_name"
android:uiOptions="splitActionBarWhenNarrow"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>
在 SearchableActivity 中,添加onNewIntent()方法:
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
// Gets the search query from the voice recognizer intent
String query = intent.getStringExtra(SearchManager.QUERY);
// Set the search box text to the received query and submit the search
mSearchView.setQuery(query, true);
}
}
这实际上接收语音识别器查询并将其放在文本框中,并像往常一样提交由onQueryTextSubmit处理的文本框搜索。