VoiceInteractionService.java revision 593334ab70a8341c7d24d71a377ab5617e3f4ab7
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    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    @Override
176    public void onCreate() {
177        super.onCreate();
178        mHandler = new MyHandler();
179    }
180
181    @Override
182    public IBinder onBind(Intent intent) {
183        if (SERVICE_INTERFACE.equals(intent.getAction())) {
184            return mInterface.asBinder();
185        }
186        return null;
187    }
188
189    /**
190     * Called during service initialization to tell you when the system is ready
191     * to receive interaction from it. You should generally do initialization here
192     * rather than in {@link #onCreate}. Methods such as {@link #showSession} and
193     * {@link #createAlwaysOnHotwordDetector}
194     * will not be operational until this point.
195     */
196    public void onReady() {
197        mSystemService = IVoiceInteractionManagerService.Stub.asInterface(
198                ServiceManager.getService(Context.VOICE_INTERACTION_MANAGER_SERVICE));
199        mKeyphraseEnrollmentInfo = new KeyphraseEnrollmentInfo(getPackageManager());
200    }
201
202    private void onShutdownInternal() {
203        onShutdown();
204        // Stop any active recognitions when shutting down.
205        // This ensures that if implementations forget to stop any active recognition,
206        // It's still guaranteed to have been stopped.
207        // This helps with cases where the voice interaction implementation is changed
208        // by the user.
209        safelyShutdownHotwordDetector();
210    }
211
212    /**
213     * Called during service de-initialization to tell you when the system is shutting the
214     * service down.
215     * At this point this service may no longer be the active {@link VoiceInteractionService}.
216     */
217    public void onShutdown() {
218    }
219
220    private void onSoundModelsChangedInternal() {
221        synchronized (this) {
222            if (mHotwordDetector != null) {
223                // TODO: Stop recognition if a sound model that was being recognized gets deleted.
224                mHotwordDetector.onSoundModelsChanged();
225            }
226        }
227    }
228
229    /**
230     * Creates an {@link AlwaysOnHotwordDetector} for the given keyphrase and locale.
231     * This instance must be retained and used by the client.
232     * Calling this a second time invalidates the previously created hotword detector
233     * which can no longer be used to manage recognition.
234     *
235     * @param keyphrase The keyphrase that's being used, for example "Hello Android".
236     * @param locale The locale for which the enrollment needs to be performed.
237     * @param callback The callback to notify of detection events.
238     * @return An always-on hotword detector for the given keyphrase and locale.
239     */
240    public final AlwaysOnHotwordDetector createAlwaysOnHotwordDetector(
241            String keyphrase, Locale locale, AlwaysOnHotwordDetector.Callback callback) {
242        if (mSystemService == null) {
243            throw new IllegalStateException("Not available until onReady() is called");
244        }
245        synchronized (mLock) {
246            // Allow only one concurrent recognition via the APIs.
247            safelyShutdownHotwordDetector();
248            mHotwordDetector = new AlwaysOnHotwordDetector(keyphrase, locale, callback,
249                    mKeyphraseEnrollmentInfo, mInterface, mSystemService);
250        }
251        return mHotwordDetector;
252    }
253
254    /**
255     * @return Details of keyphrases available for enrollment.
256     * @hide
257     */
258    @VisibleForTesting
259    protected final KeyphraseEnrollmentInfo getKeyphraseEnrollmentInfo() {
260        return mKeyphraseEnrollmentInfo;
261    }
262
263    private void safelyShutdownHotwordDetector() {
264        try {
265            synchronized (mLock) {
266                if (mHotwordDetector != null) {
267                    mHotwordDetector.stopRecognition();
268                    mHotwordDetector.invalidate();
269                    mHotwordDetector = null;
270                }
271            }
272        } catch (Exception ex) {
273            // Ignore.
274        }
275    }
276
277    @Override
278    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
279        pw.println("VOICE INTERACTION");
280        synchronized (mLock) {
281            pw.println("  AlwaysOnHotwordDetector");
282            if (mHotwordDetector == null) {
283                pw.println("    NULL");
284            } else {
285                mHotwordDetector.dump("    ", pw);
286            }
287        }
288    }
289}
290