VoiceInteractionService.java revision 38a499edf5542fbd0948a02b77ecd84c0d62a846
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 * @hide 81 * Flag for use with {@link #showSession}: request that the session be started with 82 * a screen shot of the currently focused activity. 83 */ 84 public static final int START_WITH_SCREENSHOT = 1<<1; 85 86 /** 87 * Flag for use with {@link #showSession}: indicate that the session has been started from the 88 * system assist gesture. 89 */ 90 public static final int START_SOURCE_ASSIST_GESTURE = 1<<2; 91 92 IVoiceInteractionService mInterface = new IVoiceInteractionService.Stub() { 93 @Override public void ready() { 94 mHandler.sendEmptyMessage(MSG_READY); 95 } 96 @Override public void shutdown() { 97 mHandler.sendEmptyMessage(MSG_SHUTDOWN); 98 } 99 @Override public void soundModelsChanged() { 100 mHandler.sendEmptyMessage(MSG_SOUND_MODELS_CHANGED); 101 } 102 @Override 103 public void launchVoiceAssistFromKeyguard() throws RemoteException { 104 mHandler.sendEmptyMessage(MSG_LAUNCH_VOICE_ASSIST_FROM_KEYGUARD); 105 } 106 }; 107 108 MyHandler mHandler; 109 110 IVoiceInteractionManagerService mSystemService; 111 112 private final Object mLock = new Object(); 113 114 private KeyphraseEnrollmentInfo mKeyphraseEnrollmentInfo; 115 116 private AlwaysOnHotwordDetector mHotwordDetector; 117 118 static final int MSG_READY = 1; 119 static final int MSG_SHUTDOWN = 2; 120 static final int MSG_SOUND_MODELS_CHANGED = 3; 121 static final int MSG_LAUNCH_VOICE_ASSIST_FROM_KEYGUARD = 4; 122 123 class MyHandler extends Handler { 124 @Override 125 public void handleMessage(Message msg) { 126 switch (msg.what) { 127 case MSG_READY: 128 onReady(); 129 break; 130 case MSG_SHUTDOWN: 131 onShutdownInternal(); 132 break; 133 case MSG_SOUND_MODELS_CHANGED: 134 onSoundModelsChangedInternal(); 135 break; 136 case MSG_LAUNCH_VOICE_ASSIST_FROM_KEYGUARD: 137 onLaunchVoiceAssistFromKeyguard(); 138 break; 139 default: 140 super.handleMessage(msg); 141 } 142 } 143 } 144 145 /** 146 * Called when a user has activated an affordance to launch voice assist from the Keyguard. 147 * 148 * <p>This method will only be called if the VoiceInteractionService has set 149 * {@link android.R.attr#supportsLaunchVoiceAssistFromKeyguard} and the Keyguard is showing.</p> 150 * 151 * <p>A valid implementation must start a new activity that should use {@link 152 * android.view.WindowManager.LayoutParams#FLAG_SHOW_WHEN_LOCKED} to display 153 * on top of the lock screen.</p> 154 */ 155 public void onLaunchVoiceAssistFromKeyguard() { 156 } 157 158 /** 159 * Check whether the given service component is the currently active 160 * VoiceInteractionService. 161 */ 162 public static boolean isActiveService(Context context, ComponentName service) { 163 String cur = Settings.Secure.getString(context.getContentResolver(), 164 Settings.Secure.VOICE_INTERACTION_SERVICE); 165 if (cur == null || cur.isEmpty()) { 166 return false; 167 } 168 ComponentName curComp = ComponentName.unflattenFromString(cur); 169 if (curComp == null) { 170 return false; 171 } 172 return curComp.equals(service); 173 } 174 175 /** 176 * Request that the associated {@link android.service.voice.VoiceInteractionSession} be 177 * shown to the user, starting it if necessary. 178 * @param args Arbitrary arguments that will be propagated to the session. 179 */ 180 public void showSession(Bundle args, int flags) { 181 if (mSystemService == null) { 182 throw new IllegalStateException("Not available until onReady() is called"); 183 } 184 try { 185 mSystemService.showSession(mInterface, args, flags); 186 } catch (RemoteException e) { 187 } 188 } 189 190 /** @hide */ 191 public void startSession(Bundle args, int flags) { 192 showSession(args, flags); 193 } 194 /** @hide */ 195 public void startSession(Bundle args) { 196 startSession(args, 0); 197 } 198 199 @Override 200 public void onCreate() { 201 super.onCreate(); 202 mHandler = new MyHandler(); 203 } 204 205 @Override 206 public IBinder onBind(Intent intent) { 207 if (SERVICE_INTERFACE.equals(intent.getAction())) { 208 return mInterface.asBinder(); 209 } 210 return null; 211 } 212 213 /** 214 * Called during service initialization to tell you when the system is ready 215 * to receive interaction from it. You should generally do initialization here 216 * rather than in {@link #onCreate}. Methods such as {@link #showSession} and 217 * {@link #createAlwaysOnHotwordDetector} 218 * will not be operational until this point. 219 */ 220 public void onReady() { 221 mSystemService = IVoiceInteractionManagerService.Stub.asInterface( 222 ServiceManager.getService(Context.VOICE_INTERACTION_MANAGER_SERVICE)); 223 mKeyphraseEnrollmentInfo = new KeyphraseEnrollmentInfo(getPackageManager()); 224 } 225 226 private void onShutdownInternal() { 227 onShutdown(); 228 // Stop any active recognitions when shutting down. 229 // This ensures that if implementations forget to stop any active recognition, 230 // It's still guaranteed to have been stopped. 231 // This helps with cases where the voice interaction implementation is changed 232 // by the user. 233 safelyShutdownHotwordDetector(); 234 } 235 236 /** 237 * Called during service de-initialization to tell you when the system is shutting the 238 * service down. 239 * At this point this service may no longer be the active {@link VoiceInteractionService}. 240 */ 241 public void onShutdown() { 242 } 243 244 private void onSoundModelsChangedInternal() { 245 synchronized (this) { 246 if (mHotwordDetector != null) { 247 // TODO: Stop recognition if a sound model that was being recognized gets deleted. 248 mHotwordDetector.onSoundModelsChanged(); 249 } 250 } 251 } 252 253 /** 254 * Creates an {@link AlwaysOnHotwordDetector} for the given keyphrase and locale. 255 * This instance must be retained and used by the client. 256 * Calling this a second time invalidates the previously created hotword detector 257 * which can no longer be used to manage recognition. 258 * 259 * @param keyphrase The keyphrase that's being used, for example "Hello Android". 260 * @param locale The locale for which the enrollment needs to be performed. 261 * @param callback The callback to notify of detection events. 262 * @return An always-on hotword detector for the given keyphrase and locale. 263 */ 264 public final AlwaysOnHotwordDetector createAlwaysOnHotwordDetector( 265 String keyphrase, Locale locale, AlwaysOnHotwordDetector.Callback callback) { 266 if (mSystemService == null) { 267 throw new IllegalStateException("Not available until onReady() is called"); 268 } 269 synchronized (mLock) { 270 // Allow only one concurrent recognition via the APIs. 271 safelyShutdownHotwordDetector(); 272 mHotwordDetector = new AlwaysOnHotwordDetector(keyphrase, locale, callback, 273 mKeyphraseEnrollmentInfo, mInterface, mSystemService); 274 } 275 return mHotwordDetector; 276 } 277 278 /** 279 * @return Details of keyphrases available for enrollment. 280 * @hide 281 */ 282 @VisibleForTesting 283 protected final KeyphraseEnrollmentInfo getKeyphraseEnrollmentInfo() { 284 return mKeyphraseEnrollmentInfo; 285 } 286 287 private void safelyShutdownHotwordDetector() { 288 try { 289 synchronized (mLock) { 290 if (mHotwordDetector != null) { 291 mHotwordDetector.stopRecognition(); 292 mHotwordDetector.invalidate(); 293 mHotwordDetector = null; 294 } 295 } 296 } catch (Exception ex) { 297 // Ignore. 298 } 299 } 300 301 @Override 302 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 303 pw.println("VOICE INTERACTION"); 304 synchronized (mLock) { 305 pw.println(" AlwaysOnHotwordDetector"); 306 if (mHotwordDetector == null) { 307 pw.println(" NULL"); 308 } else { 309 mHotwordDetector.dump(" ", pw); 310 } 311 } 312 } 313} 314