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