VoiceInteractionService.java revision e2c020a449cf1de10230d2ac31a083f342aa75c8
1/** 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.service.voice; 18 19import android.annotation.SdkConstant; 20import android.app.Service; 21import android.content.ComponentName; 22import android.content.Context; 23import android.content.Intent; 24import android.hardware.soundtrigger.KeyphraseEnrollmentInfo; 25import android.os.Bundle; 26import android.os.Handler; 27import android.os.IBinder; 28import android.os.Message; 29import android.os.RemoteException; 30import android.os.ServiceManager; 31import android.provider.Settings; 32 33import com.android.internal.annotations.VisibleForTesting; 34import com.android.internal.app.IVoiceInteractionManagerService; 35 36import java.io.FileDescriptor; 37import java.io.PrintWriter; 38 39 40/** 41 * Top-level service of the current global voice interactor, which is providing 42 * support for hotwording, the back-end of a {@link android.app.VoiceInteractor}, etc. 43 * The current VoiceInteractionService that has been selected by the user is kept 44 * always running by the system, to allow it to do things like listen for hotwords 45 * in the background to instigate voice interactions. 46 * 47 * <p>Because this service is always running, it should be kept as lightweight as 48 * possible. Heavy-weight operations (including showing UI) should be implemented 49 * in the associated {@link android.service.voice.VoiceInteractionSessionService} when 50 * an actual voice interaction is taking place, and that service should run in a 51 * separate process from this one. 52 */ 53public class VoiceInteractionService extends Service { 54 /** 55 * The {@link Intent} that must be declared as handled by the service. 56 * To be supported, the service must also require the 57 * {@link android.Manifest.permission#BIND_VOICE_INTERACTION} permission so 58 * that other applications can not abuse it. 59 */ 60 @SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION) 61 public static final String SERVICE_INTERFACE = 62 "android.service.voice.VoiceInteractionService"; 63 64 /** 65 * Name under which a VoiceInteractionService component publishes information about itself. 66 * This meta-data should reference an XML resource containing a 67 * <code><{@link 68 * android.R.styleable#VoiceInteractionService voice-interaction-service}></code> tag. 69 */ 70 public static final String SERVICE_META_DATA = "android.voice_interaction"; 71 72 IVoiceInteractionService mInterface = new IVoiceInteractionService.Stub() { 73 @Override public void ready() { 74 mHandler.sendEmptyMessage(MSG_READY); 75 } 76 @Override public void shutdown() { 77 mHandler.sendEmptyMessage(MSG_SHUTDOWN); 78 } 79 @Override public void soundModelsChanged() { 80 mHandler.sendEmptyMessage(MSG_SOUND_MODELS_CHANGED); 81 } 82 }; 83 84 MyHandler mHandler; 85 86 IVoiceInteractionManagerService mSystemService; 87 88 private final Object mLock = new Object(); 89 90 private KeyphraseEnrollmentInfo mKeyphraseEnrollmentInfo; 91 92 private AlwaysOnHotwordDetector mHotwordDetector; 93 94 static final int MSG_READY = 1; 95 static final int MSG_SHUTDOWN = 2; 96 static final int MSG_SOUND_MODELS_CHANGED = 3; 97 98 class MyHandler extends Handler { 99 @Override 100 public void handleMessage(Message msg) { 101 switch (msg.what) { 102 case MSG_READY: 103 onReady(); 104 break; 105 case MSG_SHUTDOWN: 106 onShutdownInternal(); 107 break; 108 case MSG_SOUND_MODELS_CHANGED: 109 onSoundModelsChangedInternal(); 110 break; 111 default: 112 super.handleMessage(msg); 113 } 114 } 115 } 116 117 /** 118 * Check whether the given service component is the currently active 119 * VoiceInteractionService. 120 */ 121 public static boolean isActiveService(Context context, ComponentName service) { 122 String cur = Settings.Secure.getString(context.getContentResolver(), 123 Settings.Secure.VOICE_INTERACTION_SERVICE); 124 if (cur == null || cur.isEmpty()) { 125 return false; 126 } 127 ComponentName curComp = ComponentName.unflattenFromString(cur); 128 if (curComp == null) { 129 return false; 130 } 131 return curComp.equals(service); 132 } 133 134 /** 135 * Initiate the execution of a new {@link android.service.voice.VoiceInteractionSession}. 136 * @param args Arbitrary arguments that will be propagated to the session. 137 */ 138 public void startSession(Bundle args) { 139 if (mSystemService == null) { 140 throw new IllegalStateException("Not available until onReady() is called"); 141 } 142 try { 143 mSystemService.startSession(mInterface, args); 144 } catch (RemoteException e) { 145 } 146 } 147 148 @Override 149 public void onCreate() { 150 super.onCreate(); 151 mHandler = new MyHandler(); 152 } 153 154 @Override 155 public IBinder onBind(Intent intent) { 156 if (SERVICE_INTERFACE.equals(intent.getAction())) { 157 return mInterface.asBinder(); 158 } 159 return null; 160 } 161 162 /** 163 * Called during service initialization to tell you when the system is ready 164 * to receive interaction from it. You should generally do initialization here 165 * rather than in {@link #onCreate()}. Methods such as {@link #startSession(Bundle)} and 166 * {@link #createAlwaysOnHotwordDetector(String, String, android.service.voice.AlwaysOnHotwordDetector.Callback)} 167 * will not be operational until this point. 168 */ 169 public void onReady() { 170 mSystemService = IVoiceInteractionManagerService.Stub.asInterface( 171 ServiceManager.getService(Context.VOICE_INTERACTION_MANAGER_SERVICE)); 172 mKeyphraseEnrollmentInfo = new KeyphraseEnrollmentInfo(getPackageManager()); 173 } 174 175 private void onShutdownInternal() { 176 onShutdown(); 177 // Stop any active recognitions when shutting down. 178 // This ensures that if implementations forget to stop any active recognition, 179 // It's still guaranteed to have been stopped. 180 // This helps with cases where the voice interaction implementation is changed 181 // by the user. 182 safelyShutdownHotwordDetector(); 183 } 184 185 /** 186 * Called during service de-initialization to tell you when the system is shutting the 187 * service down. 188 * At this point this service may no longer be the active {@link VoiceInteractionService}. 189 */ 190 public void onShutdown() { 191 } 192 193 private void onSoundModelsChangedInternal() { 194 synchronized (this) { 195 if (mHotwordDetector != null) { 196 // TODO: Stop recognition if a sound model that was being recognized gets deleted. 197 mHotwordDetector.onSoundModelsChanged(); 198 } 199 } 200 } 201 202 /** 203 * Creates an {@link AlwaysOnHotwordDetector} for the given keyphrase and locale. 204 * This instance must be retained and used by the client. 205 * Calling this a second time invalidates the previously created hotword detector 206 * which can no longer be used to manage recognition. 207 * 208 * @param keyphrase The keyphrase that's being used, for example "Hello Android". 209 * @param locale The locale for which the enrollment needs to be performed. 210 * This is a Java locale, for example "en_US". 211 * @param callback The callback to notify of detection events. 212 * @return An always-on hotword detector for the given keyphrase and locale. 213 */ 214 public final AlwaysOnHotwordDetector createAlwaysOnHotwordDetector( 215 String keyphrase, String locale, AlwaysOnHotwordDetector.Callback callback) { 216 if (mSystemService == null) { 217 throw new IllegalStateException("Not available until onReady() is called"); 218 } 219 synchronized (mLock) { 220 // Allow only one concurrent recognition via the APIs. 221 safelyShutdownHotwordDetector(); 222 mHotwordDetector = new AlwaysOnHotwordDetector(keyphrase, locale, callback, 223 mKeyphraseEnrollmentInfo, mInterface, mSystemService); 224 } 225 return mHotwordDetector; 226 } 227 228 /** 229 * @return Details of keyphrases available for enrollment. 230 * @hide 231 */ 232 @VisibleForTesting 233 protected final KeyphraseEnrollmentInfo getKeyphraseEnrollmentInfo() { 234 return mKeyphraseEnrollmentInfo; 235 } 236 237 private void safelyShutdownHotwordDetector() { 238 try { 239 synchronized (mLock) { 240 if (mHotwordDetector != null) { 241 mHotwordDetector.stopRecognition(); 242 mHotwordDetector.invalidate(); 243 mHotwordDetector = null; 244 } 245 } 246 } catch (Exception ex) { 247 // Ignore. 248 } 249 } 250 251 @Override 252 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 253 pw.println("VOICE INTERACTION"); 254 synchronized (mLock) { 255 pw.println(" AlwaysOnHotwordDetector"); 256 if (mHotwordDetector == null) { 257 pw.println(" NULL"); 258 } else { 259 mHotwordDetector.dump(" ", pw); 260 } 261 } 262 } 263} 264