services.jd revision 8982939d17881c7dcd20459955f3bfcec6e05905
1page.title=Building Accessibility Services
2parent.title=Accessibility
3parent.link=index.html
4@jd:body
5
6<div id="qv-wrapper">
7<div id="qv">
8
9  <h2>Topics</h2>
10  <ol>
11    <li><a href="#manifest">Manifest Declarations and Permissions</a>
12      <ol>
13        <li><a href="#service-declaration">Accessibility service declaration</a></li>
14        <li><a href="#service-config">Accessibility service configuration</a></li>
15      </ol>
16    </li>
17    <li><a href="#register">Registering for Accessibility Events</a></li>
18    <li><a href="#methods">AccessibilityService Methods</a></li>
19    <li><a href="#event-details">Getting Event Details</a></li>
20    <li><a href="#act-for-users">Taking Action for Users</a>
21      <ol>
22        <li><a href="#detect-gestures">Listening for gestures</a></li>
23        <li><a href="#using-actions">Using accessibility actions</a></li>
24        <li><a href="#focus-types">Using focus types</a></li>
25      </ol>
26    </li>
27    <li><a href="#examples">Example Code</a></li>
28  </ol>
29
30  <h2>Key classes</h2>
31  <ol>
32    <li>{@link android.accessibilityservice.AccessibilityService}</li>
33    <li>{@link android.accessibilityservice.AccessibilityServiceInfo}</li>
34    <li>{@link android.view.accessibility.AccessibilityEvent}</li>
35    <li>{@link android.view.accessibility.AccessibilityRecord}</li>
36    <li>{@link android.view.accessibility.AccessibilityNodeInfo}</li>
37  </ol>
38
39  <h2>See also</h2>
40  <ol>
41    <li><a href="{@docRoot}training/accessibility/index.html">Training: Implementing Accessibility</a></li>
42  </ol>
43
44</div>
45</div>
46
47<p>An accessibility service is an application that provides user interface enhancements to
48assist users with disabilities, or who may temporarily be unable to fully interact with a device.
49For example, users who are driving, taking care of a young child or attending a very loud party
50might need additional or alternative interface feedback.</p>
51
52<p>Android provides standard accessibility services, including TalkBack, and developers can
53create and distribute their own services. This document explains the basics of building an
54accessibility service.</p>
55
56<p>The ability for you to build and deploy accessibility services was introduced with Android 1.6
57  (API Level 4) and received significant improvements with Android 4.0 (API Level 14). The Android
58  <a href="{@docRoot}tools/extras/support-library.html">Support Library</a> was also updated with
59  the release of Android 4.0 to provide support for these enhanced accessibility features back to
60  Android 1.6. Developers aiming for widely compatible accessibility services are encouraged to use
61  the Support Library and develop for the more advanced accessibility features introduced in
62  Android 4.0.</p>
63
64
65<h2 id="manifest">Manifest Declarations and Permissions</h2>
66
67<p>Applications that provide accessibility services must include specific declarations in their
68 application manifests to be treated as an accessibility service by the Android system. This
69 section explains the required and optional settings for accessibility services.</p>
70
71
72<h3 id="service-declaration">Accessibility service declaration</h3>
73
74<p>In order to be treated as an accessibility service, your application must include the
75{@code service} element (rather than the {@code activity} element) within the {@code application}
76element in its manifest. In addition, within the {@code service} element, you must also include an
77accessibility service intent filter. For compatiblity with Android 4.1 and higher, the manifest
78must also request the {@link android.Manifest.permission#BIND_ACCESSIBILITY_SERVICE} permission
79as shown in the following sample:</p>
80
81<pre>
82&lt;application&gt;
83  &lt;service android:name=&quot;.MyAccessibilityService&quot;
84      android:label=&quot;@string/accessibility_service_label&quot;&gt;
85    &lt;intent-filter&gt;
86      &lt;action android:name=&quot;android.accessibilityservice.AccessibilityService&quot; /&gt;
87    &lt;/intent-filter&gt;
88  &lt;/service&gt;
89  &lt;uses-permission android:name="android.permission.BIND_ACCESSIBILITY_SERVICE" /&gt;
90&lt;/application&gt;
91</pre>
92
93<p>These declarations are required for all accessibility services deployed on Android 1.6 (API Level
94 4) or higher.</p>
95
96
97<h3 id="service-config">Accessibility service configuration</h3>
98
99<p>Accessibility services must also provide a configuration which specifies the types of
100accessibility events that the service handles and additional information about the service. The
101configuration of an accessibility service is contained in the {@link
102android.accessibilityservice.AccessibilityServiceInfo} class. Your service can build and set a
103configuration using an instance of this class and {@link
104android.accessibilityservice.AccessibilityService#setServiceInfo setServiceInfo()} at runtime.
105However, not all configuration options are available using this method.</p>
106
107<p>Beginning with Android 4.0, you can include a {@code &lt;meta-data&gt;} element in your manifest
108with a reference to a configuration file, which allows you to set the full range of options for
109your accessibility service, as shown in the following example:</p>
110
111<pre>
112&lt;service android:name=&quot;.MyAccessibilityService&quot;&gt;
113  ...
114  &lt;meta-data
115    android:name=&quot;android.accessibilityservice&quot;
116    android:resource=&quot;@xml/accessibility_service_config&quot; /&gt;
117&lt;/service&gt;
118</pre>
119
120<p>This meta-data element refers to an XML file that you create in your application’s resource
121directory ({@code &lt;project_dir&gt;/res/xml/accessibility_service_config.xml}). The following code
122shows example contents for the service configuration file:</p>
123
124<pre>
125&lt;accessibility-service xmlns:android=&quot;http://schemas.android.com/apk/res/android";
126    android:description=&quot;@string/accessibility_service_description&quot;
127    android:packageNames=&quot;com.example.android.apis&quot;
128    android:accessibilityEventTypes=&quot;typeAllMask&quot;
129    android:accessibilityFlags=&quot;flagDefault&quot;
130    android:accessibilityFeedbackType=&quot;feedbackSpoken&quot;
131    android:notificationTimeout=&quot;100&quot;
132    android:canRetrieveWindowContent=&quot;true&quot;
133    android:settingsActivity=&quot;com.example.android.accessibility.ServiceSettingsActivity&quot;
134/&gt;
135</pre>
136
137<p>For more information about the XML attributes which can be used in the accessibility service
138 configuration file, follow these links to the reference documentation:</p>
139
140<ul>
141  <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_description">{@code android:description}</a></li>
142  <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_packageNames">{@code android:packageNames}</a></li>
143  <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_accessibilityEventTypes">{@code android:accessibilityEventTypes}</a></li>
144  <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_accessibilityFlags">{@code android:accessibilityFlags}</a></li>
145  <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_accessibilityFeedbackType">{@code android:accessibilityFeedbackType}</a></li>
146  <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_notificationTimeout">{@code android:notificationTimeout}</a></li>
147  <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_canRetrieveWindowContent">{@code android:canRetrieveWindowContent}</a></li>
148  <li><a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_settingsActivity">{@code android:settingsActivity}</a></li>
149</ul>
150
151<p>For more information about which configuration settings can be dynamically set at runtime, see
152the {@link android.accessibilityservice.AccessibilityServiceInfo} reference documentation.</p>
153
154
155<h2 id="register">Registering for Accessibility Events</h2>
156
157<p>One of the most important functions of the accessibility service configuration parameters is to
158allow you to specify what types of accessibility events your service can handle. Being able to
159specify this information enables accessibility services to cooperate with each other, and allows you
160as a developer the flexibility to handle only specific events types from specific applications. The
161event filtering can include the following criteria:</p>
162
163<ul>
164  <li><strong>Package Names</strong> - Specify the package names of applications whose accessibility
165events you want your service to handle. If this parameter is omitted, your accessibility service is
166considered available to service accessibility events for any application. This parameter can be set
167in the accessibility service configuration files with the {@code android:packageNames} attribute as
168a comma-separated list, or set using the {@link
169android.accessibilityservice.AccessibilityServiceInfo#packageNames
170AccessibilityServiceInfo.packageNames} member.</li>
171  <li><strong>Event Types</strong> - Specify the types of accessibility events you want your service
172to handle. This parameter can be set in the accessibility service configuration files with the
173{@code android:accessibilityEventTypes} attribute as a list separated by the {@code |} character
174(for example {@code accessibilityEventTypes="typeViewClicked|typeViewFocused"}), or set using the
175{@link android.accessibilityservice.AccessibilityServiceInfo#eventTypes
176AccessibilityServiceInfo.eventTypes} member. </li>
177</ul>
178
179<p>When setting up your accessibility service, carefully consider what events your service is able
180to handle and only register for those events. Since users can activate more than one accessibility
181services at a time, your service must not consume events that it is not able to handle. Remember
182that other services may handle those events in order to improve a user's experience.</p>
183
184<p class="note"><strong>Note:</strong> The Android framework dispatches accessibility events to
185more than one accessibility service if the services provide different
186<a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_accessibilityFeedbackType">
187feedback types</a>. However, if two or more services provide the same feedback type, then only the
188first registered service receives the event.</p>
189
190
191<h2 id="methods">AccessibilityService Methods</h2>
192
193<p>An accessibility service must extend the {@link
194android.accessibilityservice.AccessibilityService} class and override the following methods from
195that class. These methods are presented in the order in which they are called by the Android system,
196from when the service is started
197({@link android.accessibilityservice.AccessibilityService#onServiceConnected onServiceConnected()}),
198while it is running ({@link android.accessibilityservice.AccessibilityService#onAccessibilityEvent
199onAccessibilityEvent()},
200{@link android.accessibilityservice.AccessibilityService#onInterrupt onInterrupt()}) to when it is
201shut down ({@link android.accessibilityservice.AccessibilityService#onUnbind onUnbind()}).</p>
202
203<ul>
204  <li>{@link android.accessibilityservice.AccessibilityService#onServiceConnected
205onServiceConnected()} - (optional) This system calls this method when it successfully connects to
206your accessibility service. Use this method to do any one-time setup steps for your service,
207including connecting to user feedback system services, such as the audio manager or device vibrator.
208If you want to set the configuration of your service at runtime or make one-time adjustments, this
209is a convenient location from which to call {@link
210android.accessibilityservice.AccessibilityService#setServiceInfo setServiceInfo()}.</li>
211
212  <li>{@link android.accessibilityservice.AccessibilityService#onAccessibilityEvent
213onAccessibilityEvent()} - (required) This method is called back by the system when it detects an
214{@link android.view.accessibility.AccessibilityEvent} that matches the event filtering parameters
215specified by your accessibility service. For example, when the user clicks a button or focuses on a
216user interface control in an application for which your accessibility service is providing feedback.
217When this happens, the system calls this method, passing the associated {@link
218android.view.accessibility.AccessibilityEvent}, which the service can then interpret and use to
219provide feedback to the user. This method may be called many times over the lifecycle of your
220service.</li>
221
222  <li>{@link android.accessibilityservice.AccessibilityService#onInterrupt onInterrupt()} -
223(required) This method is called when the system wants to interrupt the feedback your service is
224providing, usually in response to a user action such as moving focus to a different control. This
225method may be called many times over the lifecycle of your service.</li>
226
227  <li>{@link android.accessibilityservice.AccessibilityService#onUnbind onUnbind()} - (optional)
228This method is called when the system is about to shutdown the accessibility service. Use this
229method to do any one-time shutdown procedures, including de-allocating user feedback system
230services, such as the audio manager or device vibrator.</li>
231</ul>
232
233<p>These callback methods provide the basic structure for your accessibility service. It is up to
234you to decide on how to process data provided by the Android system in the form of {@link
235android.view.accessibility.AccessibilityEvent} objects and provide feedback to the user. For more
236information about getting information from an accessibility event, see the
237<a href="{@docRoot}training/accessibility/service.html">Implementing Accessibility</a> training.</p>
238
239
240<h2 id="event-details">Getting Event Details</h2>
241
242<p>The Android system provides information to accessibility services about the user interface
243interaction through {@link android.view.accessibility.AccessibilityEvent} objects. Prior to Android
2444.0, the information available in an accessibility event, while providing a significant amount of
245detail about a user interface control selected by the user, offered limited contextual
246information. In many cases, this missing context information might be critical to understanding the
247meaning of the selected control.</p>
248
249<p>An example of an interface where context is critical is a calendar or day planner. If the
250user selects a 4:00 PM time slot in a Monday to Friday day list and the accessibility service
251announces “4 PM”, but does not announce the weekday name, the day of the month, or the month name,
252the resulting feedback is confusing. In this case, the context of a user interface control is
253critical to a user who wants to schedule a meeting.</p>
254
255<p>Android 4.0 significantly extends the amount of information that an accessibility service can
256obtain about an user interface interaction by composing accessibility events based on the view
257hierarchy. A view hierarchy is the set of user interface components that contain the component (its
258parents) and the user interface elements that may be contained by that component (its children). In
259this way, the Android system can provide much richer detail about accessibility events, allowing
260accessibility services to provide more useful feedback to users.</p>
261
262<p>An accessibility service gets information about an user interface event through an {@link
263android.view.accessibility.AccessibilityEvent} passed by the system to the service’s
264{@link android.accessibilityservice.AccessibilityService#onAccessibilityEvent
265onAccessibilityEvent()} callback method. This object provides details about the event, including the
266type of object being acted upon, its descriptive text and other details. Starting in Android 4.0
267(and supported in previous releases through the {@link
268android.support.v4.view.accessibility.AccessibilityEventCompat} object in the Support Library), you
269can obtain additional information about the event using these calls:</p>
270
271<ul>
272  <li>{@link android.view.accessibility.AccessibilityEvent#getRecordCount
273AccessibilityEvent.getRecordCount()} and {@link
274android.view.accessibility.AccessibilityEvent#getRecord getRecord(int)} - These methods allow you to
275retrieve the set of {@link android.view.accessibility.AccessibilityRecord} objects which contributed
276to the {@link android.view.accessibility.AccessibilityEvent} passed to you by the system. This level
277of detail provides more context for the event that triggered your accessibility service.</li>
278
279  <li>{@link android.view.accessibility.AccessibilityEvent#getSource
280AccessibilityEvent.getSource()} - This method returns an {@link
281android.view.accessibility.AccessibilityNodeInfo} object. This object allows you to request view
282layout hierarchy (parents and children) of the component that originated the accessibility event.
283This feature allows an accessibility service to investigate the full context of an event, including
284the content and state of any enclosing views or child views.
285
286<p class="caution"><strong>Important:</strong> The ability to investigate the view
287hierarchy from an {@link android.view.accessibility.AccessibilityEvent} potentially exposes private
288user information to your accessibility service. For this reason, your service must request this
289level of access through the accessibility <a href="#service-config">service configuration XML</a>
290file, by including the {@code canRetrieveWindowContent} attribute and setting it to {@code true}. If
291you do not include this setting in your service configuration xml file, calls to {@link
292android.view.accessibility.AccessibilityEvent#getSource getSource()} fail.</p>
293
294<p class="note"><strong>Note:</strong> In Android 4.1 (API Level 16) and higher, the
295{@link android.view.accessibility.AccessibilityEvent#getSource getSource()} method,
296as well as {@link android.view.accessibility.AccessibilityNodeInfo#getChild
297AccessibilityNodeInfo.getChild()} and
298{@link android.view.accessibility.AccessibilityNodeInfo#getParent getParent()}, return only
299view objects that are considered important for accessibility (views that draw content or respond to
300user actions). If your service requires all views, it can request them by setting the
301{@link android.accessibilityservice.AccessibilityServiceInfo#flags flags} member of the service's
302{@link android.accessibilityservice.AccessibilityServiceInfo} instance to
303{@link android.accessibilityservice.AccessibilityServiceInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS}.</p>
304  </li>
305</ul>
306
307
308<h2 id="act-for-users">Taking Action for Users</h2>
309
310<p>Starting with Android 4.0 (API Level 14), accessibility services can act on behalf
311  of users, including changing the input focus and selecting (activating) user interface elements.
312  In Android 4.1 (API Level 16) the range of actions has been expanded to include scrolling lists
313  and interacting with text fields. Accessibility services can
314  also take global actions, such as navigating to the Home screen, pressing the Back button, opening
315  the notifications screen and recent applications list. Android 4.1 also includes a new type of
316  focus, <em>Accessibilty Focus</em>, which makes all visible elements selectable by an
317  accessibility service.</p>
318
319<p>These new capabilities make it possible for developers of accessibility services to create
320  alternative navigation modes such as
321  <a href="{@docRoot}tools/testing/testing_accessibility.html#test-gestures">gesture navigation</a>,
322  and give users with disabilities improved control of their Android devices.</p>
323
324
325<h3 id="detect-gestures">Listening for gestures</h3>
326
327<p>Accessibility services can listen for specific gestures and respond by taking action on behalf
328  of a user. This feature, added in Android 4.1 (API Level 16), and requires that your
329  accessibility service request activation of the Explore by Touch feature. Your service can
330  request this activation by setting the
331  {@link android.accessibilityservice.AccessibilityServiceInfo#flags flags} member of the service’s
332  {@link android.accessibilityservice.AccessibilityServiceInfo} instance to
333  {@link android.accessibilityservice.AccessibilityServiceInfo#FLAG_REQUEST_TOUCH_EXPLORATION_MODE},
334  as shown in the following example.
335  </p>
336
337<pre>
338public class MyAccessibilityService extends AccessibilityService {
339    &#64;Override
340    public void onCreate() {
341        getServiceInfo().flags = AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE;
342    }
343    ...
344}
345</pre>
346
347<p>Once your service has requested activation of Explore by Touch, the user must allow the
348  feature to be turned on, if it is not already active. When this feature is active, your service
349  receives notification of accessibility gestures through your service's
350  {@link android.accessibilityservice.AccessibilityService#onGesture onGesture()} callback method
351  and can respond by taking actions for the user.</p>
352
353
354<h3 id="using-actions">Using accessibility actions</h3>
355
356<p>Accessibility services can take action on behalf of users to make interacting with applications
357  simpler and more productive. The ability of accessibility services to perform actions was added
358  in Android 4.0 (API Level 14) and significantly expanded with Android 4.1 (API Level 16).</p>
359
360<p>In order to take actions on behalf of users, your accessibility service must
361  <a href="#register">register</a> to receive events from a few or many applications and request
362  permission to view the content of applications by setting the
363  <a href="{@docRoot}reference/android/R.styleable.html#AccessibilityService_canRetrieveWindowContent">
364  {@code android:canRetrieveWindowContent}</a> to {@code true} in the
365  <a href="#service-config">service configuration file</a>. When events are received by your
366  service, it can then retrieve the
367  {@link android.view.accessibility.AccessibilityNodeInfo} object from the event using
368  {@link android.view.accessibility.AccessibilityEvent#getSource getSource()}.
369  With the {@link android.view.accessibility.AccessibilityNodeInfo} object, your service can then
370  explore the view hierarchy to determine what action to take and then act for the user using
371  {@link android.view.accessibility.AccessibilityNodeInfo#performAction performAction()}.</p>
372
373<pre>
374public class MyAccessibilityService extends AccessibilityService {
375
376    &#64;Override
377    public void onAccessibilityEvent(AccessibilityEvent event) {
378        // get the source node of the event
379        AccessibilityNodeInfo nodeInfo = event.getSource();
380
381        // Use the event and node information to determine
382        // what action to take
383
384        // take action on behalf of the user
385        nodeInfo.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
386
387        // recycle the nodeInfo object
388        nodeInfo.recycle();
389    }
390    ...
391}
392</pre>
393
394<p>The {@link android.view.accessibility.AccessibilityNodeInfo#performAction performAction()} method
395  allows your service to take action within an application. If your service needs to perform a
396  global action such as navigating to the Home screen, pressing the Back button, opening the
397  notifications screen or recent applications list, then use the
398  {@link android.accessibilityservice.AccessibilityService#performGlobalAction performGlobalAction()}
399  method.</p>
400
401
402<h3 id="focus-types">Using focus types</h3>
403
404<p>Android 4.1 (API Level 16) introduces a new type of user interface focus called <em>Accessibility
405  Focus</em>. This type of focus can be used by accessibility services to select any visible user
406  interface element and act on it. This focus type is different from the more well known <em>Input
407  Focus</em>, which determines what on-screen user interface element receives input when a user
408  types characters, presses <strong>Enter</strong> on a keyboard or pushes the center button of a
409  D-pad control.</p>
410
411<p>Accessibility Focus is completely separate and independent from Input Focus. In fact, it is
412  possible for one element in a user interface to have Input Focus while another element has
413  Accessibility Focus. The purpose of Accessibility Focus is to provide accessibility services with
414  a method of interacting with any visible element on a screen, regardless of whether or not the
415  element is input-focusable from a system perspective. You can see accessibility focus in action by
416  testing accessibility gestures. For more information about testing this feature, see
417  <a href="{@docRoot}tools/testing/testing_accessibility.html#test-gestures">Testing gesture
418  navigation</a>.</p>
419
420<p class="note">
421  <strong>Note:</strong> Accessibility services that use Accessibility Focus are responsible for
422  synchronizing the current Input Focus when an element is capable of this type of focus. Services
423  that do not synchronize Input Focus with Accessibility Focus run the risk of causing problems in
424  applications that expect input focus to be in a specific location when certain actions are taken.
425  </p>
426
427<p>An accessibility service can determine what user interface element has Input Focus or
428  Accessibility Focus using the {@link android.view.accessibility.AccessibilityNodeInfo#findFocus
429  AccessibilityNodeInfo.findFocus()} method. You can also search for elements that can be selected
430  with Input Focus using the
431  {@link android.view.accessibility.AccessibilityNodeInfo#focusSearch focusSearch()} method.
432  Finally, your accessibility service can set Accessibility Focus using the
433  {@link android.view.accessibility.AccessibilityNodeInfo#performAction
434  performAction(AccessibilityNodeInfo.ACTION_SET_ACCESSIBILITY_FOCUS)} method.</p>
435
436
437<h2 id="examples">Example Code</h2>
438
439<p>The API Demo project contains two samples which can be used as a starting point for generating
440accessibility services
441({@code &lt;sdk&gt;/samples/&lt;platform&gt;/ApiDemos/src/com/example/android/apis/accessibility}):
442</p>
443
444<ul>
445  <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/accessibility/ClockBackService.html">ClockBackService</a>
446 - This service is based on the original implementation of {@link
447android.accessibilityservice.AccessibilityService} and can be used as a base for developing basic
448accessibility services that are compatible with Android 1.6 (API Level 4) and higher.</li>
449  <li><a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/accessibility/TaskBackService.html">TaskBackService</a>
450 - This service is based on the enhanced accessibility APIs introduced in Android 4.0 (API Level
45114). However, you can use the Android <a href="{@docRoot}tools/extras/support-library.html">Support
452Libary</a> to substitute classes introduced in later API levels (e.g.,
453{@link android.view.accessibility.AccessibilityRecord},
454{@link android.view.accessibility.AccessibilityNodeInfo}
455) with equivalent support package classes (e.g.,
456{@link android.support.v4.view.accessibility.AccessibilityRecordCompat},
457{@link android.support.v4.view.accessibility.AccessibilityNodeInfoCompat}
458) to make this example work with API versions back to Android 1.6 (API Level 4).</li>
459</ul>
460