上下文:
我正在尝试将谷歌语音操作集成到我的应用中。我已经看到并理解(或至少是我认为的)google codelabs-io2015 示例,在此示例中,如果您不修改代码,一切都会按预期工作。当您尝试使此示例适应您的实际用例时,问题就开始了。
问题:
所以,我的问题是我正在尝试实现搜索语音操作,但Activity#isVoiceInteraction始终为 false。我最终不明白活动何时以及为什么(以及何时不)链接到语音交互器。
研究:
查看Activity、Activity#isVoiceInteraction和Activity#getVoiceInteractor API level 23的源代码,我发现以下内容:
/**
* Check whether this activity is running as part of a voice interaction with the user.
* If true, it should perform its interaction with the user through the
* {@link VoiceInteractor} returned by {@link #getVoiceInteractor}.
*/
public boolean isVoiceInteraction() {
return mVoiceInteractor != null;
}
,
/**
* Retrieve the active {@link VoiceInteractor} that the user is going through to
* interact with this activity.
*/
public VoiceInteractor getVoiceInteractor() {
return mVoiceInteractor;
}
并且mVoiceInteractor
仅在attach
函数上初始化,如下所示:
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor) {
...
mLastNonConfigurationInstances = lastNonConfigurationInstances;
if (voiceInteractor != null) {
if (lastNonConfigurationInstances != null) {
mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
} else {
mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
Looper.myLooper());
}
}
...
}