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