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