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