这里有一个完整的例子,但是开始起来太复杂了。这是我的示例适用于 android 7.1.1
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.eaydin79.voiceinteraction">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:theme="@style/AppTheme" >
<service
android:name="voiceInteractionService"
android:permission="android.permission.BIND_VOICE_INTERACTION" >
<meta-data
android:name="android.voice_interaction"
android:resource="@xml/interaction_service" />
<intent-filter>
<action android:name="android.service.voice.VoiceInteractionService" />
</intent-filter>
</service>
<service
android:name="voiceInteractionSessionService"
android:permission="android.permission.BIND_VOICE_INTERACTION" >
</service>
</application>
</manifest>
这是存储在 res\xml 文件夹中的 interaction_service.xml 文件
<?xml version="1.0" encoding="utf-8"?>
<voice-interaction-service xmlns:android="http://schemas.android.com/apk/res/android"
android:sessionService="com.eaydin79.voiceinteraction.voiceInteractionSessionService"
android:recognitionService="com.eaydin79.voiceinteraction.voiceInteractionService"
android:supportsAssist="true" />
语音交互服务.java
package com.eaydin79.voiceinteraction;
import android.service.voice.VoiceInteractionService;
import android.service.voice.VoiceInteractionSession;
public class voiceInteractionService extends VoiceInteractionService {
@Override
public void onReady() {
super.onReady();
}
}
语音交互会话服务.java
package com.eaydin79.voiceinteraction;
import android.os.Bundle;
import android.service.voice.VoiceInteractionSession;
import android.service.voice.VoiceInteractionSessionService;
public class voiceInteractionSessionService extends VoiceInteractionSessionService {
@Override
public VoiceInteractionSession onNewSession(Bundle bundle) {
return new voiceInteractionSession(this);
}
}
语音交互会话.java
package com.eaydin79.voiceinteraction;
import android.app.VoiceInteractor;
import android.content.Context;
import android.os.Bundle;
import android.service.voice.VoiceInteractionSession;
import android.media.AudioManager;
public class voiceInteractionSession extends VoiceInteractionSession {
voiceInteractionSession(Context context) {
super(context);
}
@Override
public void onShow(Bundle args, int showFlags) {
super.onShow(args, showFlags);
//whatever you want to do when you hold the home button
//i am using it to show volume control slider
AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_SAME, AudioManager.FLAG_SHOW_UI);
hide();
}
}