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