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