Debian Codegraph @

core/java/android/service/voice/VoiceInteractionSession.java

raw symbols SCIP
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
17 package android.service.voice;
18
19 import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
20
21 import android.annotation.CallbackExecutor;
22 import android.annotation.IntDef;
23 import android.annotation.IntRange;
24 import android.annotation.NonNull;
25 import android.annotation.Nullable;
26 import android.app.Activity;
27 import android.app.Dialog;
28 import android.app.DirectAction;
29 import android.app.Instrumentation;
30 import android.app.VoiceInteractor;
31 import android.app.assist.AssistContent;
32 import android.app.assist.AssistStructure;
33 import android.content.ComponentCallbacks2;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.pm.ParceledListSlice;
37 import android.content.res.Configuration;
38 import android.content.res.TypedArray;
39 import android.graphics.Bitmap;
40 import android.graphics.Rect;
41 import android.graphics.Region;
42 import android.os.Binder;
43 import android.os.Bundle;
44 import android.os.CancellationSignal;
45 import android.os.Handler;
46 import android.os.IBinder;
47 import android.os.ICancellationSignal;
48 import android.os.Message;
49 import android.os.RemoteCallback;
50 import android.os.RemoteException;
51 import android.os.UserHandle;
52 import android.util.ArrayMap;
53 import android.util.DebugUtils;
54 import android.util.Log;
55 import android.view.Gravity;
56 import android.view.KeyEvent;
57 import android.view.LayoutInflater;
58 import android.view.View;
59 import android.view.ViewTreeObserver;
60 import android.view.WindowManager;
61 import android.widget.FrameLayout;
62
63 import com.android.internal.annotations.Immutable;
64 import com.android.internal.app.IVoiceInteractionManagerService;
65 import com.android.internal.app.IVoiceInteractionSessionShowCallback;
66 import com.android.internal.app.IVoiceInteractor;
67 import com.android.internal.app.IVoiceInteractorCallback;
68 import com.android.internal.app.IVoiceInteractorRequest;
69 import com.android.internal.os.HandlerCaller;
70 import com.android.internal.os.SomeArgs;
71 import com.android.internal.util.function.pooled.PooledLambda;
72
73 import java.io.FileDescriptor;
74 import java.io.PrintWriter;
75 import java.lang.annotation.Retention;
76 import java.lang.annotation.RetentionPolicy;
77 import java.lang.ref.WeakReference;
78 import java.util.ArrayList;
79 import java.util.Arrays;
80 import java.util.Collections;
81 import java.util.List;
82 import java.util.Map;
83 import java.util.Objects;
84 import java.util.concurrent.Executor;
85 import java.util.function.Consumer;
86
87 /**
88 * An active voice interaction session, providing a facility for the implementation
89 * to interact with the user in the voice interaction layer. The user interface is
90 * initially shown by default, and can be created by overriding {@link #onCreateContentView()}
91 * in which the UI can be built.
92 *
93 * <p>A voice interaction session can be self-contained, ultimately calling {@link #finish}
94 * when done. It can also initiate voice interactions with applications by calling
95 * {@link #startVoiceActivity}</p>.
96 */
97 public class VoiceInteractionSession implements KeyEvent.Callback, ComponentCallbacks2 {
98 static final String TAG = "VoiceInteractionSession";
99 static final boolean DEBUG = false;
100
101 /**
102 * Flag received in {@link #onShow}: originator requested that the session be started with
103 * assist data from the currently focused activity.
104 */
105 public static final int SHOW_WITH_ASSIST = 1<<0;
106
107 /**
108 * Flag received in {@link #onShow}: originator requested that the session be started with
109 * a screen shot of the currently focused activity.
110 */
111 public static final int SHOW_WITH_SCREENSHOT = 1<<1;
112
113 /**
114 * Flag for use with {@link #onShow}: indicates that the session has been started from the
115 * system assist gesture.
116 */
117 public static final int SHOW_SOURCE_ASSIST_GESTURE = 1<<2;
118
119 /**
120 * Flag for use with {@link #onShow}: indicates that the application itself has invoked
121 * the assistant.
122 */
123 public static final int SHOW_SOURCE_APPLICATION = 1<<3;
124
125 /**
126 * Flag for use with {@link #onShow}: indicates that an Activity has invoked the voice
127 * interaction service for a local interaction using
128 * {@link Activity#startLocalVoiceInteraction(Bundle)}.
129 */
130 public static final int SHOW_SOURCE_ACTIVITY = 1<<4;
131
132 /**
133 * Flag for use with {@link #onShow}: indicates that the voice interaction service was invoked
134 * from a physical button.
135 */
136 public static final int SHOW_SOURCE_PUSH_TO_TALK = 1 << 5;
137
138 /**
139 * Flag for use with {@link #onShow}: indicates that the voice interaction service was invoked
140 * from a notification.
141 */
142 public static final int SHOW_SOURCE_NOTIFICATION = 1 << 6;
143
144 /**
145 * Flag for use with {@link #onShow}: indicates that the voice interaction service was invoked
146 * from an Android automotive system UI.
147 */
148 public static final int SHOW_SOURCE_AUTOMOTIVE_SYSTEM_UI = 1 << 7;
149
150 /** @hide */
151 public static final int VOICE_INTERACTION_ACTIVITY_EVENT_START = 1;
152 /** @hide */
153 public static final int VOICE_INTERACTION_ACTIVITY_EVENT_RESUME = 2;
154 /** @hide */
155 public static final int VOICE_INTERACTION_ACTIVITY_EVENT_PAUSE = 3;
156 /** @hide */
157 public static final int VOICE_INTERACTION_ACTIVITY_EVENT_STOP = 4;
158
159 /** @hide */
160 @IntDef(prefix = { "VOICE_INTERACTION_ACTIVITY_EVENT_" }, value = {
161 VOICE_INTERACTION_ACTIVITY_EVENT_START,
162 VOICE_INTERACTION_ACTIVITY_EVENT_RESUME,
163 VOICE_INTERACTION_ACTIVITY_EVENT_PAUSE,
164 VOICE_INTERACTION_ACTIVITY_EVENT_STOP
165 })
166 @Retention(RetentionPolicy.SOURCE)
167 public @interface VoiceInteractionActivityEventType{}
168
169 final Context mContext;
170 final HandlerCaller mHandlerCaller;
171
172 final KeyEvent.DispatcherState mDispatcherState = new KeyEvent.DispatcherState();
173
174 IVoiceInteractionManagerService mSystemService;
175 IBinder mToken;
176
177 int mTheme = 0;
178 LayoutInflater mInflater;
179 TypedArray mThemeAttrs;
180 View mRootView;
181 FrameLayout mContentFrame;
182 VoiceInteractionWindow mWindow;
183
184 boolean mUiEnabled = true;
185 boolean mInitialized;
186 boolean mWindowAdded;
187 boolean mWindowVisible;
188 boolean mWindowWasVisible;
189 boolean mInShowWindow;
190
191 final ArrayMap<IBinder, Request> mActiveRequests = new ArrayMap<IBinder, Request>();
192
193 final Insets mTmpInsets = new Insets();
194
195 final WeakReference<VoiceInteractionSession> mWeakRef
196 = new WeakReference<VoiceInteractionSession>(this);
197
198 // Registry of remote callbacks pending a reply with reply handles.
199 final Map<SafeResultListener, Consumer<Bundle>> mRemoteCallbacks = new ArrayMap<>();
200
201 ICancellationSignal mKillCallback;
202
203 private final Map<VisibleActivityCallback, Executor> mVisibleActivityCallbacks =
204 new ArrayMap<>();
205 private final List<VisibleActivityInfo> mVisibleActivityInfos = new ArrayList<>();
206
207 final IVoiceInteractor mInteractor = new IVoiceInteractor.Stub() {
208 @Override
209 public IVoiceInteractorRequest startConfirmation(String callingPackage,
210 IVoiceInteractorCallback callback, VoiceInteractor.Prompt prompt, Bundle extras) {
211 ConfirmationRequest request = new ConfirmationRequest(callingPackage,
212 Binder.getCallingUid(), callback, VoiceInteractionSession.this,
213 prompt, extras);
214 addRequest(request);
215 mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_CONFIRMATION,
216 request));
217 return request.mInterface;
218 }
219
220 @Override
221 public IVoiceInteractorRequest startPickOption(String callingPackage,
222 IVoiceInteractorCallback callback, VoiceInteractor.Prompt prompt,
223 VoiceInteractor.PickOptionRequest.Option[] options, Bundle extras) {
224 PickOptionRequest request = new PickOptionRequest(callingPackage,
225 Binder.getCallingUid(), callback, VoiceInteractionSession.this,
226 prompt, options, extras);
227 addRequest(request);
228 mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_PICK_OPTION,
229 request));
230 return request.mInterface;
231 }
232
233 @Override
234 public IVoiceInteractorRequest startCompleteVoice(String callingPackage,
235 IVoiceInteractorCallback callback, VoiceInteractor.Prompt message, Bundle extras) {
236 CompleteVoiceRequest request = new CompleteVoiceRequest(callingPackage,
237 Binder.getCallingUid(), callback, VoiceInteractionSession.this,
238 message, extras);
239 addRequest(request);
240 mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_COMPLETE_VOICE,
241 request));
242 return request.mInterface;
243 }
244
245 @Override
246 public IVoiceInteractorRequest startAbortVoice(String callingPackage,
247 IVoiceInteractorCallback callback, VoiceInteractor.Prompt message, Bundle extras) {
248 AbortVoiceRequest request = new AbortVoiceRequest(callingPackage,
249 Binder.getCallingUid(), callback, VoiceInteractionSession.this,
250 message, extras);
251 addRequest(request);
252 mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_ABORT_VOICE,
253 request));
254 return request.mInterface;
255 }
256
257 @Override
258 public IVoiceInteractorRequest startCommand(String callingPackage,
259 IVoiceInteractorCallback callback, String command, Bundle extras) {
260 CommandRequest request = new CommandRequest(callingPackage,
261 Binder.getCallingUid(), callback, VoiceInteractionSession.this,
262 command, extras);
263 addRequest(request);
264 mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_COMMAND,
265 request));
266 return request.mInterface;
267 }
268
269 @Override
270 public boolean[] supportsCommands(String callingPackage, String[] commands) {
271 Message msg = mHandlerCaller.obtainMessageIOO(MSG_SUPPORTS_COMMANDS,
272 0, commands, null);
273 SomeArgs args = mHandlerCaller.sendMessageAndWait(msg);
274 if (args != null) {
275 boolean[] res = (boolean[])args.arg1;
276 args.recycle();
277 return res;
278 }
279 return new boolean[commands.length];
280 }
281
282 @Override
283 public void notifyDirectActionsChanged(int taskId, IBinder assistToken) {
284 mHandlerCaller.getHandler().sendMessage(PooledLambda.obtainMessage(
285 VoiceInteractionSession::onDirectActionsInvalidated,
286 VoiceInteractionSession.this, new ActivityId(taskId, assistToken))
287 );
288 }
289
290 @Override
291 public void setKillCallback(ICancellationSignal callback) {
292 mKillCallback = callback;
293 }
294 };
295
296 final IVoiceInteractionSession mSession = new IVoiceInteractionSession.Stub() {
297 @Override
298 public void show(Bundle sessionArgs, int flags,
299 IVoiceInteractionSessionShowCallback showCallback) {
300 mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageIOO(MSG_SHOW,
301 flags, sessionArgs, showCallback));
302 }
303
304 @Override
305 public void hide() {
306 // Remove any pending messages to show the session
307 mHandlerCaller.removeMessages(MSG_SHOW);
308 mHandlerCaller.sendMessage(mHandlerCaller.obtainMessage(MSG_HIDE));
309 }
310
311 @Override
312 public void handleAssist(final int taskId, final IBinder assistToken, final Bundle data,
313 final AssistStructure structure, final AssistContent content, final int index,
314 final int count) {
315 // We want to pre-warm the AssistStructure before handing it off to the main
316 // thread. We also want to do this on a separate thread, so that if the app
317 // is for some reason slow (due to slow filling in of async children in the
318 // structure), we don't block other incoming IPCs (such as the screenshot) to
319 // us (since we are a oneway interface, they get serialized). (Okay?)
320 Thread retriever = new Thread("AssistStructure retriever") {
321 @Override
322 public void run() {
323 Throwable failure = null;
324 if (structure != null) {
325 try {
326 structure.ensureData();
327 } catch (Throwable e) {
328 Log.w(TAG, "Failure retrieving AssistStructure", e);
329 failure = e;
330 }
331 }
332
333 SomeArgs args = SomeArgs.obtain();
334 args.argi1 = taskId;
335 args.arg1 = data;
336 args.arg2 = (failure == null) ? structure : null;
337 args.arg3 = failure;
338 args.arg4 = content;
339 args.arg5 = assistToken;
340 args.argi5 = index;
341 args.argi6 = count;
342
343 mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(
344 MSG_HANDLE_ASSIST, args));
345 }
346 };
347 retriever.start();
348 }
349
350 @Override
351 public void handleScreenshot(Bitmap screenshot) {
352 mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_HANDLE_SCREENSHOT,
353 screenshot));
354 }
355
356 @Override
357 public void taskStarted(Intent intent, int taskId) {
358 mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageIO(MSG_TASK_STARTED,
359 taskId, intent));
360 }
361
362 @Override
363 public void taskFinished(Intent intent, int taskId) {
364 mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageIO(MSG_TASK_FINISHED,
365 taskId, intent));
366 }
367
368 @Override
369 public void closeSystemDialogs() {
370 mHandlerCaller.sendMessage(mHandlerCaller.obtainMessage(MSG_CLOSE_SYSTEM_DIALOGS));
371 }
372
373 @Override
374 public void onLockscreenShown() {
375 mHandlerCaller.sendMessage(mHandlerCaller.obtainMessage(MSG_ON_LOCKSCREEN_SHOWN));
376 }
377
378 @Override
379 public void destroy() {
380 mHandlerCaller.sendMessage(mHandlerCaller.obtainMessage(MSG_DESTROY));
381 }
382
383 @Override
384 public void notifyVisibleActivityInfoChanged(VisibleActivityInfo visibleActivityInfo,
385 int type) {
386 mHandlerCaller.sendMessage(
387 mHandlerCaller.obtainMessageIO(MSG_NOTIFY_VISIBLE_ACTIVITY_INFO_CHANGED, type,
388 visibleActivityInfo));
389 }
390 };
391
392 /**
393 * Base class representing a request from a voice-driver app to perform a particular
394 * voice operation with the user. See related subclasses for the types of requests
395 * that are possible.
396 */
397 public static class Request {
398 final IVoiceInteractorRequest mInterface = new IVoiceInteractorRequest.Stub() {
399 @Override
400 public void cancel() throws RemoteException {
401 VoiceInteractionSession session = mSession.get();
402 if (session != null) {
403 session.mHandlerCaller.sendMessage(
404 session.mHandlerCaller.obtainMessageO(MSG_CANCEL, Request.this));
405 }
406 }
407 };
408 final String mCallingPackage;
409 final int mCallingUid;
410 final IVoiceInteractorCallback mCallback;
411 final WeakReference<VoiceInteractionSession> mSession;
412 final Bundle mExtras;
413
414 Request(String packageName, int uid, IVoiceInteractorCallback callback,
415 VoiceInteractionSession session, Bundle extras) {
416 mCallingPackage = packageName;
417 mCallingUid = uid;
418 mCallback = callback;
419 mSession = session.mWeakRef;
420 mExtras = extras;
421 }
422
423 /**
424 * Return the uid of the application that initiated the request.
425 */
426 public int getCallingUid() {
427 return mCallingUid;
428 }
429
430 /**
431 * Return the package name of the application that initiated the request.
432 */
433 public String getCallingPackage() {
434 return mCallingPackage;
435 }
436
437 /**
438 * Return any additional extra information that was supplied as part of the request.
439 */
440 public Bundle getExtras() {
441 return mExtras;
442 }
443
444 /**
445 * Check whether this request is currently active. A request becomes inactive after
446 * calling {@link #cancel} or a final result method that completes the request. After
447 * this point, further interactions with the request will result in
448 * {@link java.lang.IllegalStateException} errors; you should not catch these errors,
449 * but can use this method if you need to determine the state of the request. Returns
450 * true if the request is still active.
451 */
452 public boolean isActive() {
453 VoiceInteractionSession session = mSession.get();
454 if (session == null) {
455 return false;
456 }
457 return session.isRequestActive(mInterface.asBinder());
458 }
459
460 void finishRequest() {
461 VoiceInteractionSession session = mSession.get();
462 if (session == null) {
463 throw new IllegalStateException("VoiceInteractionSession has been destroyed");
464 }
465 Request req = session.removeRequest(mInterface.asBinder());
466 if (req == null) {
467 throw new IllegalStateException("Request not active: " + this);
468 } else if (req != this) {
469 throw new IllegalStateException("Current active request " + req
470 + " not same as calling request " + this);
471 }
472 }
473
474 /**
475 * Ask the app to cancel this current request.
476 * This also finishes the request (it is no longer active).
477 */
478 public void cancel() {
479 try {
480 if (DEBUG) Log.d(TAG, "sendCancelResult: req=" + mInterface);
481 finishRequest();
482 mCallback.deliverCancel(mInterface);
483 } catch (RemoteException e) {
484 }
485 }
486
487 @Override
488 public String toString() {
489 StringBuilder sb = new StringBuilder(128);
490 DebugUtils.buildShortClassTag(this, sb);
491 sb.append(" ");
492 sb.append(mInterface.asBinder());
493 sb.append(" pkg=");
494 sb.append(mCallingPackage);
495 sb.append(" uid=");
496 UserHandle.formatUid(sb, mCallingUid);
497 sb.append('}');
498 return sb.toString();
499 }
500
501 void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
502 writer.print(prefix); writer.print("mInterface=");
503 writer.println(mInterface.asBinder());
504 writer.print(prefix); writer.print("mCallingPackage="); writer.print(mCallingPackage);
505 writer.print(" mCallingUid="); UserHandle.formatUid(writer, mCallingUid);
506 writer.println();
507 writer.print(prefix); writer.print("mCallback=");
508 writer.println(mCallback.asBinder());
509 if (mExtras != null) {
510 writer.print(prefix); writer.print("mExtras=");
511 writer.println(mExtras);
512 }
513 }
514 }
515
516 /**
517 * A request for confirmation from the user of an operation, as per
518 * {@link android.app.VoiceInteractor.ConfirmationRequest
519 * VoiceInteractor.ConfirmationRequest}.
520 */
521 public static final class ConfirmationRequest extends Request {
522 final VoiceInteractor.Prompt mPrompt;
523
524 ConfirmationRequest(String packageName, int uid, IVoiceInteractorCallback callback,
525 VoiceInteractionSession session, VoiceInteractor.Prompt prompt, Bundle extras) {
526 super(packageName, uid, callback, session, extras);
527 mPrompt = prompt;
528 }
529
530 /**
531 * Return the prompt informing the user of what will happen, as per
532 * {@link android.app.VoiceInteractor.ConfirmationRequest
533 * VoiceInteractor.ConfirmationRequest}.
534 */
535 @Nullable
536 public VoiceInteractor.Prompt getVoicePrompt() {
537 return mPrompt;
538 }
539
540 /**
541 * Return the prompt informing the user of what will happen, as per
542 * {@link android.app.VoiceInteractor.ConfirmationRequest
543 * VoiceInteractor.ConfirmationRequest}.
544 * @deprecated Prefer {@link #getVoicePrompt()} which allows multiple voice prompts.
545 */
546 @Deprecated
547 @Nullable
548 public CharSequence getPrompt() {
549 return (mPrompt != null ? mPrompt.getVoicePromptAt(0) : null);
550 }
551
552 /**
553 * Report that the voice interactor has confirmed the operation with the user, resulting
554 * in a call to
555 * {@link android.app.VoiceInteractor.ConfirmationRequest#onConfirmationResult
556 * VoiceInteractor.ConfirmationRequest.onConfirmationResult}.
557 * This finishes the request (it is no longer active).
558 */
559 public void sendConfirmationResult(boolean confirmed, Bundle result) {
560 try {
561 if (DEBUG) Log.d(TAG, "sendConfirmationResult: req=" + mInterface
562 + " confirmed=" + confirmed + " result=" + result);
563 finishRequest();
564 mCallback.deliverConfirmationResult(mInterface, confirmed, result);
565 } catch (RemoteException e) {
566 }
567 }
568
569 void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
570 super.dump(prefix, fd, writer, args);
571 writer.print(prefix); writer.print("mPrompt=");
572 writer.println(mPrompt);
573 }
574 }
575
576 /**
577 * A request for the user to pick from a set of option, as per
578 * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}.
579 */
580 public static final class PickOptionRequest extends Request {
581 final VoiceInteractor.Prompt mPrompt;
582 final VoiceInteractor.PickOptionRequest.Option[] mOptions;
583
584 PickOptionRequest(String packageName, int uid, IVoiceInteractorCallback callback,
585 VoiceInteractionSession session, VoiceInteractor.Prompt prompt,
586 VoiceInteractor.PickOptionRequest.Option[] options, Bundle extras) {
587 super(packageName, uid, callback, session, extras);
588 mPrompt = prompt;
589 mOptions = options;
590 }
591
592 /**
593 * Return the prompt informing the user of what they are picking, as per
594 * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}.
595 */
596 @Nullable
597 public VoiceInteractor.Prompt getVoicePrompt() {
598 return mPrompt;
599 }
600
601 /**
602 * Return the prompt informing the user of what they are picking, as per
603 * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}.
604 * @deprecated Prefer {@link #getVoicePrompt()} which allows multiple voice prompts.
605 */
606 @Deprecated
607 @Nullable
608 public CharSequence getPrompt() {
609 return (mPrompt != null ? mPrompt.getVoicePromptAt(0) : null);
610 }
611
612 /**
613 * Return the set of options the user is picking from, as per
614 * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}.
615 */
616 public VoiceInteractor.PickOptionRequest.Option[] getOptions() {
617 return mOptions;
618 }
619
620 void sendPickOptionResult(boolean finished,
621 VoiceInteractor.PickOptionRequest.Option[] selections, Bundle result) {
622 try {
623 if (DEBUG) Log.d(TAG, "sendPickOptionResult: req=" + mInterface
624 + " finished=" + finished + " selections=" + Arrays.toString(selections)
625 + " result=" + result);
626 if (finished) {
627 finishRequest();
628 }
629 mCallback.deliverPickOptionResult(mInterface, finished, selections, result);
630 } catch (RemoteException e) {
631 }
632 }
633
634 /**
635 * Report an intermediate option selection from the request, without completing it (the
636 * request is still active and the app is waiting for the final option selection),
637 * resulting in a call to
638 * {@link android.app.VoiceInteractor.PickOptionRequest#onPickOptionResult
639 * VoiceInteractor.PickOptionRequest.onPickOptionResult} with false for finished.
640 */
641 public void sendIntermediatePickOptionResult(
642 VoiceInteractor.PickOptionRequest.Option[] selections, Bundle result) {
643 sendPickOptionResult(false, selections, result);
644 }
645
646 /**
647 * Report the final option selection for the request, completing the request
648 * and resulting in a call to
649 * {@link android.app.VoiceInteractor.PickOptionRequest#onPickOptionResult
650 * VoiceInteractor.PickOptionRequest.onPickOptionResult} with false for finished.
651 * This finishes the request (it is no longer active).
652 */
653 public void sendPickOptionResult(
654 VoiceInteractor.PickOptionRequest.Option[] selections, Bundle result) {
655 sendPickOptionResult(true, selections, result);
656 }
657
658 void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
659 super.dump(prefix, fd, writer, args);
660 writer.print(prefix); writer.print("mPrompt=");
661 writer.println(mPrompt);
662 if (mOptions != null) {
663 writer.print(prefix); writer.println("Options:");
664 for (int i=0; i<mOptions.length; i++) {
665 VoiceInteractor.PickOptionRequest.Option op = mOptions[i];
666 writer.print(prefix); writer.print(" #"); writer.print(i); writer.println(":");
667 writer.print(prefix); writer.print(" mLabel=");
668 writer.println(op.getLabel());
669 writer.print(prefix); writer.print(" mIndex=");
670 writer.println(op.getIndex());
671 if (op.countSynonyms() > 0) {
672 writer.print(prefix); writer.println(" Synonyms:");
673 for (int j=0; j<op.countSynonyms(); j++) {
674 writer.print(prefix); writer.print(" #"); writer.print(j);
675 writer.print(": "); writer.println(op.getSynonymAt(j));
676 }
677 }
678 if (op.getExtras() != null) {
679 writer.print(prefix); writer.print(" mExtras=");
680 writer.println(op.getExtras());
681 }
682 }
683 }
684 }
685 }
686
687 /**
688 * A request to simply inform the user that the voice operation has completed, as per
689 * {@link android.app.VoiceInteractor.CompleteVoiceRequest
690 * VoiceInteractor.CompleteVoiceRequest}.
691 */
692 public static final class CompleteVoiceRequest extends Request {
693 final VoiceInteractor.Prompt mPrompt;
694
695 CompleteVoiceRequest(String packageName, int uid, IVoiceInteractorCallback callback,
696 VoiceInteractionSession session, VoiceInteractor.Prompt prompt, Bundle extras) {
697 super(packageName, uid, callback, session, extras);
698 mPrompt = prompt;
699 }
700
701 /**
702 * Return the message informing the user of the completion, as per
703 * {@link android.app.VoiceInteractor.CompleteVoiceRequest
704 * VoiceInteractor.CompleteVoiceRequest}.
705 */
706 @Nullable
707 public VoiceInteractor.Prompt getVoicePrompt() {
708 return mPrompt;
709 }
710
711 /**
712 * Return the message informing the user of the completion, as per
713 * {@link android.app.VoiceInteractor.CompleteVoiceRequest
714 * VoiceInteractor.CompleteVoiceRequest}.
715 * @deprecated Prefer {@link #getVoicePrompt()} which allows a separate visual message.
716 */
717 @Deprecated
718 @Nullable
719 public CharSequence getMessage() {
720 return (mPrompt != null ? mPrompt.getVoicePromptAt(0) : null);
721 }
722
723 /**
724 * Report that the voice interactor has finished completing the voice operation, resulting
725 * in a call to
726 * {@link android.app.VoiceInteractor.CompleteVoiceRequest#onCompleteResult
727 * VoiceInteractor.CompleteVoiceRequest.onCompleteResult}.
728 * This finishes the request (it is no longer active).
729 */
730 public void sendCompleteResult(Bundle result) {
731 try {
732 if (DEBUG) Log.d(TAG, "sendCompleteVoiceResult: req=" + mInterface
733 + " result=" + result);
734 finishRequest();
735 mCallback.deliverCompleteVoiceResult(mInterface, result);
736 } catch (RemoteException e) {
737 }
738 }
739
740 void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
741 super.dump(prefix, fd, writer, args);
742 writer.print(prefix); writer.print("mPrompt=");
743 writer.println(mPrompt);
744 }
745 }
746
747 /**
748 * A request to report that the current user interaction can not be completed with voice, as per
749 * {@link android.app.VoiceInteractor.AbortVoiceRequest VoiceInteractor.AbortVoiceRequest}.
750 */
751 public static final class AbortVoiceRequest extends Request {
752 final VoiceInteractor.Prompt mPrompt;
753
754 AbortVoiceRequest(String packageName, int uid, IVoiceInteractorCallback callback,
755 VoiceInteractionSession session, VoiceInteractor.Prompt prompt, Bundle extras) {
756 super(packageName, uid, callback, session, extras);
757 mPrompt = prompt;
758 }
759
760 /**
761 * Return the message informing the user of the problem, as per
762 * {@link android.app.VoiceInteractor.AbortVoiceRequest VoiceInteractor.AbortVoiceRequest}.
763 */
764 @Nullable
765 public VoiceInteractor.Prompt getVoicePrompt() {
766 return mPrompt;
767 }
768
769 /**
770 * Return the message informing the user of the problem, as per
771 * {@link android.app.VoiceInteractor.AbortVoiceRequest VoiceInteractor.AbortVoiceRequest}.
772 * @deprecated Prefer {@link #getVoicePrompt()} which allows a separate visual message.
773 */
774 @Deprecated
775 @Nullable
776 public CharSequence getMessage() {
777 return (mPrompt != null ? mPrompt.getVoicePromptAt(0) : null);
778 }
779
780 /**
781 * Report that the voice interactor has finished aborting the voice operation, resulting
782 * in a call to
783 * {@link android.app.VoiceInteractor.AbortVoiceRequest#onAbortResult
784 * VoiceInteractor.AbortVoiceRequest.onAbortResult}. This finishes the request (it
785 * is no longer active).
786 */
787 public void sendAbortResult(Bundle result) {
788 try {
789 if (DEBUG) Log.d(TAG, "sendConfirmResult: req=" + mInterface
790 + " result=" + result);
791 finishRequest();
792 mCallback.deliverAbortVoiceResult(mInterface, result);
793 } catch (RemoteException e) {
794 }
795 }
796
797 void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
798 super.dump(prefix, fd, writer, args);
799 writer.print(prefix); writer.print("mPrompt=");
800 writer.println(mPrompt);
801 }
802 }
803
804 /**
805 * A generic vendor-specific request, as per
806 * {@link android.app.VoiceInteractor.CommandRequest VoiceInteractor.CommandRequest}.
807 */
808 public static final class CommandRequest extends Request {
809 final String mCommand;
810
811 CommandRequest(String packageName, int uid, IVoiceInteractorCallback callback,
812 VoiceInteractionSession session, String command, Bundle extras) {
813 super(packageName, uid, callback, session, extras);
814 mCommand = command;
815 }
816
817 /**
818 * Return the command that is being executed, as per
819 * {@link android.app.VoiceInteractor.CommandRequest VoiceInteractor.CommandRequest}.
820 */
821 public String getCommand() {
822 return mCommand;
823 }
824
825 void sendCommandResult(boolean finished, Bundle result) {
826 try {
827 if (DEBUG) Log.d(TAG, "sendCommandResult: req=" + mInterface
828 + " result=" + result);
829 if (finished) {
830 finishRequest();
831 }
832 mCallback.deliverCommandResult(mInterface, finished, result);
833 } catch (RemoteException e) {
834 }
835 }
836
837 /**
838 * Report an intermediate result of the request, without completing it (the request
839 * is still active and the app is waiting for the final result), resulting in a call to
840 * {@link android.app.VoiceInteractor.CommandRequest#onCommandResult
841 * VoiceInteractor.CommandRequest.onCommandResult} with false for isCompleted.
842 */
843 public void sendIntermediateResult(Bundle result) {
844 sendCommandResult(false, result);
845 }
846
847 /**
848 * Report the final result of the request, completing the request and resulting in a call to
849 * {@link android.app.VoiceInteractor.CommandRequest#onCommandResult
850 * VoiceInteractor.CommandRequest.onCommandResult} with true for isCompleted.
851 * This finishes the request (it is no longer active).
852 */
853 public void sendResult(Bundle result) {
854 sendCommandResult(true, result);
855 }
856
857 void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
858 super.dump(prefix, fd, writer, args);
859 writer.print(prefix); writer.print("mCommand=");
860 writer.println(mCommand);
861 }
862 }
863
864 static final int MSG_START_CONFIRMATION = 1;
865 static final int MSG_START_PICK_OPTION = 2;
866 static final int MSG_START_COMPLETE_VOICE = 3;
867 static final int MSG_START_ABORT_VOICE = 4;
868 static final int MSG_START_COMMAND = 5;
869 static final int MSG_SUPPORTS_COMMANDS = 6;
870 static final int MSG_CANCEL = 7;
871
872 static final int MSG_TASK_STARTED = 100;
873 static final int MSG_TASK_FINISHED = 101;
874 static final int MSG_CLOSE_SYSTEM_DIALOGS = 102;
875 static final int MSG_DESTROY = 103;
876 static final int MSG_HANDLE_ASSIST = 104;
877 static final int MSG_HANDLE_SCREENSHOT = 105;
878 static final int MSG_SHOW = 106;
879 static final int MSG_HIDE = 107;
880 static final int MSG_ON_LOCKSCREEN_SHOWN = 108;
881 static final int MSG_NOTIFY_VISIBLE_ACTIVITY_INFO_CHANGED = 109;
882 static final int MSG_REGISTER_VISIBLE_ACTIVITY_CALLBACK = 110;
883 static final int MSG_UNREGISTER_VISIBLE_ACTIVITY_CALLBACK = 111;
884
885 class MyCallbacks implements HandlerCaller.Callback, VoiceInteractionWindow.Callback {
886 @Override
887 public void executeMessage(Message msg) {
888 SomeArgs args = null;
889 switch (msg.what) {
890 case MSG_START_CONFIRMATION:
891 if (DEBUG) Log.d(TAG, "onConfirm: req=" + msg.obj);
892 onRequestConfirmation((ConfirmationRequest) msg.obj);
893 break;
894 case MSG_START_PICK_OPTION:
895 if (DEBUG) Log.d(TAG, "onPickOption: req=" + msg.obj);
896 onRequestPickOption((PickOptionRequest) msg.obj);
897 break;
898 case MSG_START_COMPLETE_VOICE:
899 if (DEBUG) Log.d(TAG, "onCompleteVoice: req=" + msg.obj);
900 onRequestCompleteVoice((CompleteVoiceRequest) msg.obj);
901 break;
902 case MSG_START_ABORT_VOICE:
903 if (DEBUG) Log.d(TAG, "onAbortVoice: req=" + msg.obj);
904 onRequestAbortVoice((AbortVoiceRequest) msg.obj);
905 break;
906 case MSG_START_COMMAND:
907 if (DEBUG) Log.d(TAG, "onCommand: req=" + msg.obj);
908 onRequestCommand((CommandRequest) msg.obj);
909 break;
910 case MSG_SUPPORTS_COMMANDS:
911 args = (SomeArgs)msg.obj;
912 if (DEBUG) Log.d(TAG, "onGetSupportedCommands: cmds=" + args.arg1);
913 args.arg1 = onGetSupportedCommands((String[]) args.arg1);
914 args.complete();
915 args = null;
916 break;
917 case MSG_CANCEL:
918 if (DEBUG) Log.d(TAG, "onCancel: req=" + ((Request)msg.obj));
919 onCancelRequest((Request) msg.obj);
920 break;
921 case MSG_TASK_STARTED:
922 if (DEBUG) Log.d(TAG, "onTaskStarted: intent=" + msg.obj
923 + " taskId=" + msg.arg1);
924 onTaskStarted((Intent) msg.obj, msg.arg1);
925 break;
926 case MSG_TASK_FINISHED:
927 if (DEBUG) Log.d(TAG, "onTaskFinished: intent=" + msg.obj
928 + " taskId=" + msg.arg1);
929 onTaskFinished((Intent) msg.obj, msg.arg1);
930 break;
931 case MSG_CLOSE_SYSTEM_DIALOGS:
932 if (DEBUG) Log.d(TAG, "onCloseSystemDialogs");
933 onCloseSystemDialogs();
934 break;
935 case MSG_DESTROY:
936 if (DEBUG) Log.d(TAG, "doDestroy");
937 doDestroy();
938 break;
939 case MSG_HANDLE_ASSIST:
940 args = (SomeArgs)msg.obj;
941 if (DEBUG) Log.d(TAG, "onHandleAssist: taskId=" + args.argi1
942 + "assistToken=" + args.arg5 + " data=" + args.arg1
943 + " structure=" + args.arg2 + " content=" + args.arg3
944 + " activityIndex=" + args.argi5 + " activityCount=" + args.argi6);
945 doOnHandleAssist(args.argi1, (IBinder) args.arg5, (Bundle) args.arg1,
946 (AssistStructure) args.arg2, (Throwable) args.arg3,
947 (AssistContent) args.arg4, args.argi5, args.argi6);
948 break;
949 case MSG_HANDLE_SCREENSHOT:
950 if (DEBUG) Log.d(TAG, "onHandleScreenshot: " + msg.obj);
951 onHandleScreenshot((Bitmap) msg.obj);
952 break;
953 case MSG_SHOW:
954 args = (SomeArgs)msg.obj;
955 if (DEBUG) Log.d(TAG, "doShow: args=" + args.arg1
956 + " flags=" + msg.arg1
957 + " showCallback=" + args.arg2);
958 doShow((Bundle) args.arg1, msg.arg1,
959 (IVoiceInteractionSessionShowCallback) args.arg2);
960 break;
961 case MSG_HIDE:
962 if (DEBUG) Log.d(TAG, "doHide");
963 doHide();
964 break;
965 case MSG_ON_LOCKSCREEN_SHOWN:
966 if (DEBUG) Log.d(TAG, "onLockscreenShown");
967 onLockscreenShown();
968 break;
969 case MSG_NOTIFY_VISIBLE_ACTIVITY_INFO_CHANGED:
970 if (DEBUG) {
971 Log.d(TAG,
972 "doNotifyVisibleActivityInfoChanged: visibleActivityInfo=" + msg.obj
973 + " type=" + msg.arg1);
974 }
975 doNotifyVisibleActivityInfoChanged((VisibleActivityInfo) msg.obj, msg.arg1);
976 break;
977 case MSG_REGISTER_VISIBLE_ACTIVITY_CALLBACK:
978 if (DEBUG) {
979 Log.d(TAG, "doRegisterVisibleActivityCallback");
980 }
981 args = (SomeArgs) msg.obj;
982 doRegisterVisibleActivityCallback((Executor) args.arg1,
983 (VisibleActivityCallback) args.arg2);
984 break;
985 case MSG_UNREGISTER_VISIBLE_ACTIVITY_CALLBACK:
986 if (DEBUG) {
987 Log.d(TAG, "doUnregisterVisibleActivityCallback");
988 }
989 doUnregisterVisibleActivityCallback((VisibleActivityCallback) msg.obj);
990 break;
991 }
992 if (args != null) {
993 args.recycle();
994 }
995 }
996
997 @Override
998 public void onBackPressed() {
999 VoiceInteractionSession.this.onBackPressed();
1000 }
1001 }
1002
1003 final MyCallbacks mCallbacks = new MyCallbacks();
1004
1005 /**
1006 * Information about where interesting parts of the input method UI appear.
1007 */
1008 public static final class Insets {
1009 /**
1010 * This is the part of the UI that is the main content. It is
1011 * used to determine the basic space needed, to resize/pan the
1012 * application behind. It is assumed that this inset does not
1013 * change very much, since any change will cause a full resize/pan
1014 * of the application behind. This value is relative to the top edge
1015 * of the input method window.
1016 */
1017 public final Rect contentInsets = new Rect();
1018
1019 /**
1020 * This is the region of the UI that is touchable. It is used when
1021 * {@link #touchableInsets} is set to {@link #TOUCHABLE_INSETS_REGION}.
1022 * The region should be specified relative to the origin of the window frame.
1023 */
1024 public final Region touchableRegion = new Region();
1025
1026 /**
1027 * Option for {@link #touchableInsets}: the entire window frame
1028 * can be touched.
1029 */
1030 public static final int TOUCHABLE_INSETS_FRAME
1031 = ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME;
1032
1033 /**
1034 * Option for {@link #touchableInsets}: the area inside of
1035 * the content insets can be touched.
1036 */
1037 public static final int TOUCHABLE_INSETS_CONTENT
1038 = ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_CONTENT;
1039
1040 /**
1041 * Option for {@link #touchableInsets}: the region specified by
1042 * {@link #touchableRegion} can be touched.
1043 */
1044 public static final int TOUCHABLE_INSETS_REGION
1045 = ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION;
1046
1047 /**
1048 * Determine which area of the window is touchable by the user. May
1049 * be one of: {@link #TOUCHABLE_INSETS_FRAME},
1050 * {@link #TOUCHABLE_INSETS_CONTENT}, or {@link #TOUCHABLE_INSETS_REGION}.
1051 */
1052 public int touchableInsets;
1053 }
1054
1055 final ViewTreeObserver.OnComputeInternalInsetsListener mInsetsComputer =
1056 new ViewTreeObserver.OnComputeInternalInsetsListener() {
1057 public void onComputeInternalInsets(ViewTreeObserver.InternalInsetsInfo info) {
1058 onComputeInsets(mTmpInsets);
1059 info.contentInsets.set(mTmpInsets.contentInsets);
1060 info.visibleInsets.set(mTmpInsets.contentInsets);
1061 info.touchableRegion.set(mTmpInsets.touchableRegion);
1062 info.setTouchableInsets(mTmpInsets.touchableInsets);
1063 }
1064 };
1065
1066 public VoiceInteractionSession(Context context) {
1067 this(context, new Handler());
1068 }
1069
1070 public VoiceInteractionSession(Context context, Handler handler) {
1071 mContext = context;
1072 mHandlerCaller = new HandlerCaller(context, handler.getLooper(),
1073 mCallbacks, true);
1074 }
1075
1076 public Context getContext() {
1077 return mContext;
1078 }
1079
1080 void addRequest(Request req) {
1081 synchronized (this) {
1082 mActiveRequests.put(req.mInterface.asBinder(), req);
1083 }
1084 }
1085
1086 boolean isRequestActive(IBinder reqInterface) {
1087 synchronized (this) {
1088 return mActiveRequests.containsKey(reqInterface);
1089 }
1090 }
1091
1092 Request removeRequest(IBinder reqInterface) {
1093 synchronized (this) {
1094 return mActiveRequests.remove(reqInterface);
1095 }
1096 }
1097
1098 void doCreate(IVoiceInteractionManagerService service, IBinder token) {
1099 mSystemService = service;
1100 mToken = token;
1101 onCreate();
1102 }
1103
1104 void doShow(Bundle args, int flags, final IVoiceInteractionSessionShowCallback showCallback) {
1105 if (DEBUG) Log.v(TAG, "Showing window: mWindowAdded=" + mWindowAdded
1106 + " mWindowVisible=" + mWindowVisible);
1107
1108 if (mInShowWindow) {
1109 Log.w(TAG, "Re-entrance in to showWindow");
1110 return;
1111 }
1112
1113 try {
1114 mInShowWindow = true;
1115 onPrepareShow(args, flags);
1116 if (!mWindowVisible) {
1117 ensureWindowAdded();
1118 }
1119 onShow(args, flags);
1120 if (!mWindowVisible) {
1121 mWindowVisible = true;
1122 if (mUiEnabled) {
1123 showWindow();
1124 }
1125 }
1126 if (showCallback != null) {
1127 if (mUiEnabled) {
1128 mRootView.invalidate();
1129 mRootView.getViewTreeObserver().addOnPreDrawListener(
1130 new ViewTreeObserver.OnPreDrawListener() {
1131 @Override
1132 public boolean onPreDraw() {
1133 mRootView.getViewTreeObserver().removeOnPreDrawListener(this);
1134 try {
1135 showCallback.onShown();
1136 } catch (RemoteException e) {
1137 Log.w(TAG, "Error calling onShown", e);
1138 }
1139 return true;
1140 }
1141 });
1142 } else {
1143 try {
1144 showCallback.onShown();
1145 } catch (RemoteException e) {
1146 Log.w(TAG, "Error calling onShown", e);
1147 }
1148 }
1149 }
1150 } finally {
1151 mWindowWasVisible = true;
1152 mInShowWindow = false;
1153 }
1154 }
1155
1156 void doHide() {
1157 if (mWindowVisible) {
1158 ensureWindowHidden();
1159 mWindowVisible = false;
1160 onHide();
1161 }
1162 }
1163
1164 void doDestroy() {
1165 onDestroy();
1166 if (mKillCallback != null) {
1167 try {
1168 mKillCallback.cancel();
1169 } catch (RemoteException e) {
1170 /* ignore */
1171 }
1172 mKillCallback = null;
1173 }
1174 if (mInitialized) {
1175 mRootView.getViewTreeObserver().removeOnComputeInternalInsetsListener(
1176 mInsetsComputer);
1177 if (mWindowAdded) {
1178 mWindow.dismiss();
1179 mWindowAdded = false;
1180 }
1181 mInitialized = false;
1182 }
1183 }
1184
1185 private void doNotifyVisibleActivityInfoChanged(VisibleActivityInfo visibleActivityInfo,
1186 int type) {
1187
1188 if (mVisibleActivityCallbacks.isEmpty()) {
1189 return;
1190 }
1191
1192 switch (type) {
1193 case VisibleActivityInfo.TYPE_ACTIVITY_ADDED:
1194 notifyVisibleActivityChanged(visibleActivityInfo, type);
1195 mVisibleActivityInfos.add(visibleActivityInfo);
1196 break;
1197 case VisibleActivityInfo.TYPE_ACTIVITY_REMOVED:
1198 notifyVisibleActivityChanged(visibleActivityInfo, type);
1199 mVisibleActivityInfos.remove(visibleActivityInfo);
1200 break;
1201 }
1202 }
1203
1204 private void doRegisterVisibleActivityCallback(@NonNull @CallbackExecutor Executor executor,
1205 @NonNull VisibleActivityCallback callback) {
1206 if (mVisibleActivityCallbacks.containsKey(callback)) {
1207 if (DEBUG) {
1208 Log.d(TAG, "doRegisterVisibleActivityCallback: callback has registered");
1209 }
1210 return;
1211 }
1212
1213 int preCallbackCount = mVisibleActivityCallbacks.size();
1214 mVisibleActivityCallbacks.put(callback, executor);
1215
1216 if (preCallbackCount == 0) {
1217 try {
1218 mSystemService.startListeningVisibleActivityChanged(mToken);
1219 } catch (RemoteException e) {
1220 e.rethrowFromSystemServer();
1221 }
1222 } else {
1223 for (int i = 0; i < mVisibleActivityInfos.size(); i++) {
1224 final VisibleActivityInfo visibleActivityInfo = mVisibleActivityInfos.get(i);
1225 executor.execute(() -> callback.onVisible(visibleActivityInfo));
1226 }
1227 }
1228 }
1229
1230 private void doUnregisterVisibleActivityCallback(@NonNull VisibleActivityCallback callback) {
1231 mVisibleActivityCallbacks.remove(callback);
1232
1233 if (mVisibleActivityCallbacks.size() == 0) {
1234 mVisibleActivityInfos.clear();
1235 try {
1236 mSystemService.stopListeningVisibleActivityChanged(mToken);
1237 } catch (RemoteException e) {
1238 e.rethrowFromSystemServer();
1239 }
1240 }
1241 }
1242
1243 private void notifyVisibleActivityChanged(VisibleActivityInfo visibleActivityInfo, int type) {
1244 for (Map.Entry<VisibleActivityCallback, Executor> e :
1245 mVisibleActivityCallbacks.entrySet()) {
1246 final Executor executor = e.getValue();
1247 final VisibleActivityCallback visibleActivityCallback = e.getKey();
1248
1249 switch (type) {
1250 case VisibleActivityInfo.TYPE_ACTIVITY_ADDED:
1251 Binder.withCleanCallingIdentity(() -> {
1252 executor.execute(
1253 () -> visibleActivityCallback.onVisible(visibleActivityInfo));
1254 });
1255 break;
1256 case VisibleActivityInfo.TYPE_ACTIVITY_REMOVED:
1257 Binder.withCleanCallingIdentity(() -> {
1258 executor.execute(() -> visibleActivityCallback.onInvisible(
1259 visibleActivityInfo.getActivityId()));
1260 });
1261 break;
1262 }
1263 }
1264 }
1265
1266 void ensureWindowCreated() {
1267 if (mInitialized) {
1268 return;
1269 }
1270
1271 if (!mUiEnabled) {
1272 throw new IllegalStateException("setUiEnabled is false");
1273 }
1274
1275 mInitialized = true;
1276 mInflater = (LayoutInflater)mContext.getSystemService(
1277 Context.LAYOUT_INFLATER_SERVICE);
1278 mWindow = new VoiceInteractionWindow(mContext, "VoiceInteractionSession", mTheme,
1279 mCallbacks, this, mDispatcherState,
1280 WindowManager.LayoutParams.TYPE_VOICE_INTERACTION, Gravity.BOTTOM, true);
1281 mWindow.getWindow().getAttributes().setFitInsetsTypes(0 /* types */);
1282 mWindow.getWindow().addFlags(
1283 WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED |
1284 WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
1285 WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
1286
1287 mThemeAttrs = mContext.obtainStyledAttributes(android.R.styleable.VoiceInteractionSession);
1288 mRootView = mInflater.inflate(
1289 com.android.internal.R.layout.voice_interaction_session, null);
1290 mRootView.setSystemUiVisibility(
1291 View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
1292 | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1293 mWindow.setContentView(mRootView);
1294 mRootView.getViewTreeObserver().addOnComputeInternalInsetsListener(mInsetsComputer);
1295
1296 mContentFrame = (FrameLayout)mRootView.findViewById(android.R.id.content);
1297
1298 mWindow.getWindow().setLayout(MATCH_PARENT, MATCH_PARENT);
1299 mWindow.setToken(mToken);
1300 }
1301
1302 void ensureWindowAdded() {
1303 if (mUiEnabled && !mWindowAdded) {
1304 mWindowAdded = true;
1305 ensureWindowCreated();
1306 View v = onCreateContentView();
1307 if (v != null) {
1308 setContentView(v);
1309 }
1310 }
1311 }
1312
1313 void showWindow() {
1314 if (mWindow != null) {
1315 mWindow.show();
1316 try {
1317 mSystemService.setSessionWindowVisible(mToken, true);
1318 } catch (RemoteException e) {
1319 Log.w(TAG, "Failed to notify session window shown", e);
1320 }
1321 }
1322 }
1323
1324 void ensureWindowHidden() {
1325 if (mWindow != null) {
1326 mWindow.hide();
1327 try {
1328 mSystemService.setSessionWindowVisible(mToken, false);
1329 } catch (RemoteException e) {
1330 Log.w(TAG, "Failed to notify session window hidden", e);
1331 }
1332 }
1333 }
1334
1335 /**
1336 * Equivalent to {@link VoiceInteractionService#setDisabledShowContext
1337 * VoiceInteractionService.setDisabledShowContext(int)}.
1338 */
1339 public void setDisabledShowContext(int flags) {
1340 try {
1341 mSystemService.setDisabledShowContext(flags);
1342 } catch (RemoteException e) {
1343 }
1344 }
1345
1346 /**
1347 * Equivalent to {@link VoiceInteractionService#getDisabledShowContext
1348 * VoiceInteractionService.getDisabledShowContext}.
1349 */
1350 public int getDisabledShowContext() {
1351 try {
1352 return mSystemService.getDisabledShowContext();
1353 } catch (RemoteException e) {
1354 return 0;
1355 }
1356 }
1357
1358 /**
1359 * Return which show context flags have been disabled by the user through the system
1360 * settings UI, so the session will never get this data. Returned flags are any combination of
1361 * {@link VoiceInteractionSession#SHOW_WITH_ASSIST VoiceInteractionSession.SHOW_WITH_ASSIST} and
1362 * {@link VoiceInteractionSession#SHOW_WITH_SCREENSHOT
1363 * VoiceInteractionSession.SHOW_WITH_SCREENSHOT}. Note that this only tells you about
1364 * global user settings, not about restrictions that may be applied contextual based on
1365 * the current application the user is in or other transient states.
1366 */
1367 public int getUserDisabledShowContext() {
1368 try {
1369 return mSystemService.getUserDisabledShowContext();
1370 } catch (RemoteException e) {
1371 return 0;
1372 }
1373 }
1374
1375 /**
1376 * Show the UI for this session. This asks the system to go through the process of showing
1377 * your UI, which will eventually culminate in {@link #onShow}. This is similar to calling
1378 * {@link VoiceInteractionService#showSession VoiceInteractionService.showSession}.
1379 * @param args Arbitrary arguments that will be propagated {@link #onShow}.
1380 * @param flags Indicates additional optional behavior that should be performed. May
1381 * be any combination of
1382 * {@link VoiceInteractionSession#SHOW_WITH_ASSIST VoiceInteractionSession.SHOW_WITH_ASSIST} and
1383 * {@link VoiceInteractionSession#SHOW_WITH_SCREENSHOT
1384 * VoiceInteractionSession.SHOW_WITH_SCREENSHOT}
1385 * to request that the system generate and deliver assist data on the current foreground
1386 * app as part of showing the session UI.
1387 */
1388 public void show(Bundle args, int flags) {
1389 if (mToken == null) {
1390 throw new IllegalStateException("Can't call before onCreate()");
1391 }
1392 try {
1393 mSystemService.showSessionFromSession(mToken, args, flags);
1394 } catch (RemoteException e) {
1395 }
1396 }
1397
1398 /**
1399 * Hide the session's UI, if currently shown. Call this when you are done with your
1400 * user interaction.
1401 */
1402 public void hide() {
1403 if (mToken == null) {
1404 throw new IllegalStateException("Can't call before onCreate()");
1405 }
1406 try {
1407 mSystemService.hideSessionFromSession(mToken);
1408 } catch (RemoteException e) {
1409 }
1410 }
1411
1412 /**
1413 * Control whether the UI layer for this session is enabled. It is enabled by default.
1414 * If set to false, you will not be able to provide a UI through {@link #onCreateContentView()}.
1415 */
1416 public void setUiEnabled(boolean enabled) {
1417 if (mUiEnabled != enabled) {
1418 mUiEnabled = enabled;
1419 if (mWindowVisible) {
1420 if (enabled) {
1421 ensureWindowAdded();
1422 showWindow();
1423 } else {
1424 ensureWindowHidden();
1425 }
1426 }
1427 }
1428 }
1429
1430 /**
1431 * You can call this to customize the theme used by your IME's window.
1432 * This must be set before {@link #onCreate}, so you
1433 * will typically call it in your constructor with the resource ID
1434 * of your custom theme.
1435 */
1436 public void setTheme(int theme) {
1437 if (mWindow != null) {
1438 throw new IllegalStateException("Must be called before onCreate()");
1439 }
1440 mTheme = theme;
1441 }
1442
1443 /**
1444 * Ask that a new activity be started for voice interaction. This will create a
1445 * new dedicated task in the activity manager for this voice interaction session;
1446 * this means that {@link Intent#FLAG_ACTIVITY_NEW_TASK Intent.FLAG_ACTIVITY_NEW_TASK}
1447 * will be set for you to make it a new task.
1448 *
1449 * <p>The newly started activity will be displayed to the user in a special way, as
1450 * a layer under the voice interaction UI.</p>
1451 *
1452 * <p>As the voice activity runs, it can retrieve a {@link android.app.VoiceInteractor}
1453 * through which it can perform voice interactions through your session. These requests
1454 * for voice interactions will appear as callbacks on {@link #onGetSupportedCommands},
1455 * {@link #onRequestConfirmation}, {@link #onRequestPickOption},
1456 * {@link #onRequestCompleteVoice}, {@link #onRequestAbortVoice},
1457 * or {@link #onRequestCommand}
1458 *
1459 * <p>You will receive a call to {@link #onTaskStarted} when the task starts up
1460 * and {@link #onTaskFinished} when the last activity has finished.
1461 *
1462 * @param intent The Intent to start this voice interaction. The given Intent will
1463 * always have {@link Intent#CATEGORY_VOICE Intent.CATEGORY_VOICE} added to it, since
1464 * this is part of a voice interaction.
1465 */
1466 public void startVoiceActivity(Intent intent) {
1467 if (mToken == null) {
1468 throw new IllegalStateException("Can't call before onCreate()");
1469 }
1470 try {
1471 intent.migrateExtraStreamToClipData(mContext);
1472 intent.prepareToLeaveProcess(mContext);
1473 int res = mSystemService.startVoiceActivity(mToken, intent,
1474 intent.resolveType(mContext.getContentResolver()),
1475 mContext.getAttributionTag());
1476 Instrumentation.checkStartActivityResult(res, intent);
1477 } catch (RemoteException e) {
1478 }
1479 }
1480
1481 /**
1482 * <p>Ask that a new assistant activity be started. This will create a new task in the
1483 * in activity manager: this means that
1484 * {@link Intent#FLAG_ACTIVITY_NEW_TASK Intent.FLAG_ACTIVITY_NEW_TASK}
1485 * will be set for you to make it a new task.</p>
1486 *
1487 * <p>The newly started activity will be displayed on top of other activities in the system
1488 * in a new layer that is not affected by multi-window mode. Tasks started from this activity
1489 * will go into the normal activity layer and not this new layer.</p>
1490 *
1491 * <p>By default, the system will create a window for the UI for this session. If you are using
1492 * an assistant activity instead, then you can disable the window creation by calling
1493 * {@link #setUiEnabled} in {@link #onPrepareShow(Bundle, int)}.</p>
1494 */
1495 public void startAssistantActivity(Intent intent) {
1496 if (mToken == null) {
1497 throw new IllegalStateException("Can't call before onCreate()");
1498 }
1499 try {
1500 intent.migrateExtraStreamToClipData(mContext);
1501 intent.prepareToLeaveProcess(mContext);
1502 int res = mSystemService.startAssistantActivity(mToken, intent,
1503 intent.resolveType(mContext.getContentResolver()),
1504 mContext.getAttributionTag());
1505 Instrumentation.checkStartActivityResult(res, intent);
1506 } catch (RemoteException e) {
1507 }
1508 }
1509
1510 /**
1511 * Requests a list of supported actions from an app.
1512 *
1513 * @param activityId Ths activity id of the app to get the actions from.
1514 * @param cancellationSignal A signal to cancel the operation in progress,
1515 * or {@code null} if none.
1516 * @param resultExecutor The handler to receive the callback.
1517 * @param callback The callback to receive the response.
1518 */
1519 public final void requestDirectActions(@NonNull ActivityId activityId,
1520 @Nullable CancellationSignal cancellationSignal,
1521 @NonNull @CallbackExecutor Executor resultExecutor,
1522 @NonNull Consumer<List<DirectAction>> callback) {
1523 Objects.requireNonNull(activityId);
1524 Objects.requireNonNull(resultExecutor);
1525 Objects.requireNonNull(callback);
1526 if (mToken == null) {
1527 throw new IllegalStateException("Can't call before onCreate()");
1528 }
1529
1530 if (cancellationSignal != null) {
1531 cancellationSignal.throwIfCanceled();
1532 }
1533
1534 final RemoteCallback cancellationCallback = (cancellationSignal != null)
1535 ? new RemoteCallback(b -> {
1536 if (b != null) {
1537 final IBinder cancellation = b.getBinder(
1538 VoiceInteractor.KEY_CANCELLATION_SIGNAL);
1539 if (cancellation != null) {
1540 cancellationSignal.setRemote(ICancellationSignal.Stub.asInterface(
1541 cancellation));
1542 }
1543 }
1544 })
1545 : null;
1546
1547 try {
1548 mSystemService.requestDirectActions(mToken, activityId.getTaskId(),
1549 activityId.getAssistToken(), cancellationCallback,
1550 new RemoteCallback(createSafeResultListener((result) -> {
1551 List<DirectAction> list;
1552 if (result == null) {
1553 list = Collections.emptyList();
1554 } else {
1555 final ParceledListSlice<DirectAction> pls = result.getParcelable(
1556 DirectAction.KEY_ACTIONS_LIST);
1557 if (pls != null) {
1558 final List<DirectAction> receivedList = pls.getList();
1559 list = (receivedList != null) ? receivedList : Collections.emptyList();
1560 } else {
1561 list = Collections.emptyList();
1562 }
1563 }
1564 resultExecutor.execute(() -> callback.accept(list));
1565 })));
1566 } catch (RemoteException e) {
1567 e.rethrowFromSystemServer();
1568 }
1569 }
1570
1571 /**
1572 * Called when the direct actions are invalidated.
1573 */
1574 public void onDirectActionsInvalidated(@NonNull ActivityId activityId) {
1575
1576 }
1577
1578 /**
1579 * Asks that an action be performed by the app. This will send a request to the app which
1580 * provided this action.
1581 *
1582 * <p> An action could take time to execute and the result is provided asynchronously
1583 * via a callback. If the action is taking longer and you want to cancel its execution
1584 * you can pass in a cancellation signal through which to notify the app to abort the
1585 * action.
1586 *
1587 * @param action The action to be performed.
1588 * @param extras Any optional extras sent to the app as part of the request
1589 * @param cancellationSignal A signal to cancel the operation in progress,
1590 * or {@code null} if none.
1591 * @param resultExecutor The handler to receive the callback.
1592 * @param resultListener The callback to receive the response.
1593 *
1594 * @see #requestDirectActions(ActivityId, CancellationSignal, Executor, Consumer)
1595 * @see Activity#onGetDirectActions(CancellationSignal, Consumer)
1596 */
1597 public final void performDirectAction(@NonNull DirectAction action, @Nullable Bundle extras,
1598 @Nullable CancellationSignal cancellationSignal,
1599 @NonNull @CallbackExecutor Executor resultExecutor,
1600 @NonNull Consumer<Bundle> resultListener) {
1601 if (mToken == null) {
1602 throw new IllegalStateException("Can't call before onCreate()");
1603 }
1604 Objects.requireNonNull(resultExecutor);
1605 Objects.requireNonNull(resultListener);
1606
1607 if (cancellationSignal != null) {
1608 cancellationSignal.throwIfCanceled();
1609 }
1610
1611 final RemoteCallback cancellationCallback = (cancellationSignal != null)
1612 ? new RemoteCallback(createSafeResultListener(b -> {
1613 if (b != null) {
1614 final IBinder cancellation = b.getBinder(
1615 VoiceInteractor.KEY_CANCELLATION_SIGNAL);
1616 if (cancellation != null) {
1617 cancellationSignal.setRemote(ICancellationSignal.Stub.asInterface(
1618 cancellation));
1619 }
1620 }
1621 }))
1622 : null;
1623
1624 final RemoteCallback resultCallback = new RemoteCallback(createSafeResultListener(b -> {
1625 if (b != null) {
1626 resultExecutor.execute(() -> resultListener.accept(b));
1627 } else {
1628 resultExecutor.execute(() -> resultListener.accept(Bundle.EMPTY));
1629 }
1630 }));
1631
1632 try {
1633 mSystemService.performDirectAction(mToken, action.getId(), extras,
1634 action.getTaskId(), action.getActivityId(), cancellationCallback,
1635 resultCallback);
1636 } catch (RemoteException e) {
1637 e.rethrowFromSystemServer();
1638 }
1639 }
1640
1641 /**
1642 * Set whether this session will keep the device awake while it is running a voice
1643 * activity. By default, the system holds a wake lock for it while in this state,
1644 * so that it can work even if the screen is off. Setting this to false removes that
1645 * wake lock, allowing the CPU to go to sleep. This is typically used if the
1646 * session decides it has been waiting too long for a response from the user and
1647 * doesn't want to let this continue to drain the battery.
1648 *
1649 * <p>Passing false here will release the wake lock, and you can call later with
1650 * true to re-acquire it. It will also be automatically re-acquired for you each
1651 * time you start a new voice activity task -- that is when you call
1652 * {@link #startVoiceActivity}.</p>
1653 */
1654 public void setKeepAwake(boolean keepAwake) {
1655 if (mToken == null) {
1656 throw new IllegalStateException("Can't call before onCreate()");
1657 }
1658 try {
1659 mSystemService.setKeepAwake(mToken, keepAwake);
1660 } catch (RemoteException e) {
1661 }
1662 }
1663
1664 /**
1665 * Request that all system dialogs (and status bar shade etc) be closed, allowing
1666 * access to the session's UI. This will <em>not</em> cause the lock screen to be
1667 * dismissed.
1668 */
1669 public void closeSystemDialogs() {
1670 if (mToken == null) {
1671 throw new IllegalStateException("Can't call before onCreate()");
1672 }
1673 try {
1674 mSystemService.closeSystemDialogs(mToken);
1675 } catch (RemoteException e) {
1676 }
1677 }
1678
1679 /**
1680 * Convenience for inflating views.
1681 */
1682 public LayoutInflater getLayoutInflater() {
1683 ensureWindowCreated();
1684 return mInflater;
1685 }
1686
1687 /**
1688 * Retrieve the window being used to show the session's UI.
1689 */
1690 public Dialog getWindow() {
1691 ensureWindowCreated();
1692 return mWindow;
1693 }
1694
1695 /**
1696 * Finish the session. This completely destroys the session -- the next time it is shown,
1697 * an entirely new one will be created. You do not normally call this function; instead,
1698 * use {@link #hide} and allow the system to destroy your session if it needs its RAM.
1699 */
1700 public void finish() {
1701 if (mToken == null) {
1702 throw new IllegalStateException("Can't call before onCreate()");
1703 }
1704 try {
1705 mSystemService.finish(mToken);
1706 } catch (RemoteException e) {
1707 }
1708 }
1709
1710 /**
1711 * Initiatize a new session. At this point you don't know exactly what this
1712 * session will be used for; you will find that out in {@link #onShow}.
1713 */
1714 public void onCreate() {
1715 doOnCreate();
1716 }
1717
1718 private void doOnCreate() {
1719 mTheme = mTheme != 0 ? mTheme
1720 : com.android.internal.R.style.Theme_DeviceDefault_VoiceInteractionSession;
1721 }
1722
1723 /**
1724 * Called prior to {@link #onShow} before any UI setup has occurred. Not generally useful.
1725 *
1726 * @param args The arguments that were supplied to
1727 * {@link VoiceInteractionService#showSession VoiceInteractionService.showSession}.
1728 * @param showFlags The show flags originally provided to
1729 * {@link VoiceInteractionService#showSession VoiceInteractionService.showSession}.
1730 */
1731 public void onPrepareShow(Bundle args, int showFlags) {
1732 }
1733
1734 /**
1735 * Called when the session UI is going to be shown. This is called after
1736 * {@link #onCreateContentView} (if the session's content UI needed to be created) and
1737 * immediately prior to the window being shown. This may be called while the window
1738 * is already shown, if a show request has come in while it is shown, to allow you to
1739 * update the UI to match the new show arguments.
1740 *
1741 * @param args The arguments that were supplied to
1742 * {@link VoiceInteractionService#showSession VoiceInteractionService.showSession}.
1743 * Some example keys include : "invocation_type", "invocation_phone_state",
1744 * "invocation_time_ms", Intent.EXTRA_TIME ("android.intent.extra.TIME") indicating timing
1745 * in milliseconds of the KeyEvent that triggered Assistant and
1746 * Intent.EXTRA_ASSIST_INPUT_DEVICE_ID (android.intent.extra.ASSIST_INPUT_DEVICE_ID)
1747 * referring to the device that sent the request.
1748 * @param showFlags The show flags originally provided to
1749 * {@link VoiceInteractionService#showSession VoiceInteractionService.showSession}.
1750 */
1751 public void onShow(Bundle args, int showFlags) {
1752 }
1753
1754 /**
1755 * Called immediately after stopping to show the session UI.
1756 */
1757 public void onHide() {
1758 }
1759
1760 /**
1761 * Last callback to the session as it is being finished.
1762 */
1763 public void onDestroy() {
1764 }
1765
1766 /**
1767 * Hook in which to create the session's UI.
1768 */
1769 public View onCreateContentView() {
1770 return null;
1771 }
1772
1773 public void setContentView(View view) {
1774 ensureWindowCreated();
1775 mContentFrame.removeAllViews();
1776 mContentFrame.addView(view, new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT));
1777 mContentFrame.requestApplyInsets();
1778 }
1779
1780 void doOnHandleAssist(int taskId, IBinder assistToken, Bundle data, AssistStructure structure,
1781 Throwable failure, AssistContent content, int index, int count) {
1782 if (failure != null) {
1783 onAssistStructureFailure(failure);
1784 }
1785 AssistState assistState = new AssistState(new ActivityId(taskId, assistToken),
1786 data, structure, content, index, count);
1787 onHandleAssist(assistState);
1788 }
1789
1790 /**
1791 * Called when there has been a failure transferring the {@link AssistStructure} to
1792 * the assistant. This may happen, for example, if the data is too large and results
1793 * in an out of memory exception, the data has been cleared during transferring due to
1794 * the new incoming assist data, or the client has provided corrupt data. This will be
1795 * called immediately before {@link #onHandleAssist} and the AssistStructure supplied
1796 * there afterwards will be null.
1797 *
1798 * @param failure The failure exception that was thrown when building the
1799 * {@link AssistStructure}.
1800 */
1801 public void onAssistStructureFailure(Throwable failure) {
1802 }
1803
1804 /**
1805 * Called to receive data from the application that the user was currently viewing when
1806 - * an assist session is started. If the original show request did not specify
1807 * {@link #SHOW_WITH_ASSIST}, this method will not be called.
1808 *
1809 * @param data Arbitrary data supplied by the app through
1810 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
1811 * May be null if assist data has been disabled by the user or device policy.
1812 * @param structure If available, the structure definition of all windows currently
1813 * displayed by the app. May be null if assist data has been disabled by the user
1814 * or device policy; will be an empty stub if the application has disabled assist
1815 * by marking its window as secure.
1816 * @param content Additional content data supplied by the app through
1817 * {@link android.app.Activity#onProvideAssistContent Activity.onProvideAssistContent}.
1818 * May be null if assist data has been disabled by the user or device policy; will
1819 * not be automatically filled in with data from the app if the app has marked its
1820 * window as secure.
1821 *
1822 * @deprecated use {@link #onHandleAssist(AssistState)}
1823 */
1824 @Deprecated
1825 public void onHandleAssist(@Nullable Bundle data, @Nullable AssistStructure structure,
1826 @Nullable AssistContent content) {
1827 }
1828
1829 /**
1830 * Called to receive data from the application that the user was currently viewing when
1831 * an assist session is started. If the original show request did not specify
1832 * {@link #SHOW_WITH_ASSIST}, {@link AssistState} parameter will only provide
1833 * {@link ActivityId}. If there was a failure to write the assist data to
1834 * {@link AssistStructure}, the {@link AssistState#getAssistStructure()} will return null.
1835 *
1836 * <p>This method is called for all activities along with an index and count that indicates
1837 * which activity the data is for. {@code index} will be between 0 and {@code count}-1 and
1838 * this method is called once for each activity in no particular order. The {@code count}
1839 * indicates how many activities to expect assist data for, including the top focused one.
1840 * The focused activity can be determined by calling {@link AssistState#isFocused()}.
1841 *
1842 * <p>To be responsive to assist requests, process assist data as soon as it is received,
1843 * without waiting for all queued activities to return assist data.
1844 *
1845 * @param state The state object capturing the state of an activity.
1846 */
1847 public void onHandleAssist(@NonNull AssistState state) {
1848 if (state.getAssistData() == null && state.getAssistStructure() == null
1849 && state.getAssistContent() == null) {
1850 return;
1851 } else if (state.getIndex() == 0) {
1852 onHandleAssist(state.getAssistData(), state.getAssistStructure(),
1853 state.getAssistContent());
1854 } else {
1855 onHandleAssistSecondary(state.getAssistData(), state.getAssistStructure(),
1856 state.getAssistContent(), state.getIndex(), state.getCount());
1857 }
1858 }
1859
1860 /**
1861 * Called to receive data from other applications that the user was or is interacting with,
1862 * that are currently on the screen in a multi-window display environment, not including the
1863 * currently focused activity. This could be
1864 * a free-form window, a picture-in-picture window, or another window in a split-screen display.
1865 * <p>
1866 * This method is very similar to
1867 * {@link #onHandleAssist} except that it is called
1868 * for additional non-focused activities along with an index and count that indicates
1869 * which additional activity the data is for. {@code index} will be between 1 and
1870 * {@code count}-1 and this method is called once for each additional window, in no particular
1871 * order. The {@code count} indicates how many windows to expect assist data for, including the
1872 * top focused activity, which continues to be returned via {@link #onHandleAssist}.
1873 * <p>
1874 * To be responsive to assist requests, process assist data as soon as it is received,
1875 * without waiting for all queued activities to return assist data.
1876 *
1877 * @param data Arbitrary data supplied by the app through
1878 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
1879 * May be null if assist data has been disabled by the user or device policy.
1880 * @param structure If available, the structure definition of all windows currently
1881 * displayed by the app. May be null if assist data has been disabled by the user
1882 * or device policy; will be an empty stub if the application has disabled assist
1883 * by marking its window as secure.
1884 * @param content Additional content data supplied by the app through
1885 * {@link android.app.Activity#onProvideAssistContent Activity.onProvideAssistContent}.
1886 * May be null if assist data has been disabled by the user or device policy; will
1887 * not be automatically filled in with data from the app if the app has marked its
1888 * window as secure.
1889 * @param index the index of the additional activity that this data
1890 * is for.
1891 * @param count the total number of additional activities for which the assist data is being
1892 * returned, including the focused activity that is returned via
1893 * {@link #onHandleAssist}.
1894 *
1895 * @deprecated use {@link #onHandleAssist(AssistState)}
1896 */
1897 @Deprecated
1898 public void onHandleAssistSecondary(@Nullable Bundle data, @Nullable AssistStructure structure,
1899 @Nullable AssistContent content, int index, int count) {
1900 }
1901
1902 /**
1903 * Called to receive a screenshot of what the user was currently viewing when an assist
1904 * session is started. May be null if screenshots are disabled by the user, policy,
1905 * or application. If the original show request did not specify
1906 * {@link #SHOW_WITH_SCREENSHOT}, this method will not be called.
1907 */
1908 public void onHandleScreenshot(@Nullable Bitmap screenshot) {
1909 }
1910
1911 public boolean onKeyDown(int keyCode, KeyEvent event) {
1912 return false;
1913 }
1914
1915 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
1916 return false;
1917 }
1918
1919 public boolean onKeyUp(int keyCode, KeyEvent event) {
1920 return false;
1921 }
1922
1923 public boolean onKeyMultiple(int keyCode, int count, KeyEvent event) {
1924 return false;
1925 }
1926
1927 /**
1928 * Called when the user presses the back button while focus is in the session UI. Note
1929 * that this will only happen if the session UI has requested input focus in its window;
1930 * otherwise, the back key will go to whatever window has focus and do whatever behavior
1931 * it normally has there. The default implementation simply calls {@link #hide}.
1932 */
1933 public void onBackPressed() {
1934 hide();
1935 }
1936
1937 /**
1938 * Sessions automatically watch for requests that all system UI be closed (such as when
1939 * the user presses HOME), which will appear here. The default implementation always
1940 * calls {@link #hide}.
1941 */
1942 public void onCloseSystemDialogs() {
1943 hide();
1944 }
1945
1946 /**
1947 * Called when the lockscreen was shown.
1948 */
1949 public void onLockscreenShown() {
1950 hide();
1951 }
1952
1953 @Override
1954 public void onConfigurationChanged(Configuration newConfig) {
1955 }
1956
1957 @Override
1958 public void onLowMemory() {
1959 }
1960
1961 @Override
1962 public void onTrimMemory(int level) {
1963 }
1964
1965 /**
1966 * Compute the interesting insets into your UI. The default implementation
1967 * sets {@link Insets#contentInsets outInsets.contentInsets.top} to the height
1968 * of the window, meaning it should not adjust content underneath. The default touchable
1969 * insets are {@link Insets#TOUCHABLE_INSETS_FRAME}, meaning it consumes all touch
1970 * events within its window frame.
1971 *
1972 * @param outInsets Fill in with the current UI insets.
1973 */
1974 public void onComputeInsets(Insets outInsets) {
1975 outInsets.contentInsets.left = 0;
1976 outInsets.contentInsets.bottom = 0;
1977 outInsets.contentInsets.right = 0;
1978 View decor = getWindow().getWindow().getDecorView();
1979 outInsets.contentInsets.top = decor.getHeight();
1980 outInsets.touchableInsets = Insets.TOUCHABLE_INSETS_FRAME;
1981 outInsets.touchableRegion.setEmpty();
1982 }
1983
1984 /**
1985 * Called when a task initiated by {@link #startVoiceActivity(android.content.Intent)}
1986 * has actually started.
1987 *
1988 * @param intent The original {@link Intent} supplied to
1989 * {@link #startVoiceActivity(android.content.Intent)}.
1990 * @param taskId Unique ID of the now running task.
1991 */
1992 public void onTaskStarted(Intent intent, int taskId) {
1993 }
1994
1995 /**
1996 * Called when the last activity of a task initiated by
1997 * {@link #startVoiceActivity(android.content.Intent)} has finished. The default
1998 * implementation calls {@link #finish()} on the assumption that this represents
1999 * the completion of a voice action. You can override the implementation if you would
2000 * like a different behavior.
2001 *
2002 * @param intent The original {@link Intent} supplied to
2003 * {@link #startVoiceActivity(android.content.Intent)}.
2004 * @param taskId Unique ID of the finished task.
2005 */
2006 public void onTaskFinished(Intent intent, int taskId) {
2007 hide();
2008 }
2009
2010 /**
2011 * Request to query for what extended commands the session supports.
2012 *
2013 * @param commands An array of commands that are being queried.
2014 * @return Return an array of booleans indicating which of each entry in the
2015 * command array is supported. A true entry in the array indicates the command
2016 * is supported; false indicates it is not. The default implementation returns
2017 * an array of all false entries.
2018 */
2019 public boolean[] onGetSupportedCommands(String[] commands) {
2020 return new boolean[commands.length];
2021 }
2022
2023 /**
2024 * Request to confirm with the user before proceeding with an unrecoverable operation,
2025 * corresponding to a {@link android.app.VoiceInteractor.ConfirmationRequest
2026 * VoiceInteractor.ConfirmationRequest}.
2027 *
2028 * @param request The active request.
2029 */
2030 public void onRequestConfirmation(ConfirmationRequest request) {
2031 }
2032
2033 /**
2034 * Request for the user to pick one of N options, corresponding to a
2035 * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}.
2036 *
2037 * @param request The active request.
2038 */
2039 public void onRequestPickOption(PickOptionRequest request) {
2040 }
2041
2042 /**
2043 * Request to complete the voice interaction session because the voice activity successfully
2044 * completed its interaction using voice. Corresponds to
2045 * {@link android.app.VoiceInteractor.CompleteVoiceRequest
2046 * VoiceInteractor.CompleteVoiceRequest}. The default implementation just sends an empty
2047 * confirmation back to allow the activity to exit.
2048 *
2049 * @param request The active request.
2050 */
2051 public void onRequestCompleteVoice(CompleteVoiceRequest request) {
2052 }
2053
2054 /**
2055 * Request to abort the voice interaction session because the voice activity can not
2056 * complete its interaction using voice. Corresponds to
2057 * {@link android.app.VoiceInteractor.AbortVoiceRequest
2058 * VoiceInteractor.AbortVoiceRequest}. The default implementation just sends an empty
2059 * confirmation back to allow the activity to exit.
2060 *
2061 * @param request The active request.
2062 */
2063 public void onRequestAbortVoice(AbortVoiceRequest request) {
2064 }
2065
2066 /**
2067 * Process an arbitrary extended command from the caller,
2068 * corresponding to a {@link android.app.VoiceInteractor.CommandRequest
2069 * VoiceInteractor.CommandRequest}.
2070 *
2071 * @param request The active request.
2072 */
2073 public void onRequestCommand(CommandRequest request) {
2074 }
2075
2076 /**
2077 * Called when the {@link android.app.VoiceInteractor} has asked to cancel a {@link Request}
2078 * that was previously delivered to {@link #onRequestConfirmation},
2079 * {@link #onRequestPickOption}, {@link #onRequestCompleteVoice}, {@link #onRequestAbortVoice},
2080 * or {@link #onRequestCommand}.
2081 *
2082 * @param request The request that is being canceled.
2083 */
2084 public void onCancelRequest(Request request) {
2085 }
2086
2087 /**
2088 * Registers a callback that will be notified when visible activities have been changed.
2089 *
2090 * Note: The {@link VisibleActivityCallback#onVisible(VisibleActivityInfo)} will be called
2091 * immediately with current visible activities when the callback is registered for the first
2092 * time. If the callback is already registered, this method does nothing.
2093 *
2094 * @param executor The executor which will be used to invoke the callback.
2095 * @param callback The callback to receive the response.
2096 *
2097 * @throws IllegalStateException if calling this method before onCreate().
2098 */
2099 public final void registerVisibleActivityCallback(@NonNull @CallbackExecutor Executor executor,
2100 @NonNull VisibleActivityCallback callback) {
2101 if (DEBUG) {
2102 Log.d(TAG, "registerVisibleActivityCallback");
2103 }
2104 if (mToken == null) {
2105 throw new IllegalStateException("Can't call before onCreate()");
2106 }
2107 Objects.requireNonNull(executor);
2108 Objects.requireNonNull(callback);
2109
2110 mHandlerCaller.sendMessage(
2111 mHandlerCaller.obtainMessageOO(MSG_REGISTER_VISIBLE_ACTIVITY_CALLBACK, executor,
2112 callback));
2113 }
2114
2115 /**
2116 * Unregisters the callback.
2117 *
2118 * @param callback The callback to receive the response.
2119 */
2120 public final void unregisterVisibleActivityCallback(@NonNull VisibleActivityCallback callback) {
2121 if (DEBUG) {
2122 Log.d(TAG, "unregisterVisibleActivityCallback");
2123 }
2124 Objects.requireNonNull(callback);
2125
2126 mHandlerCaller.sendMessage(
2127 mHandlerCaller.obtainMessageO(MSG_UNREGISTER_VISIBLE_ACTIVITY_CALLBACK, callback));
2128 }
2129
2130 /**
2131 * Print the Service's state into the given stream. This gets invoked by
2132 * {@link VoiceInteractionSessionService} when its Service
2133 * {@link android.app.Service#dump} method is called.
2134 *
2135 * @param prefix Text to print at the front of each line.
2136 * @param fd The raw file descriptor that the dump is being sent to.
2137 * @param writer The PrintWriter to which you should dump your state. This will be
2138 * closed for you after you return.
2139 * @param args additional arguments to the dump request.
2140 */
2141 public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
2142 writer.print(prefix); writer.print("mToken="); writer.println(mToken);
2143 writer.print(prefix); writer.print("mTheme=#"); writer.println(Integer.toHexString(mTheme));
2144 writer.print(prefix); writer.print("mUiEnabled="); writer.println(mUiEnabled);
2145 writer.print(" mInitialized="); writer.println(mInitialized);
2146 writer.print(prefix); writer.print("mWindowAdded="); writer.print(mWindowAdded);
2147 writer.print(" mWindowVisible="); writer.println(mWindowVisible);
2148 writer.print(prefix); writer.print("mWindowWasVisible="); writer.print(mWindowWasVisible);
2149 writer.print(" mInShowWindow="); writer.println(mInShowWindow);
2150 if (mActiveRequests.size() > 0) {
2151 writer.print(prefix); writer.println("Active requests:");
2152 String innerPrefix = prefix + " ";
2153 for (int i=0; i<mActiveRequests.size(); i++) {
2154 Request req = mActiveRequests.valueAt(i);
2155 writer.print(prefix); writer.print(" #"); writer.print(i);
2156 writer.print(": ");
2157 writer.println(req);
2158 req.dump(innerPrefix, fd, writer, args);
2159
2160 }
2161 }
2162 }
2163
2164 private SafeResultListener createSafeResultListener(
2165 @NonNull Consumer<Bundle> consumer) {
2166 synchronized (this) {
2167 final SafeResultListener listener = new SafeResultListener(consumer, this);
2168 mRemoteCallbacks.put(listener, consumer);
2169 return listener;
2170 }
2171 }
2172
2173 private Consumer<Bundle> removeSafeResultListener(@NonNull SafeResultListener listener) {
2174 synchronized (this) {
2175 return mRemoteCallbacks.remove(listener);
2176 }
2177 }
2178
2179 /**
2180 * Callback interface for receiving visible activity changes used for assistant usage.
2181 */
2182 public interface VisibleActivityCallback {
2183 /** Callback to inform that an activity has become visible. */
2184 default void onVisible(@NonNull VisibleActivityInfo activityInfo) {}
2185
2186 /** Callback to inform that a visible activity has gone. */
2187 default void onInvisible(@NonNull ActivityId activityId) {}
2188 }
2189
2190 /**
2191 * Represents assist state captured when this session was started.
2192 * It contains the various assist data objects and a reference to
2193 * the source activity.
2194 */
2195 @Immutable
2196 public static final class AssistState {
2197 private final @NonNull ActivityId mActivityId;
2198 private final int mIndex;
2199 private final int mCount;
2200 private final @Nullable Bundle mData;
2201 private final @Nullable AssistStructure mStructure;
2202 private final @Nullable AssistContent mContent;
2203
2204 AssistState(@NonNull ActivityId activityId, @Nullable Bundle data,
2205 @Nullable AssistStructure structure, @Nullable AssistContent content,
2206 int index, int count) {
2207 mActivityId = activityId;
2208 mIndex = index;
2209 mCount = count;
2210 mData = data;
2211 mStructure = structure;
2212 mContent = content;
2213 }
2214
2215 /**
2216 * @return whether the source activity is focused.
2217 */
2218 public boolean isFocused() {
2219 return mIndex == 0;
2220 }
2221
2222 /**
2223 * @return the index of the activity that this state is for or -1
2224 * if there was no assist data captured.
2225 */
2226 public @IntRange(from = -1) int getIndex() {
2227 return mIndex;
2228 }
2229
2230 /**
2231 * @return the total number of activities for which the assist data is
2232 * being returned.
2233 */
2234 public @IntRange(from = 0) int getCount() {
2235 return mCount;
2236 }
2237
2238 /**
2239 * @return the id of the source activity
2240 */
2241 public @NonNull ActivityId getActivityId() {
2242 return mActivityId;
2243 }
2244
2245 /**
2246 * @return Arbitrary data supplied by the app through
2247 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}.
2248 * May be null if assist data has been disabled by the user or device policy; will be null
2249 * if the original show request did not specify {@link #SHOW_WITH_ASSIST}.
2250 */
2251 public @Nullable Bundle getAssistData() {
2252 return mData;
2253 }
2254
2255 /**
2256 * @return If available, the structure definition of all windows currently
2257 * displayed by the app. May be null if assist data has been disabled by the user
2258 * or device policy; will be null if the original show request did not specify
2259 * {@link #SHOW_WITH_ASSIST} or the assist data has been corrupt when writing the data to
2260 * {@link AssistStructure}; will be an empty stub if the application has disabled assist
2261 * by marking its window as secure.
2262 */
2263 public @Nullable AssistStructure getAssistStructure() {
2264 return mStructure;
2265 }
2266
2267 /**
2268 * @return Additional content data supplied by the app through
2269 * {@link android.app.Activity#onProvideAssistContent Activity.onProvideAssistContent}.
2270 * May be null if assist data has been disabled by the user or device policy; will be null
2271 * if the original show request did not specify {@link #SHOW_WITH_ASSIST}. Will not be
2272 * automatically filled in with data from the app if the app has marked its window as
2273 * secure.
2274 */
2275 public @Nullable AssistContent getAssistContent() {
2276 return mContent;
2277 }
2278 }
2279
2280 /**
2281 * Represents the id of an assist source activity. You can use
2282 * {@link #equals(Object)} to compare instances of this class.
2283 */
2284 public static class ActivityId {
2285 private final int mTaskId;
2286 private final IBinder mAssistToken;
2287
2288 ActivityId(int taskId, IBinder assistToken) {
2289 mTaskId = taskId;
2290 mAssistToken = assistToken;
2291 }
2292
2293 int getTaskId() {
2294 return mTaskId;
2295 }
2296
2297 IBinder getAssistToken() {
2298 return mAssistToken;
2299 }
2300
2301 @Override
2302 public boolean equals(@Nullable Object o) {
2303 if (this == o) {
2304 return true;
2305 }
2306 if (o == null || getClass() != o.getClass()) {
2307 return false;
2308 }
2309
2310 ActivityId that = (ActivityId) o;
2311
2312 if (mTaskId != that.mTaskId) {
2313 return false;
2314 }
2315 return mAssistToken != null
2316 ? mAssistToken.equals(that.mAssistToken)
2317 : that.mAssistToken == null;
2318 }
2319
2320 @Override
2321 public int hashCode() {
2322 int result = mTaskId;
2323 result = 31 * result + (mAssistToken != null ? mAssistToken.hashCode() : 0);
2324 return result;
2325 }
2326 }
2327
2328 private static class SafeResultListener implements RemoteCallback.OnResultListener {
2329 private final @NonNull WeakReference<VoiceInteractionSession> mWeakSession;
2330
2331 SafeResultListener(@NonNull Consumer<Bundle> action,
2332 @NonNull VoiceInteractionSession session) {
2333 mWeakSession = new WeakReference<>(session);
2334 }
2335
2336 @Override
2337 public void onResult(Bundle result) {
2338 final VoiceInteractionSession session = mWeakSession.get();
2339 if (session != null) {
2340 final Consumer<Bundle> consumer = session.removeSafeResultListener(this);
2341 if (consumer != null) {
2342 consumer.accept(result);
2343 }
2344 }
2345 }
2346 }
2347 }