AccessibilityService.java revision 4213804541a8b05cd0587b138a2fd9a3b7fd9350
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.app.Service;
20import android.content.Context;
21import android.content.Intent;
22import android.content.res.Configuration;
23import android.os.IBinder;
24import android.os.Looper;
25import android.os.Message;
26import android.os.RemoteException;
27import android.util.LocaleUtil;
28import android.util.Log;
29import android.view.View;
30import android.view.accessibility.AccessibilityEvent;
31import android.view.accessibility.AccessibilityInteractionClient;
32import android.view.accessibility.AccessibilityNodeInfo;
33
34import com.android.internal.os.HandlerCaller;
35
36import java.util.Locale;
37
38/**
39 * An accessibility service runs in the background and receives callbacks by the system
40 * when {@link AccessibilityEvent}s are fired. Such events denote some state transition
41 * in the user interface, for example, the focus has changed, a button has been clicked,
42 * etc. Such a service can optionally request the capability for querying the content
43 * of the active window. Development of an accessibility service requires extending this
44 * class and implementing its abstract methods.
45 *
46 * <div class="special reference">
47 * <h3>Developer Guides</h3>
48 * <p>For more information about creating AccessibilityServices, read the
49 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
50 * developer guide.</p>
51 * </div>
52 *
53 * <h3>Lifecycle</h3>
54 * <p>
55 * The lifecycle of an accessibility service is managed exclusively by the system and
56 * follows the established service life cycle. Additionally, starting or stopping an
57 * accessibility service is triggered exclusively by an explicit user action through
58 * enabling or disabling it in the device settings. After the system binds to a service it
59 * calls {@link AccessibilityService#onServiceConnected()}. This method can be
60 * overriden by clients that want to perform post binding setup.
61 * </p>
62 * <h3>Declaration</h3>
63 * <p>
64 * An accessibility is declared as any other service in an AndroidManifest.xml but it
65 * must also specify that it handles the "android.accessibilityservice.AccessibilityService"
66 * {@link android.content.Intent}. Failure to declare this intent will cause the system to
67 * ignore the accessibility service. Following is an example declaration:
68 * </p>
69 * <pre> &lt;service android:name=".MyAccessibilityService"&gt;
70 *     &lt;intent-filter&gt;
71 *         &lt;action android:name="android.accessibilityservice.AccessibilityService" /&gt;
72 *     &lt;/intent-filter&gt;
73 *     . . .
74 * &lt;/service&gt;</pre>
75 * <h3>Configuration</h3>
76 * <p>
77 * An accessibility service can be configured to receive specific types of accessibility events,
78 * listen only to specific packages, get events from each type only once in a given time frame,
79 * retrieve window content, specify a settings activity, etc.
80 * </p>
81 * <p>
82 * There are two approaches for configuring an accessibility service:
83 * </p>
84 * <ul>
85 * <li>
86 * Providing a {@link #SERVICE_META_DATA meta-data} entry in the manifest when declaring
87 * the service. A service declaration with a meta-data tag is presented below:
88 * <pre> &lt;service android:name=".MyAccessibilityService"&gt;
89 *     &lt;intent-filter&gt;
90 *         &lt;action android:name="android.accessibilityservice.AccessibilityService" /&gt;
91 *     &lt;/intent-filter&gt;
92 *     &lt;meta-data android:name="android.accessibilityservice" android:resource="@xml/accessibilityservice" /&gt;
93 * &lt;/service&gt;</pre>
94 * <p class="note">
95 * <strong>Note:</strong> This approach enables setting all properties.
96 * </p>
97 * <p>
98 * For more details refer to {@link #SERVICE_META_DATA} and
99 * <code>&lt;{@link android.R.styleable#AccessibilityService accessibility-service}&gt;</code>.
100 * </p>
101 * </li>
102 * <li>
103 * Calling {@link AccessibilityService#setServiceInfo(AccessibilityServiceInfo)}. Note
104 * that this method can be called any time to dynamically change the service configuration.
105 * <p class="note">
106 * <strong>Note:</strong> This approach enables setting only dynamically configurable properties:
107 * {@link AccessibilityServiceInfo#eventTypes},
108 * {@link AccessibilityServiceInfo#feedbackType},
109 * {@link AccessibilityServiceInfo#flags},
110 * {@link AccessibilityServiceInfo#notificationTimeout},
111 * {@link AccessibilityServiceInfo#packageNames}
112 * </p>
113 * <p>
114 * For more details refer to {@link AccessibilityServiceInfo}.
115 * </p>
116 * </li>
117 * </ul>
118 * <h3>Retrieving window content</h3>
119 * <p>
120 * A service can specify in its declaration that it can retrieve the active window
121 * content which is represented as a tree of {@link AccessibilityNodeInfo}. Note that
122 * declaring this capability requires that the service declares its configuration via
123 * an XML resource referenced by {@link #SERVICE_META_DATA}.
124 * </p>
125 * <p>
126 * For security purposes an accessibility service can retrieve only the content of the
127 * currently active window. The currently active window is defined as the window from
128 * which was fired the last event of the following types:
129 * {@link AccessibilityEvent#TYPE_WINDOW_STATE_CHANGED},
130 * {@link AccessibilityEvent#TYPE_VIEW_HOVER_ENTER},
131 * {@link AccessibilityEvent#TYPE_VIEW_HOVER_EXIT},
132 * In other words, the last window that was shown or the last window that the user has touched
133 * during touch exploration.
134 * </p>
135 * <p>
136 * The entry point for retrieving window content is through calling
137 * {@link AccessibilityEvent#getSource() AccessibilityEvent.getSource()} of the last received
138 * event of the above types or a previous event from the same window
139 * (see {@link AccessibilityEvent#getWindowId() AccessibilityEvent.getWindowId()}). Invoking
140 * this method will return an {@link AccessibilityNodeInfo} that can be used to traverse the
141 * window content which represented as a tree of such objects.
142 * </p>
143 * <p class="note">
144 * <strong>Note</strong> An accessibility service may have requested to be notified for
145 * a subset of the event types, thus be unaware that the active window has changed. Therefore
146 * accessibility service that would like to retrieve window content should:
147 * <ul>
148 * <li>
149 * Register for all event types with no notification timeout and keep track for the active
150 * window by calling {@link AccessibilityEvent#getWindowId()} of the last received event and
151 * compare this with the {@link AccessibilityNodeInfo#getWindowId()} before calling retrieval
152 * methods on the latter.
153 * </li>
154 * <li>
155 * Prepare that a retrieval method on {@link AccessibilityNodeInfo} may fail since the
156 * active window has changed and the service did not get the accessibility event yet. Note
157 * that it is possible to have a retrieval method failing even adopting the strategy
158 * specified in the previous bullet because the accessibility event dispatch is asynchronous
159 * and crosses process boundaries.
160 * </li>
161 * </ul>
162 * </p>
163 * <h3>Notification strategy</h3>
164 * <p>
165 * For each feedback type only one accessibility service is notified. Services are notified
166 * in the order of registration. Hence, if two services are registered for the same
167 * feedback type in the same package the first one wins. It is possible however, to
168 * register a service as the default one for a given feedback type. In such a case this
169 * service is invoked if no other service was interested in the event. In other words, default
170 * services do not compete with other services and are notified last regardless of the
171 * registration order. This enables "generic" accessibility services that work reasonably
172 * well with most applications to coexist with "polished" ones that are targeted for
173 * specific applications.
174 * </p>
175 * <p class="note">
176 * <strong>Note:</strong> The event notification timeout is useful to avoid propagating
177 * events to the client too frequently since this is accomplished via an expensive
178 * interprocess call. One can think of the timeout as a criteria to determine when
179 * event generation has settled down.</p>
180 * <h3>Event types</h3>
181 * <ul>
182 * <li>{@link AccessibilityEvent#TYPE_VIEW_CLICKED}
183 * <li>{@link AccessibilityEvent#TYPE_VIEW_LONG_CLICKED}
184 * <li>{@link AccessibilityEvent#TYPE_VIEW_FOCUSED}
185 * <li>{@link AccessibilityEvent#TYPE_VIEW_SELECTED}
186 * <li>{@link AccessibilityEvent#TYPE_VIEW_TEXT_CHANGED}
187 * <li>{@link AccessibilityEvent#TYPE_WINDOW_STATE_CHANGED}
188 * <li>{@link AccessibilityEvent#TYPE_NOTIFICATION_STATE_CHANGED}
189 * <li>{@link AccessibilityEvent#TYPE_TOUCH_EXPLORATION_GESTURE_START}
190 * <li>{@link AccessibilityEvent#TYPE_TOUCH_EXPLORATION_GESTURE_END}
191 * <li>{@link AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}
192 * <li>{@link AccessibilityEvent#TYPE_VIEW_HOVER_EXIT}
193 * <li>{@link AccessibilityEvent#TYPE_VIEW_SCROLLED}
194 * <li>{@link AccessibilityEvent#TYPE_VIEW_TEXT_SELECTION_CHANGED}
195 * <li>{@link AccessibilityEvent#TYPE_WINDOW_CONTENT_CHANGED}
196 * </ul>
197 * <h3>Feedback types</h3>
198 * <ul>
199 * <li>{@link AccessibilityServiceInfo#FEEDBACK_AUDIBLE}
200 * <li>{@link AccessibilityServiceInfo#FEEDBACK_HAPTIC}
201 * <li>{@link AccessibilityServiceInfo#FEEDBACK_AUDIBLE}
202 * <li>{@link AccessibilityServiceInfo#FEEDBACK_VISUAL}
203 * <li>{@link AccessibilityServiceInfo#FEEDBACK_GENERIC}
204 * </ul>
205 * @see AccessibilityEvent
206 * @see AccessibilityServiceInfo
207 * @see android.view.accessibility.AccessibilityManager
208 */
209public abstract class AccessibilityService extends Service {
210
211    /**
212     * The user has performed a swipe up gesture on the touch screen.
213     */
214    public static final int GESTURE_SWIPE_UP = 1;
215
216    /**
217     * The user has performed a swipe down gesture on the touch screen.
218     */
219    public static final int GESTURE_SWIPE_DOWN = 2;
220
221    /**
222     * The user has performed a swipe left gesture on the touch screen.
223     */
224    public static final int GESTURE_SWIPE_LEFT = 3;
225
226    /**
227     * The user has performed a swipe right gesture on the touch screen.
228     */
229    public static final int GESTURE_SWIPE_RIGHT = 4;
230
231    /**
232     * The user has performed a swipe left and right gesture on the touch screen.
233     */
234    public static final int GESTURE_SWIPE_LEFT_AND_RIGHT = 5;
235
236    /**
237     * The user has performed a swipe right and left gesture on the touch screen.
238     */
239    public static final int GESTURE_SWIPE_RIGHT_AND_LEFT = 6;
240
241    /**
242     * The user has performed a swipe up and down gesture on the touch screen.
243     */
244    public static final int GESTURE_SWIPE_UP_AND_DOWN = 7;
245
246    /**
247     * The user has performed a swipe down and up gesture on the touch screen.
248     */
249    public static final int GESTURE_SWIPE_DOWN_AND_UP = 8;
250
251    /**
252     * The user has performed a clockwise circle gesture on the touch screen.
253     */
254    public static final int GESTURE_CLOCKWISE_CIRCLE = 9;
255
256    /**
257     * The user has performed a counter clockwise circle gesture on the touch screen.
258     */
259    public static final int GESTURE_COUNTER_CLOCKWISE_CIRCLE = 10;
260
261    /**
262     * The {@link Intent} that must be declared as handled by the service.
263     */
264    public static final String SERVICE_INTERFACE =
265        "android.accessibilityservice.AccessibilityService";
266
267    private static final int UNDEFINED = -1;
268
269    /**
270     * Name under which an AccessibilityService component publishes information
271     * about itself. This meta-data must reference an XML resource containing an
272     * <code>&lt;{@link android.R.styleable#AccessibilityService accessibility-service}&gt;</code>
273     * tag. This is a a sample XML file configuring an accessibility service:
274     * <pre> &lt;accessibility-service
275     *     android:accessibilityEventTypes="typeViewClicked|typeViewFocused"
276     *     android:packageNames="foo.bar, foo.baz"
277     *     android:accessibilityFeedbackType="feedbackSpoken"
278     *     android:notificationTimeout="100"
279     *     android:accessibilityFlags="flagDefault"
280     *     android:settingsActivity="foo.bar.TestBackActivity"
281     *     android:canRetrieveWindowContent="true"
282     *     . . .
283     * /&gt;</pre>
284     */
285    public static final String SERVICE_META_DATA = "android.accessibilityservice";
286
287    private static final String LOG_TAG = "AccessibilityService";
288
289    interface Callbacks {
290        public void onAccessibilityEvent(AccessibilityEvent event);
291        public void onInterrupt();
292        public void onServiceConnected();
293        public void onSetConnectionId(int connectionId);
294        public void onGesture(int gestureId);
295    }
296
297    private int mConnectionId;
298
299    private AccessibilityServiceInfo mInfo;
300
301    private int mLayoutDirection;
302
303    /**
304     * Callback for {@link android.view.accessibility.AccessibilityEvent}s.
305     *
306     * @param event An event.
307     */
308    public abstract void onAccessibilityEvent(AccessibilityEvent event);
309
310    /**
311     * Callback for interrupting the accessibility feedback.
312     */
313    public abstract void onInterrupt();
314
315    /**
316     * This method is a part of the {@link AccessibilityService} lifecycle and is
317     * called after the system has successfully bound to the service. If is
318     * convenient to use this method for setting the {@link AccessibilityServiceInfo}.
319     *
320     * @see AccessibilityServiceInfo
321     * @see #setServiceInfo(AccessibilityServiceInfo)
322     */
323    protected void onServiceConnected() {
324
325    }
326
327    /**
328     * Called by the system when the user performs a specific gesture on the
329     * touch screen.
330     *
331     * @param gestureId The unique id of the performed gesture.
332     *
333     * @see #GESTURE_SWIPE_UP
334     * @see #GESTURE_SWIPE_DOWN
335     * @see #GESTURE_SWIPE_LEFT
336     * @see #GESTURE_SWIPE_RIGHT
337     * @see #GESTURE_SWIPE_UP_AND_DOWN
338     * @see #GESTURE_SWIPE_DOWN_AND_UP
339     * @see #GESTURE_SWIPE_LEFT_AND_RIGHT
340     * @see #GESTURE_SWIPE_RIGHT_AND_LEFT
341     * @see #GESTURE_CLOCKWISE_CIRCLE
342     * @see #GESTURE_COUNTER_CLOCKWISE_CIRCLE
343     */
344    protected void onGesture(int gestureId) {
345        // TODO: Describe the default gesture processing in the javaDoc once it is finalized.
346
347        // Cache the id to avoid locking
348        final int connectionId = mConnectionId;
349        if (connectionId == UNDEFINED) {
350            throw new IllegalStateException("AccessibilityService not connected."
351                    + " Did you receive a call of onServiceConnected()?");
352        }
353        AccessibilityNodeInfo root = AccessibilityInteractionClient.getInstance()
354                .findAccessibilityNodeInfoByAccessibilityId(connectionId,
355                        AccessibilityNodeInfo.ACTIVE_WINDOW_ID, AccessibilityNodeInfo.ROOT_NODE_ID,
356                        AccessibilityNodeInfo.FLAG_PREFETCH_DESCENDANTS);
357        if (root == null) {
358            return;
359        }
360        AccessibilityNodeInfo current = root.findFocus(View.FOCUS_ACCESSIBILITY);
361        if (current == null) {
362            current = root;
363        }
364        AccessibilityNodeInfo next = null;
365        switch (gestureId) {
366            case GESTURE_SWIPE_UP: {
367                next = current.focusSearch(View.ACCESSIBILITY_FOCUS_OUT);
368            } break;
369            case GESTURE_SWIPE_DOWN: {
370                next = current.focusSearch(View.ACCESSIBILITY_FOCUS_IN);
371            } break;
372            case GESTURE_SWIPE_LEFT: {
373                if (mLayoutDirection == View.LAYOUT_DIRECTION_LTR) {
374                    next = current.focusSearch(View.ACCESSIBILITY_FOCUS_BACKWARD);
375                } else { // LAYOUT_DIRECTION_RTL
376                    next = current.focusSearch(View.ACCESSIBILITY_FOCUS_FORWARD);
377                }
378            } break;
379            case GESTURE_SWIPE_RIGHT: {
380                if (mLayoutDirection == View.LAYOUT_DIRECTION_LTR) {
381                    next = current.focusSearch(View.ACCESSIBILITY_FOCUS_FORWARD);
382                } else { // LAYOUT_DIRECTION_RTL
383                    next = current.focusSearch(View.ACCESSIBILITY_FOCUS_BACKWARD);
384                }
385            } break;
386            case GESTURE_SWIPE_UP_AND_DOWN: {
387                next = current.focusSearch(View.ACCESSIBILITY_FOCUS_UP);
388            } break;
389            case GESTURE_SWIPE_DOWN_AND_UP: {
390                next = current.focusSearch(View.ACCESSIBILITY_FOCUS_DOWN);
391            } break;
392            case GESTURE_SWIPE_LEFT_AND_RIGHT: {
393                next = current.focusSearch(View.ACCESSIBILITY_FOCUS_LEFT);
394            } break;
395            case GESTURE_SWIPE_RIGHT_AND_LEFT: {
396                next = current.focusSearch(View.ACCESSIBILITY_FOCUS_RIGHT);
397            } break;
398        }
399        if (next != null && !next.equals(current)) {
400            next.performAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
401        }
402    }
403
404    /**
405     * Gets the an {@link AccessibilityServiceInfo} describing this
406     * {@link AccessibilityService}. This method is useful if one wants
407     * to change some of the dynamically configurable properties at
408     * runtime.
409     *
410     * @return The accessibility service info.
411     *
412     * @see AccessibilityNodeInfo
413     */
414    public final AccessibilityServiceInfo getServiceInfo() {
415        IAccessibilityServiceConnection connection =
416            AccessibilityInteractionClient.getInstance().getConnection(mConnectionId);
417        if (connection != null) {
418            try {
419                return connection.getServiceInfo();
420            } catch (RemoteException re) {
421                Log.w(LOG_TAG, "Error while getting AccessibilityServiceInfo", re);
422            }
423        }
424        return null;
425    }
426
427    /**
428     * Sets the {@link AccessibilityServiceInfo} that describes this service.
429     * <p>
430     * Note: You can call this method any time but the info will be picked up after
431     *       the system has bound to this service and when this method is called thereafter.
432     *
433     * @param info The info.
434     */
435    public final void setServiceInfo(AccessibilityServiceInfo info) {
436        mInfo = info;
437        sendServiceInfo();
438    }
439
440    /**
441     * Sets the {@link AccessibilityServiceInfo} for this service if the latter is
442     * properly set and there is an {@link IAccessibilityServiceConnection} to the
443     * AccessibilityManagerService.
444     */
445    private void sendServiceInfo() {
446        IAccessibilityServiceConnection connection =
447            AccessibilityInteractionClient.getInstance().getConnection(mConnectionId);
448        if (mInfo != null && connection != null) {
449            try {
450                connection.setServiceInfo(mInfo);
451                mInfo = null;
452                AccessibilityInteractionClient.getInstance().clearCache();
453            } catch (RemoteException re) {
454                Log.w(LOG_TAG, "Error while setting AccessibilityServiceInfo", re);
455            }
456        }
457    }
458
459    @Override
460    public void onCreate() {
461        Locale locale = getResources().getConfiguration().locale;
462        mLayoutDirection = LocaleUtil.getLayoutDirectionFromLocale(locale);
463    }
464
465    @Override
466    public void onConfigurationChanged(Configuration configuration) {
467        super.onConfigurationChanged(configuration);
468        mLayoutDirection = LocaleUtil.getLayoutDirectionFromLocale(configuration.locale);
469    }
470
471    /**
472     * Implement to return the implementation of the internal accessibility
473     * service interface.
474     */
475    @Override
476    public final IBinder onBind(Intent intent) {
477        return new IAccessibilityServiceClientWrapper(this, getMainLooper(), new Callbacks() {
478            @Override
479            public void onServiceConnected() {
480                AccessibilityService.this.onServiceConnected();
481            }
482
483            @Override
484            public void onInterrupt() {
485                AccessibilityService.this.onInterrupt();
486            }
487
488            @Override
489            public void onAccessibilityEvent(AccessibilityEvent event) {
490                AccessibilityService.this.onAccessibilityEvent(event);
491            }
492
493            @Override
494            public void onSetConnectionId( int connectionId) {
495                mConnectionId = connectionId;
496            }
497
498            @Override
499            public void onGesture(int gestureId) {
500                AccessibilityService.this.onGesture(gestureId);
501            }
502        });
503    }
504
505    /**
506     * Implements the internal {@link IAccessibilityServiceClient} interface to convert
507     * incoming calls to it back to calls on an {@link AccessibilityService}.
508     */
509    static class IAccessibilityServiceClientWrapper extends IAccessibilityServiceClient.Stub
510            implements HandlerCaller.Callback {
511
512        static final int NO_ID = -1;
513
514        private static final int DO_SET_SET_CONNECTION = 10;
515        private static final int DO_ON_INTERRUPT = 20;
516        private static final int DO_ON_ACCESSIBILITY_EVENT = 30;
517        private static final int DO_ON_GESTURE = 40;
518
519        private final HandlerCaller mCaller;
520
521        private final Callbacks mCallback;
522
523        public IAccessibilityServiceClientWrapper(Context context, Looper looper,
524                Callbacks callback) {
525            mCallback = callback;
526            mCaller = new HandlerCaller(context, looper, this);
527        }
528
529        public void setConnection(IAccessibilityServiceConnection connection, int connectionId) {
530            Message message = mCaller.obtainMessageIO(DO_SET_SET_CONNECTION, connectionId,
531                    connection);
532            mCaller.sendMessage(message);
533        }
534
535        public void onInterrupt() {
536            Message message = mCaller.obtainMessage(DO_ON_INTERRUPT);
537            mCaller.sendMessage(message);
538        }
539
540        public void onAccessibilityEvent(AccessibilityEvent event) {
541            Message message = mCaller.obtainMessageO(DO_ON_ACCESSIBILITY_EVENT, event);
542            mCaller.sendMessage(message);
543        }
544
545        public void onGesture(int gestureId) {
546            Message message = mCaller.obtainMessageI(DO_ON_GESTURE, gestureId);
547            mCaller.sendMessage(message);
548        }
549
550        public void executeMessage(Message message) {
551            switch (message.what) {
552                case DO_ON_ACCESSIBILITY_EVENT :
553                    AccessibilityEvent event = (AccessibilityEvent) message.obj;
554                    if (event != null) {
555                        AccessibilityInteractionClient.getInstance().onAccessibilityEvent(event);
556                        mCallback.onAccessibilityEvent(event);
557                        event.recycle();
558                    }
559                    return;
560                case DO_ON_INTERRUPT :
561                    mCallback.onInterrupt();
562                    return;
563                case DO_SET_SET_CONNECTION :
564                    final int connectionId = message.arg1;
565                    IAccessibilityServiceConnection connection =
566                        (IAccessibilityServiceConnection) message.obj;
567                    if (connection != null) {
568                        AccessibilityInteractionClient.getInstance().addConnection(connectionId,
569                                connection);
570                        mCallback.onSetConnectionId(connectionId);
571                        mCallback.onServiceConnected();
572                    } else {
573                        AccessibilityInteractionClient.getInstance().removeConnection(connectionId);
574                        mCallback.onSetConnectionId(AccessibilityInteractionClient.NO_ID);
575                    }
576                    return;
577                case DO_ON_GESTURE :
578                    final int gestureId = message.arg1;
579                    mCallback.onGesture(gestureId);
580                    return;
581                default :
582                    Log.w(LOG_TAG, "Unknown message type " + message.what);
583            }
584        }
585    }
586}
587