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