AccessibilityService.java revision 155dda1e433a003f65b1d6a65d54bec107d27db5
1/*
2 * Copyright (C) 2009 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.accessibilityservice;
18
19import android.accessibilityservice.GestureDescription.MotionEventGenerator;
20import android.annotation.IntDef;
21import android.annotation.NonNull;
22import android.annotation.Nullable;
23import android.app.Service;
24import android.content.Context;
25import android.content.Intent;
26import android.content.pm.ParceledListSlice;
27import android.graphics.Region;
28import android.os.Handler;
29import android.os.IBinder;
30import android.os.Looper;
31import android.os.Message;
32import android.os.RemoteException;
33import android.provider.Settings;
34import android.util.ArrayMap;
35import android.util.Log;
36import android.util.Pair;
37import android.util.Slog;
38import android.util.SparseArray;
39import android.view.KeyEvent;
40import android.view.MotionEvent;
41import android.view.WindowManager;
42import android.view.WindowManagerImpl;
43import android.view.accessibility.AccessibilityEvent;
44import android.view.accessibility.AccessibilityInteractionClient;
45import android.view.accessibility.AccessibilityNodeInfo;
46import android.view.accessibility.AccessibilityWindowInfo;
47
48import com.android.internal.os.HandlerCaller;
49import com.android.internal.os.SomeArgs;
50
51import java.lang.annotation.Retention;
52import java.lang.annotation.RetentionPolicy;
53import java.util.List;
54
55/**
56 * Accessibility services are intended to assist users with disabilities in using
57 * Android devices and apps. They run in the background and receive callbacks by the system
58 * when {@link AccessibilityEvent}s are fired. Such events denote some state transition
59 * in the user interface, for example, the focus has changed, a button has been clicked,
60 * etc. Such a service can optionally request the capability for querying the content
61 * of the active window. Development of an accessibility service requires extending this
62 * class and implementing its abstract methods.
63 *
64 * <div class="special reference">
65 * <h3>Developer Guides</h3>
66 * <p>For more information about creating AccessibilityServices, read the
67 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
68 * developer guide.</p>
69 * </div>
70 *
71 * <h3>Lifecycle</h3>
72 * <p>
73 * The lifecycle of an accessibility service is managed exclusively by the system and
74 * follows the established service life cycle. Starting an accessibility service is triggered
75 * exclusively by the user explicitly turning the service on in device settings. After the system
76 * binds to a service, it calls {@link AccessibilityService#onServiceConnected()}. This method can
77 * be overriden by clients that want to perform post binding setup.
78 * </p>
79 * <p>
80 * An accessibility service stops either when the user turns it off in device settings or when
81 * it calls {@link AccessibilityService#disableSelf()}.
82 * </p>
83 * <h3>Declaration</h3>
84 * <p>
85 * An accessibility is declared as any other service in an AndroidManifest.xml, but it
86 * must do two things:
87 * <ul>
88 *     <ol>
89 *         Specify that it handles the "android.accessibilityservice.AccessibilityService"
90 *         {@link android.content.Intent}.
91 *     </ol>
92 *     <ol>
93 *         Request the {@link android.Manifest.permission#BIND_ACCESSIBILITY_SERVICE} permission to
94 *         ensure that only the system can bind to it.
95 *     </ol>
96 * </ul>
97 * If either of these items is missing, the system will ignore the accessibility service.
98 * Following is an example declaration:
99 * </p>
100 * <pre> &lt;service android:name=".MyAccessibilityService"
101 *         android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"&gt;
102 *     &lt;intent-filter&gt;
103 *         &lt;action android:name="android.accessibilityservice.AccessibilityService" /&gt;
104 *     &lt;/intent-filter&gt;
105 *     . . .
106 * &lt;/service&gt;</pre>
107 * <h3>Configuration</h3>
108 * <p>
109 * An accessibility service can be configured to receive specific types of accessibility events,
110 * listen only to specific packages, get events from each type only once in a given time frame,
111 * retrieve window content, specify a settings activity, etc.
112 * </p>
113 * <p>
114 * There are two approaches for configuring an accessibility service:
115 * </p>
116 * <ul>
117 * <li>
118 * Providing a {@link #SERVICE_META_DATA meta-data} entry in the manifest when declaring
119 * the service. A service declaration with a meta-data tag is presented below:
120 * <pre> &lt;service android:name=".MyAccessibilityService"&gt;
121 *     &lt;intent-filter&gt;
122 *         &lt;action android:name="android.accessibilityservice.AccessibilityService" /&gt;
123 *     &lt;/intent-filter&gt;
124 *     &lt;meta-data android:name="android.accessibilityservice" android:resource="@xml/accessibilityservice" /&gt;
125 * &lt;/service&gt;</pre>
126 * <p class="note">
127 * <strong>Note:</strong> This approach enables setting all properties.
128 * </p>
129 * <p>
130 * For more details refer to {@link #SERVICE_META_DATA} and
131 * <code>&lt;{@link android.R.styleable#AccessibilityService accessibility-service}&gt;</code>.
132 * </p>
133 * </li>
134 * <li>
135 * Calling {@link AccessibilityService#setServiceInfo(AccessibilityServiceInfo)}. Note
136 * that this method can be called any time to dynamically change the service configuration.
137 * <p class="note">
138 * <strong>Note:</strong> This approach enables setting only dynamically configurable properties:
139 * {@link AccessibilityServiceInfo#eventTypes},
140 * {@link AccessibilityServiceInfo#feedbackType},
141 * {@link AccessibilityServiceInfo#flags},
142 * {@link AccessibilityServiceInfo#notificationTimeout},
143 * {@link AccessibilityServiceInfo#packageNames}
144 * </p>
145 * <p>
146 * For more details refer to {@link AccessibilityServiceInfo}.
147 * </p>
148 * </li>
149 * </ul>
150 * <h3>Retrieving window content</h3>
151 * <p>
152 * A service can specify in its declaration that it can retrieve window
153 * content which is represented as a tree of {@link AccessibilityWindowInfo} and
154 * {@link AccessibilityNodeInfo} objects. Note that
155 * declaring this capability requires that the service declares its configuration via
156 * an XML resource referenced by {@link #SERVICE_META_DATA}.
157 * </p>
158 * <p>
159 * Window content may be retrieved with
160 * {@link AccessibilityEvent#getSource() AccessibilityEvent.getSource()},
161 * {@link AccessibilityService#findFocus(int)},
162 * {@link AccessibilityService#getWindows()}, or
163 * {@link AccessibilityService#getRootInActiveWindow()}.
164 * </p>
165 * <p class="note">
166 * <strong>Note</strong> An accessibility service may have requested to be notified for
167 * a subset of the event types, and thus be unaware when the node hierarchy has changed. It is also
168 * possible for a node to contain outdated information because the window content may change at any
169 * time.
170 * </p>
171 * <h3>Notification strategy</h3>
172 * <p>
173 * All accessibility services are notified of all events they have requested, regardless of their
174 * feedback type.
175 * </p>
176 * <p class="note">
177 * <strong>Note:</strong> The event notification timeout is useful to avoid propagating
178 * events to the client too frequently since this is accomplished via an expensive
179 * interprocess call. One can think of the timeout as a criteria to determine when
180 * event generation has settled down.</p>
181 * <h3>Event types</h3>
182 * <ul>
183 * <li>{@link AccessibilityEvent#TYPE_VIEW_CLICKED}</li>
184 * <li>{@link AccessibilityEvent#TYPE_VIEW_LONG_CLICKED}</li>
185 * <li>{@link AccessibilityEvent#TYPE_VIEW_FOCUSED}</li>
186 * <li>{@link AccessibilityEvent#TYPE_VIEW_SELECTED}</li>
187 * <li>{@link AccessibilityEvent#TYPE_VIEW_TEXT_CHANGED}</li>
188 * <li>{@link AccessibilityEvent#TYPE_WINDOW_STATE_CHANGED}</li>
189 * <li>{@link AccessibilityEvent#TYPE_NOTIFICATION_STATE_CHANGED}</li>
190 * <li>{@link AccessibilityEvent#TYPE_TOUCH_EXPLORATION_GESTURE_START}</li>
191 * <li>{@link AccessibilityEvent#TYPE_TOUCH_EXPLORATION_GESTURE_END}</li>
192 * <li>{@link AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}</li>
193 * <li>{@link AccessibilityEvent#TYPE_VIEW_HOVER_EXIT}</li>
194 * <li>{@link AccessibilityEvent#TYPE_VIEW_SCROLLED}</li>
195 * <li>{@link AccessibilityEvent#TYPE_VIEW_TEXT_SELECTION_CHANGED}</li>
196 * <li>{@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED}</li>
197 * <li>{@link AccessibilityEvent#TYPE_ANNOUNCEMENT}</li>
198 * <li>{@link AccessibilityEvent#TYPE_GESTURE_DETECTION_START}</li>
199 * <li>{@link AccessibilityEvent#TYPE_GESTURE_DETECTION_END}</li>
200 * <li>{@link AccessibilityEvent#TYPE_TOUCH_INTERACTION_START}</li>
201 * <li>{@link AccessibilityEvent#TYPE_TOUCH_INTERACTION_END}</li>
202 * <li>{@link AccessibilityEvent#TYPE_VIEW_ACCESSIBILITY_FOCUSED}</li>
203 * <li>{@link AccessibilityEvent#TYPE_WINDOWS_CHANGED}</li>
204 * <li>{@link AccessibilityEvent#TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED}</li>
205 * </ul>
206 * <h3>Feedback types</h3>
207 * <ul>
208 * <li>{@link AccessibilityServiceInfo#FEEDBACK_AUDIBLE}</li>
209 * <li>{@link AccessibilityServiceInfo#FEEDBACK_HAPTIC}</li>
210 * <li>{@link AccessibilityServiceInfo#FEEDBACK_AUDIBLE}</li>
211 * <li>{@link AccessibilityServiceInfo#FEEDBACK_VISUAL}</li>
212 * <li>{@link AccessibilityServiceInfo#FEEDBACK_GENERIC}</li>
213 * <li>{@link AccessibilityServiceInfo#FEEDBACK_BRAILLE}</li>
214 * </ul>
215 * @see AccessibilityEvent
216 * @see AccessibilityServiceInfo
217 * @see android.view.accessibility.AccessibilityManager
218 */
219public abstract class AccessibilityService extends Service {
220
221    /**
222     * The user has performed a swipe up gesture on the touch screen.
223     */
224    public static final int GESTURE_SWIPE_UP = 1;
225
226    /**
227     * The user has performed a swipe down gesture on the touch screen.
228     */
229    public static final int GESTURE_SWIPE_DOWN = 2;
230
231    /**
232     * The user has performed a swipe left gesture on the touch screen.
233     */
234    public static final int GESTURE_SWIPE_LEFT = 3;
235
236    /**
237     * The user has performed a swipe right gesture on the touch screen.
238     */
239    public static final int GESTURE_SWIPE_RIGHT = 4;
240
241    /**
242     * The user has performed a swipe left and right gesture on the touch screen.
243     */
244    public static final int GESTURE_SWIPE_LEFT_AND_RIGHT = 5;
245
246    /**
247     * The user has performed a swipe right and left gesture on the touch screen.
248     */
249    public static final int GESTURE_SWIPE_RIGHT_AND_LEFT = 6;
250
251    /**
252     * The user has performed a swipe up and down gesture on the touch screen.
253     */
254    public static final int GESTURE_SWIPE_UP_AND_DOWN = 7;
255
256    /**
257     * The user has performed a swipe down and up gesture on the touch screen.
258     */
259    public static final int GESTURE_SWIPE_DOWN_AND_UP = 8;
260
261    /**
262     * The user has performed a left and up gesture on the touch screen.
263     */
264    public static final int GESTURE_SWIPE_LEFT_AND_UP = 9;
265
266    /**
267     * The user has performed a left and down gesture on the touch screen.
268     */
269    public static final int GESTURE_SWIPE_LEFT_AND_DOWN = 10;
270
271    /**
272     * The user has performed a right and up gesture on the touch screen.
273     */
274    public static final int GESTURE_SWIPE_RIGHT_AND_UP = 11;
275
276    /**
277     * The user has performed a right and down gesture on the touch screen.
278     */
279    public static final int GESTURE_SWIPE_RIGHT_AND_DOWN = 12;
280
281    /**
282     * The user has performed an up and left gesture on the touch screen.
283     */
284    public static final int GESTURE_SWIPE_UP_AND_LEFT = 13;
285
286    /**
287     * The user has performed an up and right gesture on the touch screen.
288     */
289    public static final int GESTURE_SWIPE_UP_AND_RIGHT = 14;
290
291    /**
292     * The user has performed an down and left gesture on the touch screen.
293     */
294    public static final int GESTURE_SWIPE_DOWN_AND_LEFT = 15;
295
296    /**
297     * The user has performed an down and right gesture on the touch screen.
298     */
299    public static final int GESTURE_SWIPE_DOWN_AND_RIGHT = 16;
300
301    /**
302     * The {@link Intent} that must be declared as handled by the service.
303     */
304    public static final String SERVICE_INTERFACE =
305        "android.accessibilityservice.AccessibilityService";
306
307    /**
308     * Name under which an AccessibilityService component publishes information
309     * about itself. This meta-data must reference an XML resource containing an
310     * <code>&lt;{@link android.R.styleable#AccessibilityService accessibility-service}&gt;</code>
311     * tag. This is a a sample XML file configuring an accessibility service:
312     * <pre> &lt;accessibility-service
313     *     android:accessibilityEventTypes="typeViewClicked|typeViewFocused"
314     *     android:packageNames="foo.bar, foo.baz"
315     *     android:accessibilityFeedbackType="feedbackSpoken"
316     *     android:notificationTimeout="100"
317     *     android:accessibilityFlags="flagDefault"
318     *     android:settingsActivity="foo.bar.TestBackActivity"
319     *     android:canRetrieveWindowContent="true"
320     *     android:canRequestTouchExplorationMode="true"
321     *     . . .
322     * /&gt;</pre>
323     */
324    public static final String SERVICE_META_DATA = "android.accessibilityservice";
325
326    /**
327     * Action to go back.
328     */
329    public static final int GLOBAL_ACTION_BACK = 1;
330
331    /**
332     * Action to go home.
333     */
334    public static final int GLOBAL_ACTION_HOME = 2;
335
336    /**
337     * Action to toggle showing the overview of recent apps
338     */
339    public static final int GLOBAL_ACTION_RECENTS = 3;
340
341    /**
342     * Action to open the notifications.
343     */
344    public static final int GLOBAL_ACTION_NOTIFICATIONS = 4;
345
346    /**
347     * Action to open the quick settings.
348     */
349    public static final int GLOBAL_ACTION_QUICK_SETTINGS = 5;
350
351    /**
352     * Action to open the power long-press dialog.
353     */
354    public static final int GLOBAL_ACTION_POWER_DIALOG = 6;
355
356    /**
357     * Action to toggle docking the current app's window
358     */
359    public static final int GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN = 7;
360
361    private static final String LOG_TAG = "AccessibilityService";
362
363    /**
364     * @hide
365     */
366    public interface Callbacks {
367        public void onAccessibilityEvent(AccessibilityEvent event);
368        public void onInterrupt();
369        public void onServiceConnected();
370        public void init(int connectionId, IBinder windowToken);
371        public boolean onGesture(int gestureId);
372        public boolean onKeyEvent(KeyEvent event);
373        public void onMagnificationChanged(@NonNull Region region,
374                float scale, float centerX, float centerY);
375        public void onSoftKeyboardShowModeChanged(int showMode);
376        public void onPerformGestureResult(int sequence, boolean completedSuccessfully);
377    }
378
379    /**
380     * Annotations for Soft Keyboard show modes so tools can catch invalid show modes.
381     * @hide
382     */
383    @Retention(RetentionPolicy.SOURCE)
384    @IntDef({SHOW_MODE_AUTO, SHOW_MODE_HIDDEN})
385    public @interface SoftKeyboardShowMode {};
386    public static final int SHOW_MODE_AUTO = 0;
387    public static final int SHOW_MODE_HIDDEN = 1;
388
389    private int mConnectionId;
390
391    private AccessibilityServiceInfo mInfo;
392
393    private IBinder mWindowToken;
394
395    private WindowManager mWindowManager;
396
397    private MagnificationController mMagnificationController;
398    private SoftKeyboardController mSoftKeyboardController;
399
400    private int mGestureStatusCallbackSequence;
401
402    private SparseArray<GestureResultCallbackInfo> mGestureStatusCallbackInfos;
403
404    private final Object mLock = new Object();
405
406    /**
407     * Callback for {@link android.view.accessibility.AccessibilityEvent}s.
408     *
409     * @param event The new event. This event is owned by the caller and cannot be used after
410     * this method returns. Services wishing to use the event after this method returns should
411     * make a copy.
412     */
413    public abstract void onAccessibilityEvent(AccessibilityEvent event);
414
415    /**
416     * Callback for interrupting the accessibility feedback.
417     */
418    public abstract void onInterrupt();
419
420    /**
421     * Dispatches service connection to internal components first, then the
422     * client code.
423     */
424    private void dispatchServiceConnected() {
425        if (mMagnificationController != null) {
426            mMagnificationController.onServiceConnected();
427        }
428
429        // The client gets to handle service connection last, after we've set
430        // up any state upon which their code may rely.
431        onServiceConnected();
432    }
433
434    /**
435     * This method is a part of the {@link AccessibilityService} lifecycle and is
436     * called after the system has successfully bound to the service. If is
437     * convenient to use this method for setting the {@link AccessibilityServiceInfo}.
438     *
439     * @see AccessibilityServiceInfo
440     * @see #setServiceInfo(AccessibilityServiceInfo)
441     */
442    protected void onServiceConnected() {
443
444    }
445
446    /**
447     * Called by the system when the user performs a specific gesture on the
448     * touch screen.
449     *
450     * <strong>Note:</strong> To receive gestures an accessibility service must
451     * request that the device is in touch exploration mode by setting the
452     * {@link android.accessibilityservice.AccessibilityServiceInfo#FLAG_REQUEST_TOUCH_EXPLORATION_MODE}
453     * flag.
454     *
455     * @param gestureId The unique id of the performed gesture.
456     *
457     * @return Whether the gesture was handled.
458     *
459     * @see #GESTURE_SWIPE_UP
460     * @see #GESTURE_SWIPE_UP_AND_LEFT
461     * @see #GESTURE_SWIPE_UP_AND_DOWN
462     * @see #GESTURE_SWIPE_UP_AND_RIGHT
463     * @see #GESTURE_SWIPE_DOWN
464     * @see #GESTURE_SWIPE_DOWN_AND_LEFT
465     * @see #GESTURE_SWIPE_DOWN_AND_UP
466     * @see #GESTURE_SWIPE_DOWN_AND_RIGHT
467     * @see #GESTURE_SWIPE_LEFT
468     * @see #GESTURE_SWIPE_LEFT_AND_UP
469     * @see #GESTURE_SWIPE_LEFT_AND_RIGHT
470     * @see #GESTURE_SWIPE_LEFT_AND_DOWN
471     * @see #GESTURE_SWIPE_RIGHT
472     * @see #GESTURE_SWIPE_RIGHT_AND_UP
473     * @see #GESTURE_SWIPE_RIGHT_AND_LEFT
474     * @see #GESTURE_SWIPE_RIGHT_AND_DOWN
475     */
476    protected boolean onGesture(int gestureId) {
477        return false;
478    }
479
480    /**
481     * Callback that allows an accessibility service to observe the key events
482     * before they are passed to the rest of the system. This means that the events
483     * are first delivered here before they are passed to the device policy, the
484     * input method, or applications.
485     * <p>
486     * <strong>Note:</strong> It is important that key events are handled in such
487     * a way that the event stream that would be passed to the rest of the system
488     * is well-formed. For example, handling the down event but not the up event
489     * and vice versa would generate an inconsistent event stream.
490     * </p>
491     * <p>
492     * <strong>Note:</strong> The key events delivered in this method are copies
493     * and modifying them will have no effect on the events that will be passed
494     * to the system. This method is intended to perform purely filtering
495     * functionality.
496     * <p>
497     *
498     * @param event The event to be processed. This event is owned by the caller and cannot be used
499     * after this method returns. Services wishing to use the event after this method returns should
500     * make a copy.
501     * @return If true then the event will be consumed and not delivered to
502     *         applications, otherwise it will be delivered as usual.
503     */
504    protected boolean onKeyEvent(KeyEvent event) {
505        return false;
506    }
507
508    /**
509     * Gets the windows on the screen. This method returns only the windows
510     * that a sighted user can interact with, as opposed to all windows.
511     * For example, if there is a modal dialog shown and the user cannot touch
512     * anything behind it, then only the modal window will be reported
513     * (assuming it is the top one). For convenience the returned windows
514     * are ordered in a descending layer order, which is the windows that
515     * are higher in the Z-order are reported first. Since the user can always
516     * interact with the window that has input focus by typing, the focused
517     * window is always returned (even if covered by a modal window).
518     * <p>
519     * <strong>Note:</strong> In order to access the windows your service has
520     * to declare the capability to retrieve window content by setting the
521     * {@link android.R.styleable#AccessibilityService_canRetrieveWindowContent}
522     * property in its meta-data. For details refer to {@link #SERVICE_META_DATA}.
523     * Also the service has to opt-in to retrieve the interactive windows by
524     * setting the {@link AccessibilityServiceInfo#FLAG_RETRIEVE_INTERACTIVE_WINDOWS}
525     * flag.
526     * </p>
527     *
528     * @return The windows if there are windows and the service is can retrieve
529     *         them, otherwise an empty list.
530     */
531    public List<AccessibilityWindowInfo> getWindows() {
532        return AccessibilityInteractionClient.getInstance().getWindows(mConnectionId);
533    }
534
535    /**
536     * Gets the root node in the currently active window if this service
537     * can retrieve window content. The active window is the one that the user
538     * is currently touching or the window with input focus, if the user is not
539     * touching any window.
540     * <p>
541     * The currently active window is defined as the window that most recently fired one
542     * of the following events:
543     * {@link AccessibilityEvent#TYPE_WINDOW_STATE_CHANGED},
544     * {@link AccessibilityEvent#TYPE_VIEW_HOVER_ENTER},
545     * {@link AccessibilityEvent#TYPE_VIEW_HOVER_EXIT}.
546     * In other words, the last window shown that also has input focus.
547     * </p>
548     * <p>
549     * <strong>Note:</strong> In order to access the root node your service has
550     * to declare the capability to retrieve window content by setting the
551     * {@link android.R.styleable#AccessibilityService_canRetrieveWindowContent}
552     * property in its meta-data. For details refer to {@link #SERVICE_META_DATA}.
553     * </p>
554     *
555     * @return The root node if this service can retrieve window content.
556     */
557    public AccessibilityNodeInfo getRootInActiveWindow() {
558        return AccessibilityInteractionClient.getInstance().getRootInActiveWindow(mConnectionId);
559    }
560
561    /**
562     * Disables the service. After calling this method, the service will be disabled and settings
563     * will show that it is turned off.
564     */
565    public final void disableSelf() {
566        final IAccessibilityServiceConnection connection =
567                AccessibilityInteractionClient.getInstance().getConnection(mConnectionId);
568        if (connection != null) {
569            try {
570                connection.disableSelf();
571            } catch (RemoteException re) {
572                throw new RuntimeException(re);
573            }
574        }
575    }
576
577    /**
578     * Returns the magnification controller, which may be used to query and
579     * modify the state of display magnification.
580     * <p>
581     * <strong>Note:</strong> In order to control magnification, your service
582     * must declare the capability by setting the
583     * {@link android.R.styleable#AccessibilityService_canControlMagnification}
584     * property in its meta-data. For more information, see
585     * {@link #SERVICE_META_DATA}.
586     *
587     * @return the magnification controller
588     */
589    @NonNull
590    public final MagnificationController getMagnificationController() {
591        synchronized (mLock) {
592            if (mMagnificationController == null) {
593                mMagnificationController = new MagnificationController(this, mLock);
594            }
595            return mMagnificationController;
596        }
597    }
598
599    /**
600     * Dispatch a gesture to the touch screen. Any gestures currently in progress, whether from
601     * the user, this service, or another service, will be cancelled.
602     * <p>
603     * The gesture will be dispatched as if it were performed directly on the screen by a user, so
604     * the events may be affected by features such as magnification and explore by touch.
605     * </p>
606     * <p>
607     * <strong>Note:</strong> In order to dispatch gestures, your service
608     * must declare the capability by setting the
609     * {@link android.R.styleable#AccessibilityService_canPerformGestures}
610     * property in its meta-data. For more information, see
611     * {@link #SERVICE_META_DATA}.
612     * </p>
613     *
614     * @param gesture The gesture to dispatch
615     * @param callback The object to call back when the status of the gesture is known. If
616     * {@code null}, no status is reported.
617     * @param handler The handler on which to call back the {@code callback} object. If
618     * {@code null}, the object is called back on the service's main thread.
619     *
620     * @return {@code true} if the gesture is dispatched, {@code false} if not.
621     */
622    public final boolean dispatchGesture(@NonNull GestureDescription gesture,
623            @Nullable GestureResultCallback callback,
624            @Nullable Handler handler) {
625        final IAccessibilityServiceConnection connection =
626                AccessibilityInteractionClient.getInstance().getConnection(
627                        mConnectionId);
628        if (connection == null) {
629            return false;
630        }
631        List<MotionEvent> events = MotionEventGenerator.getMotionEventsFromGestureDescription(
632                gesture, 100);
633        try {
634            synchronized (mLock) {
635                mGestureStatusCallbackSequence++;
636                if (callback != null) {
637                    if (mGestureStatusCallbackInfos == null) {
638                        mGestureStatusCallbackInfos = new SparseArray<>();
639                    }
640                    GestureResultCallbackInfo callbackInfo = new GestureResultCallbackInfo(gesture,
641                            callback, handler);
642                    mGestureStatusCallbackInfos.put(mGestureStatusCallbackSequence, callbackInfo);
643                }
644                connection.sendMotionEvents(mGestureStatusCallbackSequence,
645                        new ParceledListSlice<>(events));
646            }
647        } catch (RemoteException re) {
648            throw new RuntimeException(re);
649        }
650        return true;
651    }
652
653    void onPerformGestureResult(int sequence, final boolean completedSuccessfully) {
654        if (mGestureStatusCallbackInfos == null) {
655            return;
656        }
657        GestureResultCallbackInfo callbackInfo;
658        synchronized (mLock) {
659            callbackInfo = mGestureStatusCallbackInfos.get(sequence);
660        }
661        final GestureResultCallbackInfo finalCallbackInfo = callbackInfo;
662        if ((callbackInfo != null) && (callbackInfo.gestureDescription != null)
663                && (callbackInfo.callback != null)) {
664            if (callbackInfo.handler != null) {
665                callbackInfo.handler.post(new Runnable() {
666                    @Override
667                    public void run() {
668                        if (completedSuccessfully) {
669                            finalCallbackInfo.callback
670                                    .onCompleted(finalCallbackInfo.gestureDescription);
671                        } else {
672                            finalCallbackInfo.callback
673                                    .onCancelled(finalCallbackInfo.gestureDescription);
674                        }
675                    }
676                });
677                return;
678            }
679            if (completedSuccessfully) {
680                callbackInfo.callback.onCompleted(callbackInfo.gestureDescription);
681            } else {
682                callbackInfo.callback.onCancelled(callbackInfo.gestureDescription);
683            }
684        }
685    }
686
687    private void onMagnificationChanged(@NonNull Region region, float scale,
688            float centerX, float centerY) {
689        if (mMagnificationController != null) {
690            mMagnificationController.dispatchMagnificationChanged(
691                    region, scale, centerX, centerY);
692        }
693    }
694
695    /**
696     * Used to control and query the state of display magnification.
697     */
698    public static final class MagnificationController {
699        private final AccessibilityService mService;
700
701        /**
702         * Map of listeners to their handlers. Lazily created when adding the
703         * first magnification listener.
704         */
705        private ArrayMap<OnMagnificationChangedListener, Handler> mListeners;
706        private final Object mLock;
707
708        MagnificationController(@NonNull AccessibilityService service, @NonNull Object lock) {
709            mService = service;
710            mLock = lock;
711        }
712
713        /**
714         * Called when the service is connected.
715         */
716        void onServiceConnected() {
717            synchronized (mLock) {
718                if (mListeners != null && !mListeners.isEmpty()) {
719                    setMagnificationCallbackEnabled(true);
720                }
721            }
722        }
723
724        /**
725         * Adds the specified change listener to the list of magnification
726         * change listeners. The callback will occur on the service's main
727         * thread.
728         *
729         * @param listener the listener to add, must be non-{@code null}
730         */
731        public void addListener(@NonNull OnMagnificationChangedListener listener) {
732            addListener(listener, null);
733        }
734
735        /**
736         * Adds the specified change listener to the list of magnification
737         * change listeners. The callback will occur on the specified
738         * {@link Handler}'s thread, or on the service's main thread if the
739         * handler is {@code null}.
740         *
741         * @param listener the listener to add, must be non-null
742         * @param handler the handler on which the callback should execute, or
743         *        {@code null} to execute on the service's main thread
744         */
745        public void addListener(@NonNull OnMagnificationChangedListener listener,
746                @Nullable Handler handler) {
747            synchronized (mLock) {
748                if (mListeners == null) {
749                    mListeners = new ArrayMap<>();
750                }
751
752                final boolean shouldEnableCallback = mListeners.isEmpty();
753                mListeners.put(listener, handler);
754
755                if (shouldEnableCallback) {
756                    // This may fail if the service is not connected yet, but if we
757                    // still have listeners when it connects then we can try again.
758                    setMagnificationCallbackEnabled(true);
759                }
760            }
761        }
762
763        /**
764         * Removes all instances of the specified change listener from the list
765         * of magnification change listeners.
766         *
767         * @param listener the listener to remove, must be non-null
768         * @return {@code true} if at least one instance of the listener was
769         *         removed
770         */
771        public boolean removeListener(@NonNull OnMagnificationChangedListener listener) {
772            if (mListeners == null) {
773                return false;
774            }
775
776            synchronized (mLock) {
777                final int keyIndex = mListeners.indexOfKey(listener);
778                final boolean hasKey = keyIndex >= 0;
779                if (hasKey) {
780                    mListeners.removeAt(keyIndex);
781                }
782
783                if (hasKey && mListeners.isEmpty()) {
784                    // We just removed the last listener, so we don't need
785                    // callbacks from the service anymore.
786                    setMagnificationCallbackEnabled(false);
787                }
788
789                return hasKey;
790            }
791        }
792
793        private void setMagnificationCallbackEnabled(boolean enabled) {
794            final IAccessibilityServiceConnection connection =
795                    AccessibilityInteractionClient.getInstance().getConnection(
796                            mService.mConnectionId);
797            if (connection != null) {
798                try {
799                    connection.setMagnificationCallbackEnabled(enabled);
800                } catch (RemoteException re) {
801                    throw new RuntimeException(re);
802                }
803            }
804        }
805
806        /**
807         * Dispatches magnification changes to any registered listeners. This
808         * should be called on the service's main thread.
809         */
810        void dispatchMagnificationChanged(final @NonNull Region region, final float scale,
811                final float centerX, final float centerY) {
812            final ArrayMap<OnMagnificationChangedListener, Handler> entries;
813            synchronized (mLock) {
814                if (mListeners == null || mListeners.isEmpty()) {
815                    Slog.d(LOG_TAG, "Received magnification changed "
816                            + "callback with no listeners registered!");
817                    setMagnificationCallbackEnabled(false);
818                    return;
819                }
820
821                // Listeners may remove themselves. Perform a shallow copy to avoid concurrent
822                // modification.
823                entries = new ArrayMap<>(mListeners);
824            }
825
826            for (int i = 0, count = entries.size(); i < count; i++) {
827                final OnMagnificationChangedListener listener = entries.keyAt(i);
828                final Handler handler = entries.valueAt(i);
829                if (handler != null) {
830                    handler.post(new Runnable() {
831                        @Override
832                        public void run() {
833                            listener.onMagnificationChanged(MagnificationController.this,
834                                    region, scale, centerX, centerY);
835                        }
836                    });
837                } else {
838                    // We're already on the main thread, just run the listener.
839                    listener.onMagnificationChanged(this, region, scale, centerX, centerY);
840                }
841            }
842        }
843
844        /**
845         * Returns the current magnification scale.
846         * <p>
847         * <strong>Note:</strong> If the service is not yet connected (e.g.
848         * {@link AccessibilityService#onServiceConnected()} has not yet been
849         * called) or the service has been disconnected, this method will
850         * return a default value of {@code 1.0f}.
851         *
852         * @return the current magnification scale
853         */
854        public float getScale() {
855            final IAccessibilityServiceConnection connection =
856                    AccessibilityInteractionClient.getInstance().getConnection(
857                            mService.mConnectionId);
858            if (connection != null) {
859                try {
860                    return connection.getMagnificationScale();
861                } catch (RemoteException re) {
862                    Log.w(LOG_TAG, "Failed to obtain scale", re);
863                    re.rethrowFromSystemServer();
864                }
865            }
866            return 1.0f;
867        }
868
869        /**
870         * Returns the unscaled screen-relative X coordinate of the focal
871         * center of the magnified region. This is the point around which
872         * zooming occurs and is guaranteed to lie within the magnified
873         * region.
874         * <p>
875         * <strong>Note:</strong> If the service is not yet connected (e.g.
876         * {@link AccessibilityService#onServiceConnected()} has not yet been
877         * called) or the service has been disconnected, this method will
878         * return a default value of {@code 0.0f}.
879         *
880         * @return the unscaled screen-relative X coordinate of the center of
881         *         the magnified region
882         */
883        public float getCenterX() {
884            final IAccessibilityServiceConnection connection =
885                    AccessibilityInteractionClient.getInstance().getConnection(
886                            mService.mConnectionId);
887            if (connection != null) {
888                try {
889                    return connection.getMagnificationCenterX();
890                } catch (RemoteException re) {
891                    Log.w(LOG_TAG, "Failed to obtain center X", re);
892                    re.rethrowFromSystemServer();
893                }
894            }
895            return 0.0f;
896        }
897
898        /**
899         * Returns the unscaled screen-relative Y coordinate of the focal
900         * center of the magnified region. This is the point around which
901         * zooming occurs and is guaranteed to lie within the magnified
902         * region.
903         * <p>
904         * <strong>Note:</strong> If the service is not yet connected (e.g.
905         * {@link AccessibilityService#onServiceConnected()} has not yet been
906         * called) or the service has been disconnected, this method will
907         * return a default value of {@code 0.0f}.
908         *
909         * @return the unscaled screen-relative Y coordinate of the center of
910         *         the magnified region
911         */
912        public float getCenterY() {
913            final IAccessibilityServiceConnection connection =
914                    AccessibilityInteractionClient.getInstance().getConnection(
915                            mService.mConnectionId);
916            if (connection != null) {
917                try {
918                    return connection.getMagnificationCenterY();
919                } catch (RemoteException re) {
920                    Log.w(LOG_TAG, "Failed to obtain center Y", re);
921                    re.rethrowFromSystemServer();
922                }
923            }
924            return 0.0f;
925        }
926
927        /**
928         * Returns the region of the screen currently being magnified. If
929         * magnification is not enabled, the returned region will be empty.
930         * <p>
931         * <strong>Note:</strong> If the service is not yet connected (e.g.
932         * {@link AccessibilityService#onServiceConnected()} has not yet been
933         * called) or the service has been disconnected, this method will
934         * return an empty region.
935         *
936         * @return the screen-relative bounds of the magnified region
937         */
938        @NonNull
939        public Region getMagnifiedRegion() {
940            final IAccessibilityServiceConnection connection =
941                    AccessibilityInteractionClient.getInstance().getConnection(
942                            mService.mConnectionId);
943            if (connection != null) {
944                try {
945                    return connection.getMagnifiedRegion();
946                } catch (RemoteException re) {
947                    Log.w(LOG_TAG, "Failed to obtain magnified region", re);
948                    re.rethrowFromSystemServer();
949                }
950            }
951            return Region.obtain();
952        }
953
954        /**
955         * Resets magnification scale and center to their default (e.g. no
956         * magnification) values.
957         * <p>
958         * <strong>Note:</strong> If the service is not yet connected (e.g.
959         * {@link AccessibilityService#onServiceConnected()} has not yet been
960         * called) or the service has been disconnected, this method will have
961         * no effect and return {@code false}.
962         *
963         * @param animate {@code true} to animate from the current scale and
964         *                center or {@code false} to reset the scale and center
965         *                immediately
966         * @return {@code true} on success, {@code false} on failure
967         */
968        public boolean reset(boolean animate) {
969            final IAccessibilityServiceConnection connection =
970                    AccessibilityInteractionClient.getInstance().getConnection(
971                            mService.mConnectionId);
972            if (connection != null) {
973                try {
974                    return connection.resetMagnification(animate);
975                } catch (RemoteException re) {
976                    Log.w(LOG_TAG, "Failed to reset", re);
977                    re.rethrowFromSystemServer();
978                }
979            }
980            return false;
981        }
982
983        /**
984         * Sets the magnification scale.
985         * <p>
986         * <strong>Note:</strong> If the service is not yet connected (e.g.
987         * {@link AccessibilityService#onServiceConnected()} has not yet been
988         * called) or the service has been disconnected, this method will have
989         * no effect and return {@code false}.
990         *
991         * @param scale the magnification scale to set, must be >= 1 and <= 5
992         * @param animate {@code true} to animate from the current scale or
993         *                {@code false} to set the scale immediately
994         * @return {@code true} on success, {@code false} on failure
995         */
996        public boolean setScale(float scale, boolean animate) {
997            final IAccessibilityServiceConnection connection =
998                    AccessibilityInteractionClient.getInstance().getConnection(
999                            mService.mConnectionId);
1000            if (connection != null) {
1001                try {
1002                    return connection.setMagnificationScaleAndCenter(
1003                            scale, Float.NaN, Float.NaN, animate);
1004                } catch (RemoteException re) {
1005                    Log.w(LOG_TAG, "Failed to set scale", re);
1006                    re.rethrowFromSystemServer();
1007                }
1008            }
1009            return false;
1010        }
1011
1012        /**
1013         * Sets the center of the magnified viewport.
1014         * <p>
1015         * <strong>Note:</strong> If the service is not yet connected (e.g.
1016         * {@link AccessibilityService#onServiceConnected()} has not yet been
1017         * called) or the service has been disconnected, this method will have
1018         * no effect and return {@code false}.
1019         *
1020         * @param centerX the unscaled screen-relative X coordinate on which to
1021         *                center the viewport
1022         * @param centerY the unscaled screen-relative Y coordinate on which to
1023         *                center the viewport
1024         * @param animate {@code true} to animate from the current viewport
1025         *                center or {@code false} to set the center immediately
1026         * @return {@code true} on success, {@code false} on failure
1027         */
1028        public boolean setCenter(float centerX, float centerY, boolean animate) {
1029            final IAccessibilityServiceConnection connection =
1030                    AccessibilityInteractionClient.getInstance().getConnection(
1031                            mService.mConnectionId);
1032            if (connection != null) {
1033                try {
1034                    return connection.setMagnificationScaleAndCenter(
1035                            Float.NaN, centerX, centerY, animate);
1036                } catch (RemoteException re) {
1037                    Log.w(LOG_TAG, "Failed to set center", re);
1038                    re.rethrowFromSystemServer();
1039                }
1040            }
1041            return false;
1042        }
1043
1044        /**
1045         * Listener for changes in the state of magnification.
1046         */
1047        public interface OnMagnificationChangedListener {
1048            /**
1049             * Called when the magnified region, scale, or center changes.
1050             *
1051             * @param controller the magnification controller
1052             * @param region the new magnified region, may be empty if
1053             *               magnification is not enabled (e.g. scale is 1)
1054             * @param scale the new scale
1055             * @param centerX the new X coordinate around which magnification is focused
1056             * @param centerY the new Y coordinate around which magnification is focused
1057             */
1058            void onMagnificationChanged(@NonNull MagnificationController controller,
1059                    @NonNull Region region, float scale, float centerX, float centerY);
1060        }
1061    }
1062
1063    /**
1064     * Returns the soft keyboard controller, which may be used to query and modify the soft keyboard
1065     * show mode.
1066     *
1067     * @return the soft keyboard controller
1068     */
1069    @NonNull
1070    public final SoftKeyboardController getSoftKeyboardController() {
1071        synchronized (mLock) {
1072            if (mSoftKeyboardController == null) {
1073                mSoftKeyboardController = new SoftKeyboardController(this, mLock);
1074            }
1075            return mSoftKeyboardController;
1076        }
1077    }
1078
1079    private void onSoftKeyboardShowModeChanged(int showMode) {
1080        if (mSoftKeyboardController != null) {
1081            mSoftKeyboardController.dispatchSoftKeyboardShowModeChanged(showMode);
1082        }
1083    }
1084
1085    /**
1086     * Used to control and query the soft keyboard show mode.
1087     */
1088    public static final class SoftKeyboardController {
1089        private final AccessibilityService mService;
1090
1091        /**
1092         * Map of listeners to their handlers. Lazily created when adding the first
1093         * soft keyboard change listener.
1094         */
1095        private ArrayMap<OnShowModeChangedListener, Handler> mListeners;
1096        private final Object mLock;
1097
1098        SoftKeyboardController(@NonNull AccessibilityService service, @NonNull Object lock) {
1099            mService = service;
1100            mLock = lock;
1101        }
1102
1103        /**
1104         * Called when the service is connected.
1105         */
1106        void onServiceConnected() {
1107            synchronized(mLock) {
1108                if (mListeners != null && !mListeners.isEmpty()) {
1109                    setSoftKeyboardCallbackEnabled(true);
1110                }
1111            }
1112        }
1113
1114        /**
1115         * Adds the specified change listener to the list of show mode change listeners. The
1116         * callback will occur on the service's main thread. Listener is not called on registration.
1117         */
1118        public void addOnShowModeChangedListener(@NonNull OnShowModeChangedListener listener) {
1119            addOnShowModeChangedListener(listener, null);
1120        }
1121
1122        /**
1123         * Adds the specified change listener to the list of soft keyboard show mode change
1124         * listeners. The callback will occur on the specified {@link Handler}'s thread, or on the
1125         * services's main thread if the handler is {@code null}.
1126         *
1127         * @param listener the listener to add, must be non-null
1128         * @param handler the handler on which to callback should execute, or {@code null} to
1129         *        execute on the service's main thread
1130         */
1131        public void addOnShowModeChangedListener(@NonNull OnShowModeChangedListener listener,
1132                @Nullable Handler handler) {
1133            synchronized (mLock) {
1134                if (mListeners == null) {
1135                    mListeners = new ArrayMap<>();
1136                }
1137
1138                final boolean shouldEnableCallback = mListeners.isEmpty();
1139                mListeners.put(listener, handler);
1140
1141                if (shouldEnableCallback) {
1142                    // This may fail if the service is not connected yet, but if we still have
1143                    // listeners when it connects, we can try again.
1144                    setSoftKeyboardCallbackEnabled(true);
1145                }
1146            }
1147        }
1148
1149        /**
1150         * Removes all instances of the specified change listener from the list of magnification
1151         * change listeners.
1152         *
1153         * @param listener the listener to remove, must be non-null
1154         * @return {@code true} if at least one instance of the listener was removed
1155         */
1156        public boolean removeOnShowModeChangedListener(@NonNull OnShowModeChangedListener listener) {
1157            if (mListeners == null) {
1158                return false;
1159            }
1160
1161            synchronized (mLock) {
1162                final int keyIndex = mListeners.indexOfKey(listener);
1163                final boolean hasKey = keyIndex >= 0;
1164                if (hasKey) {
1165                    mListeners.removeAt(keyIndex);
1166                }
1167
1168                if (hasKey && mListeners.isEmpty()) {
1169                    // We just removed the last listener, so we don't need callbacks from the
1170                    // service anymore.
1171                    setSoftKeyboardCallbackEnabled(false);
1172                }
1173
1174                return hasKey;
1175            }
1176        }
1177
1178        private void setSoftKeyboardCallbackEnabled(boolean enabled) {
1179            final IAccessibilityServiceConnection connection =
1180                    AccessibilityInteractionClient.getInstance().getConnection(
1181                            mService.mConnectionId);
1182            if (connection != null) {
1183                try {
1184                    connection.setSoftKeyboardCallbackEnabled(enabled);
1185                } catch (RemoteException re) {
1186                    throw new RuntimeException(re);
1187                }
1188            }
1189        }
1190
1191        /**
1192         * Dispatches the soft keyboard show mode change to any registered listeners. This should
1193         * be called on the service's main thread.
1194         */
1195        void dispatchSoftKeyboardShowModeChanged(final int showMode) {
1196            final ArrayMap<OnShowModeChangedListener, Handler> entries;
1197            synchronized (mLock) {
1198                if (mListeners == null || mListeners.isEmpty()) {
1199                    Slog.d(LOG_TAG, "Received soft keyboard show mode changed callback"
1200                            + " with no listeners registered!");
1201                    setSoftKeyboardCallbackEnabled(false);
1202                    return;
1203                }
1204
1205                // Listeners may remove themselves. Perform a shallow copy to avoid concurrent
1206                // modification.
1207                entries = new ArrayMap<>(mListeners);
1208            }
1209
1210            for (int i = 0, count = entries.size(); i < count; i++) {
1211                final OnShowModeChangedListener listener = entries.keyAt(i);
1212                final Handler handler = entries.valueAt(i);
1213                if (handler != null) {
1214                    handler.post(new Runnable() {
1215                        @Override
1216                        public void run() {
1217                            listener.onShowModeChanged(SoftKeyboardController.this, showMode);
1218                        }
1219                    });
1220                } else {
1221                    // We're already on the main thread, just run the listener.
1222                    listener.onShowModeChanged(this, showMode);
1223                }
1224            }
1225        }
1226
1227        /**
1228         * Returns the show mode of the soft keyboard. The default show mode is
1229         * {@code SHOW_MODE_AUTO}, where the soft keyboard is shown when a text input field is
1230         * focused. An AccessibilityService can also request the show mode
1231         * {@code SHOW_MODE_HIDDEN}, where the soft keyboard is never shown.
1232         *
1233         * @return the current soft keyboard show mode
1234         */
1235        @SoftKeyboardShowMode
1236        public int getShowMode() {
1237           try {
1238               return Settings.Secure.getInt(mService.getContentResolver(),
1239                       Settings.Secure.ACCESSIBILITY_SOFT_KEYBOARD_MODE);
1240           } catch (Settings.SettingNotFoundException e) {
1241               Log.v(LOG_TAG, "Failed to obtain the soft keyboard mode", e);
1242               // The settings hasn't been changed yet, so it's value is null. Return the default.
1243               return 0;
1244           }
1245        }
1246
1247        /**
1248         * Sets the soft keyboard show mode. The default show mode is
1249         * {@code SHOW_MODE_AUTO}, where the soft keyboard is shown when a text input field is
1250         * focused. An AccessibilityService can also request the show mode
1251         * {@code SHOW_MODE_HIDDEN}, where the soft keyboard is never shown. The
1252         * The lastto this method will be honored, regardless of any previous calls (including those
1253         * made by other AccessibilityServices).
1254         * <p>
1255         * <strong>Note:</strong> If the service is not yet conected (e.g.
1256         * {@link AccessibilityService#onServiceConnected()} has not yet been called) or the
1257         * service has been disconnected, this method will hav no effect and return {@code false}.
1258         *
1259         * @param showMode the new show mode for the soft keyboard
1260         * @return {@code true} on success
1261         */
1262        public boolean setShowMode(@SoftKeyboardShowMode int showMode) {
1263           final IAccessibilityServiceConnection connection =
1264                   AccessibilityInteractionClient.getInstance().getConnection(
1265                           mService.mConnectionId);
1266           if (connection != null) {
1267               try {
1268                   return connection.setSoftKeyboardShowMode(showMode);
1269               } catch (RemoteException re) {
1270                   Log.w(LOG_TAG, "Failed to set soft keyboard behavior", re);
1271                   re.rethrowFromSystemServer();
1272               }
1273           }
1274           return false;
1275        }
1276
1277        /**
1278         * Listener for changes in the soft keyboard show mode.
1279         */
1280        public interface OnShowModeChangedListener {
1281           /**
1282            * Called when the soft keyboard behavior changes. The default show mode is
1283            * {@code SHOW_MODE_AUTO}, where the soft keyboard is shown when a text input field is
1284            * focused. An AccessibilityService can also request the show mode
1285            * {@code SHOW_MODE_HIDDEN}, where the soft keyboard is never shown.
1286            *
1287            * @param controller the soft keyboard controller
1288            * @param showMode the current soft keyboard show mode
1289            */
1290            void onShowModeChanged(@NonNull SoftKeyboardController controller,
1291                    @SoftKeyboardShowMode int showMode);
1292        }
1293    }
1294
1295    /**
1296     * Performs a global action. Such an action can be performed
1297     * at any moment regardless of the current application or user
1298     * location in that application. For example going back, going
1299     * home, opening recents, etc.
1300     *
1301     * @param action The action to perform.
1302     * @return Whether the action was successfully performed.
1303     *
1304     * @see #GLOBAL_ACTION_BACK
1305     * @see #GLOBAL_ACTION_HOME
1306     * @see #GLOBAL_ACTION_NOTIFICATIONS
1307     * @see #GLOBAL_ACTION_RECENTS
1308     */
1309    public final boolean performGlobalAction(int action) {
1310        IAccessibilityServiceConnection connection =
1311            AccessibilityInteractionClient.getInstance().getConnection(mConnectionId);
1312        if (connection != null) {
1313            try {
1314                return connection.performGlobalAction(action);
1315            } catch (RemoteException re) {
1316                Log.w(LOG_TAG, "Error while calling performGlobalAction", re);
1317                re.rethrowFromSystemServer();
1318            }
1319        }
1320        return false;
1321    }
1322
1323    /**
1324     * Find the view that has the specified focus type. The search is performed
1325     * across all windows.
1326     * <p>
1327     * <strong>Note:</strong> In order to access the windows your service has
1328     * to declare the capability to retrieve window content by setting the
1329     * {@link android.R.styleable#AccessibilityService_canRetrieveWindowContent}
1330     * property in its meta-data. For details refer to {@link #SERVICE_META_DATA}.
1331     * Also the service has to opt-in to retrieve the interactive windows by
1332     * setting the {@link AccessibilityServiceInfo#FLAG_RETRIEVE_INTERACTIVE_WINDOWS}
1333     * flag. Otherwise, the search will be performed only in the active window.
1334     * </p>
1335     *
1336     * @param focus The focus to find. One of {@link AccessibilityNodeInfo#FOCUS_INPUT} or
1337     *         {@link AccessibilityNodeInfo#FOCUS_ACCESSIBILITY}.
1338     * @return The node info of the focused view or null.
1339     *
1340     * @see AccessibilityNodeInfo#FOCUS_INPUT
1341     * @see AccessibilityNodeInfo#FOCUS_ACCESSIBILITY
1342     */
1343    public AccessibilityNodeInfo findFocus(int focus) {
1344        return AccessibilityInteractionClient.getInstance().findFocus(mConnectionId,
1345                AccessibilityNodeInfo.ANY_WINDOW_ID, AccessibilityNodeInfo.ROOT_NODE_ID, focus);
1346    }
1347
1348    /**
1349     * Gets the an {@link AccessibilityServiceInfo} describing this
1350     * {@link AccessibilityService}. This method is useful if one wants
1351     * to change some of the dynamically configurable properties at
1352     * runtime.
1353     *
1354     * @return The accessibility service info.
1355     *
1356     * @see AccessibilityServiceInfo
1357     */
1358    public final AccessibilityServiceInfo getServiceInfo() {
1359        IAccessibilityServiceConnection connection =
1360            AccessibilityInteractionClient.getInstance().getConnection(mConnectionId);
1361        if (connection != null) {
1362            try {
1363                return connection.getServiceInfo();
1364            } catch (RemoteException re) {
1365                Log.w(LOG_TAG, "Error while getting AccessibilityServiceInfo", re);
1366                re.rethrowFromSystemServer();
1367            }
1368        }
1369        return null;
1370    }
1371
1372    /**
1373     * Sets the {@link AccessibilityServiceInfo} that describes this service.
1374     * <p>
1375     * Note: You can call this method any time but the info will be picked up after
1376     *       the system has bound to this service and when this method is called thereafter.
1377     *
1378     * @param info The info.
1379     */
1380    public final void setServiceInfo(AccessibilityServiceInfo info) {
1381        mInfo = info;
1382        sendServiceInfo();
1383    }
1384
1385    /**
1386     * Sets the {@link AccessibilityServiceInfo} for this service if the latter is
1387     * properly set and there is an {@link IAccessibilityServiceConnection} to the
1388     * AccessibilityManagerService.
1389     */
1390    private void sendServiceInfo() {
1391        IAccessibilityServiceConnection connection =
1392            AccessibilityInteractionClient.getInstance().getConnection(mConnectionId);
1393        if (mInfo != null && connection != null) {
1394            try {
1395                connection.setServiceInfo(mInfo);
1396                mInfo = null;
1397                AccessibilityInteractionClient.getInstance().clearCache();
1398            } catch (RemoteException re) {
1399                Log.w(LOG_TAG, "Error while setting AccessibilityServiceInfo", re);
1400                re.rethrowFromSystemServer();
1401            }
1402        }
1403    }
1404
1405    @Override
1406    public Object getSystemService(@ServiceName @NonNull String name) {
1407        if (getBaseContext() == null) {
1408            throw new IllegalStateException(
1409                    "System services not available to Activities before onCreate()");
1410        }
1411
1412        // Guarantee that we always return the same window manager instance.
1413        if (WINDOW_SERVICE.equals(name)) {
1414            if (mWindowManager == null) {
1415                mWindowManager = (WindowManager) getBaseContext().getSystemService(name);
1416            }
1417            return mWindowManager;
1418        }
1419        return super.getSystemService(name);
1420    }
1421
1422    /**
1423     * Implement to return the implementation of the internal accessibility
1424     * service interface.
1425     */
1426    @Override
1427    public final IBinder onBind(Intent intent) {
1428        return new IAccessibilityServiceClientWrapper(this, getMainLooper(), new Callbacks() {
1429            @Override
1430            public void onServiceConnected() {
1431                AccessibilityService.this.dispatchServiceConnected();
1432            }
1433
1434            @Override
1435            public void onInterrupt() {
1436                AccessibilityService.this.onInterrupt();
1437            }
1438
1439            @Override
1440            public void onAccessibilityEvent(AccessibilityEvent event) {
1441                AccessibilityService.this.onAccessibilityEvent(event);
1442            }
1443
1444            @Override
1445            public void init(int connectionId, IBinder windowToken) {
1446                mConnectionId = connectionId;
1447                mWindowToken = windowToken;
1448
1449                // The client may have already obtained the window manager, so
1450                // update the default token on whatever manager we gave them.
1451                final WindowManagerImpl wm = (WindowManagerImpl) getSystemService(WINDOW_SERVICE);
1452                wm.setDefaultToken(windowToken);
1453            }
1454
1455            @Override
1456            public boolean onGesture(int gestureId) {
1457                return AccessibilityService.this.onGesture(gestureId);
1458            }
1459
1460            @Override
1461            public boolean onKeyEvent(KeyEvent event) {
1462                return AccessibilityService.this.onKeyEvent(event);
1463            }
1464
1465            @Override
1466            public void onMagnificationChanged(@NonNull Region region,
1467                    float scale, float centerX, float centerY) {
1468                AccessibilityService.this.onMagnificationChanged(region, scale, centerX, centerY);
1469            }
1470
1471            @Override
1472            public void onSoftKeyboardShowModeChanged(int showMode) {
1473                AccessibilityService.this.onSoftKeyboardShowModeChanged(showMode);
1474            }
1475
1476            @Override
1477            public void onPerformGestureResult(int sequence, boolean completedSuccessfully) {
1478                AccessibilityService.this.onPerformGestureResult(sequence, completedSuccessfully);
1479            }
1480        });
1481    }
1482
1483    /**
1484     * Implements the internal {@link IAccessibilityServiceClient} interface to convert
1485     * incoming calls to it back to calls on an {@link AccessibilityService}.
1486     *
1487     * @hide
1488     */
1489    public static class IAccessibilityServiceClientWrapper extends IAccessibilityServiceClient.Stub
1490            implements HandlerCaller.Callback {
1491        private static final int DO_INIT = 1;
1492        private static final int DO_ON_INTERRUPT = 2;
1493        private static final int DO_ON_ACCESSIBILITY_EVENT = 3;
1494        private static final int DO_ON_GESTURE = 4;
1495        private static final int DO_CLEAR_ACCESSIBILITY_CACHE = 5;
1496        private static final int DO_ON_KEY_EVENT = 6;
1497        private static final int DO_ON_MAGNIFICATION_CHANGED = 7;
1498        private static final int DO_ON_SOFT_KEYBOARD_SHOW_MODE_CHANGED = 8;
1499        private static final int DO_GESTURE_COMPLETE = 9;
1500
1501        private final HandlerCaller mCaller;
1502
1503        private final Callbacks mCallback;
1504
1505        private int mConnectionId;
1506
1507        public IAccessibilityServiceClientWrapper(Context context, Looper looper,
1508                Callbacks callback) {
1509            mCallback = callback;
1510            mCaller = new HandlerCaller(context, looper, this, true /*asyncHandler*/);
1511        }
1512
1513        public void init(IAccessibilityServiceConnection connection, int connectionId,
1514                IBinder windowToken) {
1515            Message message = mCaller.obtainMessageIOO(DO_INIT, connectionId,
1516                    connection, windowToken);
1517            mCaller.sendMessage(message);
1518        }
1519
1520        public void onInterrupt() {
1521            Message message = mCaller.obtainMessage(DO_ON_INTERRUPT);
1522            mCaller.sendMessage(message);
1523        }
1524
1525        public void onAccessibilityEvent(AccessibilityEvent event) {
1526            Message message = mCaller.obtainMessageO(DO_ON_ACCESSIBILITY_EVENT, event);
1527            mCaller.sendMessage(message);
1528        }
1529
1530        public void onGesture(int gestureId) {
1531            Message message = mCaller.obtainMessageI(DO_ON_GESTURE, gestureId);
1532            mCaller.sendMessage(message);
1533        }
1534
1535        public void clearAccessibilityCache() {
1536            Message message = mCaller.obtainMessage(DO_CLEAR_ACCESSIBILITY_CACHE);
1537            mCaller.sendMessage(message);
1538        }
1539
1540        @Override
1541        public void onKeyEvent(KeyEvent event, int sequence) {
1542            Message message = mCaller.obtainMessageIO(DO_ON_KEY_EVENT, sequence, event);
1543            mCaller.sendMessage(message);
1544        }
1545
1546        public void onMagnificationChanged(@NonNull Region region,
1547                float scale, float centerX, float centerY) {
1548            final SomeArgs args = SomeArgs.obtain();
1549            args.arg1 = region;
1550            args.arg2 = scale;
1551            args.arg3 = centerX;
1552            args.arg4 = centerY;
1553
1554            final Message message = mCaller.obtainMessageO(DO_ON_MAGNIFICATION_CHANGED, args);
1555            mCaller.sendMessage(message);
1556        }
1557
1558        public void onSoftKeyboardShowModeChanged(int showMode) {
1559          final Message message =
1560                  mCaller.obtainMessageI(DO_ON_SOFT_KEYBOARD_SHOW_MODE_CHANGED, showMode);
1561          mCaller.sendMessage(message);
1562        }
1563
1564        public void onPerformGestureResult(int sequence, boolean successfully) {
1565            Message message = mCaller.obtainMessageII(DO_GESTURE_COMPLETE, sequence,
1566                    successfully ? 1 : 0);
1567            mCaller.sendMessage(message);
1568        }
1569
1570        @Override
1571        public void executeMessage(Message message) {
1572            switch (message.what) {
1573                case DO_ON_ACCESSIBILITY_EVENT: {
1574                    AccessibilityEvent event = (AccessibilityEvent) message.obj;
1575                    if (event != null) {
1576                        AccessibilityInteractionClient.getInstance().onAccessibilityEvent(event);
1577                        mCallback.onAccessibilityEvent(event);
1578                        // Make sure the event is recycled.
1579                        try {
1580                            event.recycle();
1581                        } catch (IllegalStateException ise) {
1582                            /* ignore - best effort */
1583                        }
1584                    }
1585                } return;
1586
1587                case DO_ON_INTERRUPT: {
1588                    mCallback.onInterrupt();
1589                } return;
1590
1591                case DO_INIT: {
1592                    mConnectionId = message.arg1;
1593                    SomeArgs args = (SomeArgs) message.obj;
1594                    IAccessibilityServiceConnection connection =
1595                            (IAccessibilityServiceConnection) args.arg1;
1596                    IBinder windowToken = (IBinder) args.arg2;
1597                    args.recycle();
1598                    if (connection != null) {
1599                        AccessibilityInteractionClient.getInstance().addConnection(mConnectionId,
1600                                connection);
1601                        mCallback.init(mConnectionId, windowToken);
1602                        mCallback.onServiceConnected();
1603                    } else {
1604                        AccessibilityInteractionClient.getInstance().removeConnection(
1605                                mConnectionId);
1606                        mConnectionId = AccessibilityInteractionClient.NO_ID;
1607                        AccessibilityInteractionClient.getInstance().clearCache();
1608                        mCallback.init(AccessibilityInteractionClient.NO_ID, null);
1609                    }
1610                } return;
1611
1612                case DO_ON_GESTURE: {
1613                    final int gestureId = message.arg1;
1614                    mCallback.onGesture(gestureId);
1615                } return;
1616
1617                case DO_CLEAR_ACCESSIBILITY_CACHE: {
1618                    AccessibilityInteractionClient.getInstance().clearCache();
1619                } return;
1620
1621                case DO_ON_KEY_EVENT: {
1622                    KeyEvent event = (KeyEvent) message.obj;
1623                    try {
1624                        IAccessibilityServiceConnection connection = AccessibilityInteractionClient
1625                                .getInstance().getConnection(mConnectionId);
1626                        if (connection != null) {
1627                            final boolean result = mCallback.onKeyEvent(event);
1628                            final int sequence = message.arg1;
1629                            try {
1630                                connection.setOnKeyEventResult(result, sequence);
1631                            } catch (RemoteException re) {
1632                                /* ignore */
1633                            }
1634                        }
1635                    } finally {
1636                        // Make sure the event is recycled.
1637                        try {
1638                            event.recycle();
1639                        } catch (IllegalStateException ise) {
1640                            /* ignore - best effort */
1641                        }
1642                    }
1643                } return;
1644
1645                case DO_ON_MAGNIFICATION_CHANGED: {
1646                    final SomeArgs args = (SomeArgs) message.obj;
1647                    final Region region = (Region) args.arg1;
1648                    final float scale = (float) args.arg2;
1649                    final float centerX = (float) args.arg3;
1650                    final float centerY = (float) args.arg4;
1651                    mCallback.onMagnificationChanged(region, scale, centerX, centerY);
1652                } return;
1653
1654                case DO_ON_SOFT_KEYBOARD_SHOW_MODE_CHANGED: {
1655                    final int showMode = (int) message.arg1;
1656                    mCallback.onSoftKeyboardShowModeChanged(showMode);
1657                } return;
1658
1659                case DO_GESTURE_COMPLETE: {
1660                    final boolean successfully = message.arg2 == 1;
1661                    mCallback.onPerformGestureResult(message.arg1, successfully);
1662                } return;
1663
1664                default :
1665                    Log.w(LOG_TAG, "Unknown message type " + message.what);
1666            }
1667        }
1668    }
1669
1670    /**
1671     * Class used to report status of dispatched gestures
1672     */
1673    public static abstract class GestureResultCallback {
1674        /** Called when the gesture has completed successfully
1675         *
1676         * @param gestureDescription The description of the gesture that completed.
1677         */
1678        public void onCompleted(GestureDescription gestureDescription) {
1679        }
1680
1681        /** Called when the gesture was cancelled
1682         *
1683         * @param gestureDescription The description of the gesture that was cancelled.
1684         */
1685        public void onCancelled(GestureDescription gestureDescription) {
1686        }
1687    }
1688
1689    /* Object to keep track of gesture result callbacks */
1690    private static class GestureResultCallbackInfo {
1691        GestureDescription gestureDescription;
1692        GestureResultCallback callback;
1693        Handler handler;
1694
1695        GestureResultCallbackInfo(GestureDescription gestureDescription,
1696                GestureResultCallback callback, Handler handler) {
1697            this.gestureDescription = gestureDescription;
1698            this.callback = callback;
1699            this.handler = handler;
1700        }
1701    }
1702}
1703