我有一个包含SearchView小部件的活动。我正在使用onQueryTextSubmit侦听器处理文本搜索的结果,这很好。(活动本身被指定为可搜索的活动)。
最近,我决定通过在voiceSearchMode文件中添加“searchable.xml”属性来添加语音识别:
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意图发送回相同的活动(这可以在onCreate方法中处理)。是否有一种使用语音识别器激活onQueryTextSubmit方法的方法(或者类似的方法不需要重新创建活动?)我之所以问这个问题,是因为如果识别器必须发送一个意图,我必须使用APP_DATA创建并发送一个额外的包,这似乎不起作用。
所以我的问题是:
(1)如何使用(或可以使用)启用语音识别搜索的onQueryTextSubmit侦听器?(与常规基于文本的搜索一样)
(2)如果(1)不可能,那么如何通过意图传递语音识别搜索查询的附加数据?,我尝试通过onSearchRequested()添加它,如下所示:
@Override
public boolean onSearchRequested() {
Bundle appData = new Bundle();
appData.putInt("testKey", 44);
this.startSearch(null, true, appData, false);
return true;
}
但是,当我试图在onCreate中访问它时,appData是空的:
@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是包含搜索小部件的相同活动,那么使用意图有什么意义呢?
如有任何意见和建议,将不胜感激。如果需要提供更多的细节,请告诉我。
发布于 2013-03-15 14:42:36
(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处理。
https://stackoverflow.com/questions/15414673
复制相似问题