2 ** Copyright 2009, The Android Open Source Project
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
8 ** http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server.accessibility;
19 import static android.accessibilityservice.AccessibilityServiceInfo.DEFAULT;
21 import android.Manifest;
22 import android.accessibilityservice.AccessibilityService;
23 import android.accessibilityservice.AccessibilityServiceInfo;
24 import android.accessibilityservice.IAccessibilityServiceClient;
25 import android.accessibilityservice.IAccessibilityServiceConnection;
26 import android.app.AlertDialog;
27 import android.app.PendingIntent;
28 import android.app.StatusBarManager;
29 import android.content.BroadcastReceiver;
30 import android.content.ComponentName;
31 import android.content.ContentResolver;
32 import android.content.Context;
33 import android.content.DialogInterface;
34 import android.content.DialogInterface.OnClickListener;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.ServiceConnection;
38 import android.content.pm.PackageManager;
39 import android.content.pm.ResolveInfo;
40 import android.content.pm.ServiceInfo;
41 import android.database.ContentObserver;
42 import android.graphics.Point;
43 import android.graphics.Rect;
44 import android.hardware.display.DisplayManager;
45 import android.hardware.input.InputManager;
46 import android.net.Uri;
47 import android.os.Binder;
48 import android.os.Build;
49 import android.os.Bundle;
50 import android.os.Handler;
51 import android.os.IBinder;
52 import android.os.Looper;
53 import android.os.Message;
54 import android.os.Process;
55 import android.os.RemoteCallbackList;
56 import android.os.RemoteException;
57 import android.os.ServiceManager;
58 import android.os.SystemClock;
59 import android.os.UserHandle;
60 import android.os.UserManager;
61 import android.provider.Settings;
62 import android.text.TextUtils;
63 import android.text.TextUtils.SimpleStringSplitter;
64 import android.util.Slog;
65 import android.util.SparseArray;
66 import android.view.Display;
67 import android.view.IWindow;
68 import android.view.IWindowManager;
69 import android.view.InputDevice;
70 import android.view.KeyCharacterMap;
71 import android.view.KeyEvent;
72 import android.view.MagnificationSpec;
73 import android.view.WindowManager;
74 import android.view.accessibility.AccessibilityEvent;
75 import android.view.accessibility.AccessibilityInteractionClient;
76 import android.view.accessibility.AccessibilityManager;
77 import android.view.accessibility.AccessibilityNodeInfo;
78 import android.view.accessibility.IAccessibilityInteractionConnection;
79 import android.view.accessibility.IAccessibilityInteractionConnectionCallback;
80 import android.view.accessibility.IAccessibilityManager;
81 import android.view.accessibility.IAccessibilityManagerClient;
83 import com.android.internal.R;
84 import com.android.internal.content.PackageMonitor;
85 import com.android.internal.statusbar.IStatusBarService;
87 import org.xmlpull.v1.XmlPullParserException;
89 import java.io.FileDescriptor;
90 import java.io.IOException;
91 import java.io.PrintWriter;
92 import java.util.ArrayList;
93 import java.util.Arrays;
94 import java.util.HashMap;
95 import java.util.HashSet;
96 import java.util.Iterator;
97 import java.util.List;
100 import java.util.concurrent.CopyOnWriteArrayList;
103 * This class is instantiated by the system as a system level service and can be
104 * accessed only by the system. The task of this service is to be a centralized
105 * event dispatch for {@link AccessibilityEvent}s generated across all processes
106 * on the device. Events are dispatched to {@link AccessibilityService}s.
110 public class AccessibilityManagerService extends IAccessibilityManager.Stub {
112 private static final boolean DEBUG = false;
114 private static final String LOG_TAG = "AccessibilityManagerService";
116 // TODO: This is arbitrary. When there is time implement this by watching
117 // when that accessibility services are bound.
118 private static final int WAIT_FOR_USER_STATE_FULLY_INITIALIZED_MILLIS = 3000;
120 private static final String FUNCTION_REGISTER_UI_TEST_AUTOMATION_SERVICE =
121 "registerUiTestAutomationService";
123 private static final String TEMPORARY_ENABLE_ACCESSIBILITY_UNTIL_KEYGUARD_REMOVED =
124 "temporaryEnableAccessibilityStateUntilKeyguardRemoved";
126 private static final ComponentName sFakeAccessibilityServiceComponentName =
127 new ComponentName("foo.bar", "FakeService");
129 private static final String FUNCTION_DUMP = "dump";
131 private static final char COMPONENT_NAME_SEPARATOR = ':';
133 private static final int OWN_PROCESS_ID = android.os.Process.myPid();
135 private static int sIdCounter = 0;
137 private static int sNextWindowId;
139 private final Context mContext;
141 private final Object mLock = new Object();
143 private final SimpleStringSplitter mStringColonSplitter =
144 new SimpleStringSplitter(COMPONENT_NAME_SEPARATOR);
146 private final List<AccessibilityServiceInfo> mEnabledServicesForFeedbackTempList =
147 new ArrayList<AccessibilityServiceInfo>();
149 private final Rect mTempRect = new Rect();
151 private final Point mTempPoint = new Point();
153 private final Display mDefaultDisplay;
155 private final PackageManager mPackageManager;
157 private final IWindowManager mWindowManagerService;
159 private final SecurityPolicy mSecurityPolicy;
161 private final MainHandler mMainHandler;
163 private Service mQueryBridge;
165 private AlertDialog mEnableTouchExplorationDialog;
167 private AccessibilityInputFilter mInputFilter;
169 private boolean mHasInputFilter;
171 private final Set<ComponentName> mTempComponentNameSet = new HashSet<ComponentName>();
173 private final List<AccessibilityServiceInfo> mTempAccessibilityServiceInfoList =
174 new ArrayList<AccessibilityServiceInfo>();
176 private final RemoteCallbackList<IAccessibilityManagerClient> mGlobalClients =
177 new RemoteCallbackList<IAccessibilityManagerClient>();
179 private final SparseArray<AccessibilityConnectionWrapper> mGlobalInteractionConnections =
180 new SparseArray<AccessibilityConnectionWrapper>();
182 private final SparseArray<IBinder> mGlobalWindowTokens = new SparseArray<IBinder>();
184 private final SparseArray<UserState> mUserStates = new SparseArray<UserState>();
186 private int mCurrentUserId = UserHandle.USER_OWNER;
188 private UserState getCurrentUserStateLocked() {
189 return getUserStateLocked(mCurrentUserId);
192 private UserState getUserStateLocked(int userId) {
193 UserState state = mUserStates.get(userId);
195 state = new UserState(userId);
196 mUserStates.put(userId, state);
202 * Creates a new instance.
204 * @param context A {@link Context} instance.
206 public AccessibilityManagerService(Context context) {
208 mPackageManager = mContext.getPackageManager();
209 mWindowManagerService = (IWindowManager) ServiceManager.getService(Context.WINDOW_SERVICE);
210 mSecurityPolicy = new SecurityPolicy();
211 mMainHandler = new MainHandler(mContext.getMainLooper());
212 //TODO: (multi-display) We need to support multiple displays.
213 DisplayManager displayManager = (DisplayManager)
214 mContext.getSystemService(Context.DISPLAY_SERVICE);
215 mDefaultDisplay = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
216 registerBroadcastReceivers();
217 new AccessibilityContentObserver(mMainHandler).register(
218 context.getContentResolver());
221 private void registerBroadcastReceivers() {
222 PackageMonitor monitor = new PackageMonitor() {
224 public void onSomePackagesChanged() {
225 synchronized (mLock) {
226 if (getChangingUserId() != mCurrentUserId) {
229 // We will update when the automation service dies.
230 UserState userState = getCurrentUserStateLocked();
231 if (userState.mUiAutomationService == null) {
232 if (readConfigurationForUserStateLocked(userState)) {
233 onUserStateChangedLocked(userState);
240 public void onPackageRemoved(String packageName, int uid) {
241 synchronized (mLock) {
242 final int userId = getChangingUserId();
243 if (userId != mCurrentUserId) {
246 UserState userState = getUserStateLocked(userId);
247 Iterator<ComponentName> it = userState.mEnabledServices.iterator();
248 while (it.hasNext()) {
249 ComponentName comp = it.next();
250 String compPkg = comp.getPackageName();
251 if (compPkg.equals(packageName)) {
253 // Update the enabled services setting.
254 persistComponentNamesToSettingLocked(
255 Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
256 userState.mEnabledServices, userId);
257 // Update the touch exploration granted services setting.
258 userState.mTouchExplorationGrantedServices.remove(comp);
259 persistComponentNamesToSettingLocked(
261 TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES,
262 userState.mTouchExplorationGrantedServices, userId);
263 // We will update when the automation service dies.
264 if (userState.mUiAutomationService == null) {
265 onUserStateChangedLocked(userState);
274 public boolean onHandleForceStop(Intent intent, String[] packages,
275 int uid, boolean doit) {
276 synchronized (mLock) {
277 final int userId = getChangingUserId();
278 if (userId != mCurrentUserId) {
281 UserState userState = getUserStateLocked(userId);
282 Iterator<ComponentName> it = userState.mEnabledServices.iterator();
283 while (it.hasNext()) {
284 ComponentName comp = it.next();
285 String compPkg = comp.getPackageName();
286 for (String pkg : packages) {
287 if (compPkg.equals(pkg)) {
292 persistComponentNamesToSettingLocked(
293 Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
294 userState.mEnabledServices, userId);
295 // We will update when the automation service dies.
296 if (userState.mUiAutomationService == null) {
297 onUserStateChangedLocked(userState);
308 monitor.register(mContext, null, UserHandle.ALL, true);
310 // user change and unlock
311 IntentFilter intentFilter = new IntentFilter();
312 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
313 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
314 intentFilter.addAction(Intent.ACTION_USER_PRESENT);
316 mContext.registerReceiverAsUser(new BroadcastReceiver() {
318 public void onReceive(Context context, Intent intent) {
319 String action = intent.getAction();
320 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
321 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
322 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
323 removeUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
324 } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
325 // We will update when the automation service dies.
326 UserState userState = getCurrentUserStateLocked();
327 if (userState.mUiAutomationService == null) {
328 if (readConfigurationForUserStateLocked(userState)) {
329 onUserStateChangedLocked(userState);
334 }, UserHandle.ALL, intentFilter, null, null);
337 public int addClient(IAccessibilityManagerClient client, int userId) {
338 synchronized (mLock) {
339 final int resolvedUserId = mSecurityPolicy
340 .resolveCallingUserIdEnforcingPermissionsLocked(userId);
341 // If the client is from a process that runs across users such as
342 // the system UI or the system we add it to the global state that
343 // is shared across users.
344 UserState userState = getUserStateLocked(resolvedUserId);
345 if (mSecurityPolicy.isCallerInteractingAcrossUsers(userId)) {
346 mGlobalClients.register(client);
348 Slog.i(LOG_TAG, "Added global client for pid:" + Binder.getCallingPid());
350 return userState.getClientState();
352 userState.mClients.register(client);
353 // If this client is not for the current user we do not
354 // return a state since it is not for the foreground user.
355 // We will send the state to the client on a user switch.
357 Slog.i(LOG_TAG, "Added user client for pid:" + Binder.getCallingPid()
358 + " and userId:" + mCurrentUserId);
360 return (resolvedUserId == mCurrentUserId) ? userState.getClientState() : 0;
365 public boolean sendAccessibilityEvent(AccessibilityEvent event, int userId) {
366 synchronized (mLock) {
367 final int resolvedUserId = mSecurityPolicy
368 .resolveCallingUserIdEnforcingPermissionsLocked(userId);
369 // This method does nothing for a background user.
370 if (resolvedUserId != mCurrentUserId) {
371 return true; // yes, recycle the event
373 if (mSecurityPolicy.canDispatchAccessibilityEvent(event)) {
374 mSecurityPolicy.updateEventSourceLocked(event);
375 mMainHandler.obtainMessage(MainHandler.MSG_UPDATE_ACTIVE_WINDOW,
376 event.getWindowId(), event.getEventType()).sendToTarget();
377 notifyAccessibilityServicesDelayedLocked(event, false);
378 notifyAccessibilityServicesDelayedLocked(event, true);
380 if (mHasInputFilter && mInputFilter != null) {
381 mMainHandler.obtainMessage(MainHandler.MSG_SEND_ACCESSIBILITY_EVENT_TO_INPUT_FILTER,
382 AccessibilityEvent.obtain(event)).sendToTarget();
385 getUserStateLocked(resolvedUserId).mHandledFeedbackTypes = 0;
387 return (OWN_PROCESS_ID != Binder.getCallingPid());
390 public List<AccessibilityServiceInfo> getInstalledAccessibilityServiceList(int userId) {
391 synchronized (mLock) {
392 final int resolvedUserId = mSecurityPolicy
393 .resolveCallingUserIdEnforcingPermissionsLocked(userId);
394 return getUserStateLocked(resolvedUserId).mInstalledServices;
398 public List<AccessibilityServiceInfo> getEnabledAccessibilityServiceList(int feedbackType,
400 List<AccessibilityServiceInfo> result = null;
401 synchronized (mLock) {
402 final int resolvedUserId = mSecurityPolicy
403 .resolveCallingUserIdEnforcingPermissionsLocked(userId);
404 result = mEnabledServicesForFeedbackTempList;
406 List<Service> services = getUserStateLocked(resolvedUserId).mBoundServices;
407 while (feedbackType != 0) {
408 final int feedbackTypeBit = (1 << Integer.numberOfTrailingZeros(feedbackType));
409 feedbackType &= ~feedbackTypeBit;
410 final int serviceCount = services.size();
411 for (int i = 0; i < serviceCount; i++) {
412 Service service = services.get(i);
413 if ((service.mFeedbackType & feedbackTypeBit) != 0) {
414 result.add(service.mAccessibilityServiceInfo);
422 public void interrupt(int userId) {
423 CopyOnWriteArrayList<Service> services;
424 synchronized (mLock) {
425 final int resolvedUserId = mSecurityPolicy
426 .resolveCallingUserIdEnforcingPermissionsLocked(userId);
427 // This method does nothing for a background user.
428 if (resolvedUserId != mCurrentUserId) {
431 services = getUserStateLocked(resolvedUserId).mBoundServices;
433 for (int i = 0, count = services.size(); i < count; i++) {
434 Service service = services.get(i);
436 service.mServiceInterface.onInterrupt();
437 } catch (RemoteException re) {
438 Slog.e(LOG_TAG, "Error during sending interrupt request to "
439 + service.mService, re);
444 public int addAccessibilityInteractionConnection(IWindow windowToken,
445 IAccessibilityInteractionConnection connection, int userId) throws RemoteException {
446 synchronized (mLock) {
447 final int resolvedUserId = mSecurityPolicy
448 .resolveCallingUserIdEnforcingPermissionsLocked(userId);
449 final int windowId = sNextWindowId++;
450 // If the window is from a process that runs across users such as
451 // the system UI or the system we add it to the global state that
452 // is shared across users.
453 if (mSecurityPolicy.isCallerInteractingAcrossUsers(userId)) {
454 AccessibilityConnectionWrapper wrapper = new AccessibilityConnectionWrapper(
455 windowId, connection, UserHandle.USER_ALL);
456 wrapper.linkToDeath();
457 mGlobalInteractionConnections.put(windowId, wrapper);
458 mGlobalWindowTokens.put(windowId, windowToken.asBinder());
460 Slog.i(LOG_TAG, "Added global connection for pid:" + Binder.getCallingPid()
461 + " with windowId: " + windowId);
464 AccessibilityConnectionWrapper wrapper = new AccessibilityConnectionWrapper(
465 windowId, connection, resolvedUserId);
466 wrapper.linkToDeath();
467 UserState userState = getUserStateLocked(resolvedUserId);
468 userState.mInteractionConnections.put(windowId, wrapper);
469 userState.mWindowTokens.put(windowId, windowToken.asBinder());
471 Slog.i(LOG_TAG, "Added user connection for pid:" + Binder.getCallingPid()
472 + " with windowId: " + windowId + " and userId:" + mCurrentUserId);
476 Slog.i(LOG_TAG, "Adding interaction connection to windowId: " + windowId);
482 public void removeAccessibilityInteractionConnection(IWindow window) {
483 synchronized (mLock) {
484 mSecurityPolicy.resolveCallingUserIdEnforcingPermissionsLocked(
485 UserHandle.getCallingUserId());
486 IBinder token = window.asBinder();
487 final int removedWindowId = removeAccessibilityInteractionConnectionInternalLocked(
488 token, mGlobalWindowTokens, mGlobalInteractionConnections);
489 if (removedWindowId >= 0) {
491 Slog.i(LOG_TAG, "Removed global connection for pid:" + Binder.getCallingPid()
492 + " with windowId: " + removedWindowId);
496 final int userCount = mUserStates.size();
497 for (int i = 0; i < userCount; i++) {
498 UserState userState = mUserStates.valueAt(i);
499 final int removedWindowIdForUser =
500 removeAccessibilityInteractionConnectionInternalLocked(
501 token, userState.mWindowTokens, userState.mInteractionConnections);
502 if (removedWindowIdForUser >= 0) {
504 Slog.i(LOG_TAG, "Removed user connection for pid:" + Binder.getCallingPid()
505 + " with windowId: " + removedWindowIdForUser + " and userId:"
506 + mUserStates.keyAt(i));
514 private int removeAccessibilityInteractionConnectionInternalLocked(IBinder windowToken,
515 SparseArray<IBinder> windowTokens,
516 SparseArray<AccessibilityConnectionWrapper> interactionConnections) {
517 final int count = windowTokens.size();
518 for (int i = 0; i < count; i++) {
519 if (windowTokens.valueAt(i) == windowToken) {
520 final int windowId = windowTokens.keyAt(i);
521 windowTokens.removeAt(i);
522 AccessibilityConnectionWrapper wrapper = interactionConnections.get(windowId);
523 wrapper.unlinkToDeath();
524 interactionConnections.remove(windowId);
531 public void registerUiTestAutomationService(IBinder owner, IAccessibilityServiceClient serviceClient,
532 AccessibilityServiceInfo accessibilityServiceInfo) {
533 mSecurityPolicy.enforceCallingPermission(Manifest.permission.RETRIEVE_WINDOW_CONTENT,
534 FUNCTION_REGISTER_UI_TEST_AUTOMATION_SERVICE);
536 accessibilityServiceInfo.setComponentName(sFakeAccessibilityServiceComponentName);
538 synchronized (mLock) {
539 UserState userState = getCurrentUserStateLocked();
541 if (userState.mUiAutomationService != null) {
542 throw new IllegalStateException("UiAutomationService " + serviceClient
543 + "already registered!");
547 owner.linkToDeath(userState.mUiAutomationSerivceOnwerDeathRecipient, 0);
548 } catch (RemoteException re) {
549 Slog.e(LOG_TAG, "Couldn't register for the death of a"
550 + " UiTestAutomationService!", re);
554 userState.mUiAutomationServiceOwner = owner;
555 userState.mUiAutomationServiceClient = serviceClient;
557 // Set the temporary state.
558 userState.mIsAccessibilityEnabled = true;
559 userState.mIsTouchExplorationEnabled = false;
560 userState.mIsEnhancedWebAccessibilityEnabled = false;
561 userState.mIsDisplayMagnificationEnabled = false;
562 userState.mInstalledServices.add(accessibilityServiceInfo);
563 userState.mEnabledServices.clear();
564 userState.mEnabledServices.add(sFakeAccessibilityServiceComponentName);
565 userState.mTouchExplorationGrantedServices.add(sFakeAccessibilityServiceComponentName);
567 // Use the new state instead of settings.
568 onUserStateChangedLocked(userState);
572 public void unregisterUiTestAutomationService(IAccessibilityServiceClient serviceClient) {
573 synchronized (mLock) {
574 UserState userState = getCurrentUserStateLocked();
575 // Automation service is not bound, so pretend it died to perform clean up.
576 if (userState.mUiAutomationService != null
577 && serviceClient != null
578 && userState.mUiAutomationService != null
579 && userState.mUiAutomationService.mServiceInterface != null
580 && userState.mUiAutomationService.mServiceInterface.asBinder()
581 == serviceClient.asBinder()) {
582 userState.mUiAutomationService.binderDied();
584 throw new IllegalStateException("UiAutomationService " + serviceClient
585 + " not registered!");
590 public void temporaryEnableAccessibilityStateUntilKeyguardRemoved(
591 ComponentName service, boolean touchExplorationEnabled) {
592 mSecurityPolicy.enforceCallingPermission(
593 Manifest.permission.TEMPORARY_ENABLE_ACCESSIBILITY,
594 TEMPORARY_ENABLE_ACCESSIBILITY_UNTIL_KEYGUARD_REMOVED);
596 if (!mWindowManagerService.isKeyguardLocked()) {
599 } catch (RemoteException re) {
602 synchronized (mLock) {
603 // Set the temporary state.
604 UserState userState = getCurrentUserStateLocked();
606 // This is a nop if UI automation is enabled.
607 if (userState.mUiAutomationService != null) {
611 userState.mIsAccessibilityEnabled = true;
612 userState.mIsTouchExplorationEnabled = touchExplorationEnabled;
613 userState.mIsEnhancedWebAccessibilityEnabled = false;
614 userState.mIsDisplayMagnificationEnabled = false;
615 userState.mEnabledServices.clear();
616 userState.mEnabledServices.add(service);
617 userState.mBindingServices.clear();
618 userState.mTouchExplorationGrantedServices.clear();
619 userState.mTouchExplorationGrantedServices.add(service);
621 // User the current state instead settings.
622 onUserStateChangedLocked(userState);
626 boolean onGesture(int gestureId) {
627 synchronized (mLock) {
628 boolean handled = notifyGestureLocked(gestureId, false);
630 handled = notifyGestureLocked(gestureId, true);
637 * Gets the bounds of the accessibility focus in the active window.
639 * @param outBounds The output to which to write the focus bounds.
640 * @return Whether accessibility focus was found and the bounds are populated.
642 // TODO: (multi-display) Make sure this works for multiple displays.
643 boolean getAccessibilityFocusBoundsInActiveWindow(Rect outBounds) {
644 // Instead of keeping track of accessibility focus events per
645 // window to be able to find the focus in the active window,
646 // we take a stateless approach and look it up. This is fine
647 // since we do this only when the user clicks/long presses.
648 Service service = getQueryBridge();
649 final int connectionId = service.mId;
650 AccessibilityInteractionClient client = AccessibilityInteractionClient.getInstance();
651 client.addConnection(connectionId, service);
653 AccessibilityNodeInfo root = AccessibilityInteractionClient.getInstance()
654 .getRootInActiveWindow(connectionId);
658 AccessibilityNodeInfo focus = root.findFocus(
659 AccessibilityNodeInfo.FOCUS_ACCESSIBILITY);
663 focus.getBoundsInScreen(outBounds);
665 MagnificationSpec spec = service.getCompatibleMagnificationSpec(focus.getWindowId());
666 if (spec != null && !spec.isNop()) {
667 outBounds.offset((int) -spec.offsetX, (int) -spec.offsetY);
668 outBounds.scale(1 / spec.scale);
671 // Clip to the window rectangle.
672 Rect windowBounds = mTempRect;
673 getActiveWindowBounds(windowBounds);
674 outBounds.intersect(windowBounds);
675 // Clip to the screen rectangle.
676 mDefaultDisplay.getRealSize(mTempPoint);
677 outBounds.intersect(0, 0, mTempPoint.x, mTempPoint.y);
681 client.removeConnection(connectionId);
686 * Gets the bounds of the active window.
688 * @param outBounds The output to which to write the bounds.
690 boolean getActiveWindowBounds(Rect outBounds) {
692 synchronized (mLock) {
693 final int windowId = mSecurityPolicy.mActiveWindowId;
694 token = mGlobalWindowTokens.get(windowId);
696 token = getCurrentUserStateLocked().mWindowTokens.get(windowId);
700 mWindowManagerService.getWindowFrame(token, outBounds);
701 if (!outBounds.isEmpty()) {
704 } catch (RemoteException re) {
710 int getActiveWindowId() {
711 return mSecurityPolicy.mActiveWindowId;
714 void onTouchInteractionStart() {
715 mSecurityPolicy.onTouchInteractionStart();
718 void onTouchInteractionEnd() {
719 mSecurityPolicy.onTouchInteractionEnd();
722 void onMagnificationStateChanged() {
723 notifyClearAccessibilityNodeInfoCacheLocked();
726 private void switchUser(int userId) {
727 synchronized (mLock) {
728 // Disconnect from services for the old user.
729 UserState oldUserState = getUserStateLocked(mCurrentUserId);
730 oldUserState.onSwitchToAnotherUser();
732 // Disable the local managers for the old user.
733 if (oldUserState.mClients.getRegisteredCallbackCount() > 0) {
734 mMainHandler.obtainMessage(MainHandler.MSG_SEND_CLEARED_STATE_TO_CLIENTS_FOR_USER,
735 oldUserState.mUserId, 0).sendToTarget();
738 // Announce user changes only if more that one exist.
739 UserManager userManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
740 final boolean announceNewUser = userManager.getUsers().size() > 1;
743 mCurrentUserId = userId;
745 UserState userState = getCurrentUserStateLocked();
746 if (userState.mUiAutomationService != null) {
747 // Switching users disables the UI automation service.
748 userState.mUiAutomationService.binderDied();
751 readConfigurationForUserStateLocked(userState);
752 // Even if reading did not yield change, we have to update
753 // the state since the context in which the current user
754 // state was used has changed since it was inactive.
755 onUserStateChangedLocked(userState);
757 if (announceNewUser) {
758 // Schedule announcement of the current user if needed.
759 mMainHandler.sendEmptyMessageDelayed(MainHandler.MSG_ANNOUNCE_NEW_USER_IF_NEEDED,
760 WAIT_FOR_USER_STATE_FULLY_INITIALIZED_MILLIS);
765 private void removeUser(int userId) {
766 synchronized (mLock) {
767 mUserStates.remove(userId);
771 private Service getQueryBridge() {
772 if (mQueryBridge == null) {
773 AccessibilityServiceInfo info = new AccessibilityServiceInfo();
774 mQueryBridge = new Service(UserHandle.USER_NULL,
775 sFakeAccessibilityServiceComponentName, info);
780 private boolean notifyGestureLocked(int gestureId, boolean isDefault) {
781 // TODO: Now we are giving the gestures to the last enabled
782 // service that can handle them which is the last one
783 // in our list since we write the last enabled as the
784 // last record in the enabled services setting. Ideally,
785 // the user should make the call which service handles
786 // gestures. However, only one service should handle
787 // gestures to avoid user frustration when different
788 // behavior is observed from different combinations of
789 // enabled accessibility services.
790 UserState state = getCurrentUserStateLocked();
791 for (int i = state.mBoundServices.size() - 1; i >= 0; i--) {
792 Service service = state.mBoundServices.get(i);
793 if (service.mRequestTouchExplorationMode && service.mIsDefault == isDefault) {
794 service.notifyGesture(gestureId);
801 private void notifyClearAccessibilityNodeInfoCacheLocked() {
802 UserState state = getCurrentUserStateLocked();
803 for (int i = state.mBoundServices.size() - 1; i >= 0; i--) {
804 Service service = state.mBoundServices.get(i);
805 service.notifyClearAccessibilityNodeInfoCache();
810 * Removes an AccessibilityInteractionConnection.
812 * @param windowId The id of the window to which the connection is targeted.
813 * @param userId The id of the user owning the connection. UserHandle.USER_ALL
816 private void removeAccessibilityInteractionConnectionLocked(int windowId, int userId) {
817 if (userId == UserHandle.USER_ALL) {
818 mGlobalWindowTokens.remove(windowId);
819 mGlobalInteractionConnections.remove(windowId);
821 UserState userState = getCurrentUserStateLocked();
822 userState.mWindowTokens.remove(windowId);
823 userState.mInteractionConnections.remove(windowId);
826 Slog.i(LOG_TAG, "Removing interaction connection to windowId: " + windowId);
830 private boolean readInstalledAccessibilityServiceLocked(UserState userState) {
831 mTempAccessibilityServiceInfoList.clear();
833 List<ResolveInfo> installedServices = mPackageManager.queryIntentServicesAsUser(
834 new Intent(AccessibilityService.SERVICE_INTERFACE),
835 PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
838 for (int i = 0, count = installedServices.size(); i < count; i++) {
839 ResolveInfo resolveInfo = installedServices.get(i);
840 ServiceInfo serviceInfo = resolveInfo.serviceInfo;
841 if (!android.Manifest.permission.BIND_ACCESSIBILITY_SERVICE.equals(
842 serviceInfo.permission)) {
843 Slog.w(LOG_TAG, "Skipping accessibilty service " + new ComponentName(
844 serviceInfo.packageName, serviceInfo.name).flattenToShortString()
845 + ": it does not require the permission "
846 + android.Manifest.permission.BIND_ACCESSIBILITY_SERVICE);
849 AccessibilityServiceInfo accessibilityServiceInfo;
851 accessibilityServiceInfo = new AccessibilityServiceInfo(resolveInfo, mContext);
852 mTempAccessibilityServiceInfoList.add(accessibilityServiceInfo);
853 } catch (XmlPullParserException xppe) {
854 Slog.e(LOG_TAG, "Error while initializing AccessibilityServiceInfo", xppe);
855 } catch (IOException ioe) {
856 Slog.e(LOG_TAG, "Error while initializing AccessibilityServiceInfo", ioe);
860 if (!mTempAccessibilityServiceInfoList.equals(userState.mInstalledServices)) {
861 userState.mInstalledServices.clear();
862 userState.mInstalledServices.addAll(mTempAccessibilityServiceInfoList);
863 mTempAccessibilityServiceInfoList.clear();
867 mTempAccessibilityServiceInfoList.clear();
871 private boolean readEnabledAccessibilityServicesLocked(UserState userState) {
872 mTempComponentNameSet.clear();
873 readComponentNamesFromSettingLocked(Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,
874 userState.mUserId, mTempComponentNameSet);
875 if (!mTempComponentNameSet.equals(userState.mEnabledServices)) {
876 userState.mEnabledServices.clear();
877 userState.mEnabledServices.addAll(mTempComponentNameSet);
878 mTempComponentNameSet.clear();
881 mTempComponentNameSet.clear();
885 private boolean readTouchExplorationGrantedAccessibilityServicesLocked(
886 UserState userState) {
887 mTempComponentNameSet.clear();
888 readComponentNamesFromSettingLocked(
889 Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES,
890 userState.mUserId, mTempComponentNameSet);
891 if (!mTempComponentNameSet.equals(userState.mTouchExplorationGrantedServices)) {
892 userState.mTouchExplorationGrantedServices.clear();
893 userState.mTouchExplorationGrantedServices.addAll(mTempComponentNameSet);
894 mTempComponentNameSet.clear();
897 mTempComponentNameSet.clear();
902 * Performs {@link AccessibilityService}s delayed notification. The delay is configurable
903 * and denotes the period after the last event before notifying the service.
905 * @param event The event.
906 * @param isDefault True to notify default listeners, not default services.
908 private void notifyAccessibilityServicesDelayedLocked(AccessibilityEvent event,
911 UserState state = getCurrentUserStateLocked();
912 for (int i = 0, count = state.mBoundServices.size(); i < count; i++) {
913 Service service = state.mBoundServices.get(i);
915 if (service.mIsDefault == isDefault) {
916 if (canDispathEventLocked(service, event, state.mHandledFeedbackTypes)) {
917 state.mHandledFeedbackTypes |= service.mFeedbackType;
918 service.notifyAccessibilityEvent(event);
922 } catch (IndexOutOfBoundsException oobe) {
923 // An out of bounds exception can happen if services are going away
924 // as the for loop is running. If that happens, just bail because
925 // there are no more services to notify.
930 private void addServiceLocked(Service service, UserState userState) {
932 service.linkToOwnDeath();
933 userState.mBoundServices.add(service);
934 userState.mComponentNameToServiceMap.put(service.mComponentName, service);
935 } catch (RemoteException re) {
943 * @param service The service.
944 * @return True if the service was removed, false otherwise.
946 private void removeServiceLocked(Service service, UserState userState) {
947 userState.mBoundServices.remove(service);
948 userState.mComponentNameToServiceMap.remove(service.mComponentName);
949 service.unlinkToOwnDeath();
953 * Determines if given event can be dispatched to a service based on the package of the
954 * event source and already notified services for that event type. Specifically, a
955 * service is notified if it is interested in events from the package and no other service
956 * providing the same feedback type has been notified. Exception are services the
957 * provide generic feedback (feedback type left as a safety net for unforeseen feedback
958 * types) which are always notified.
960 * @param service The potential receiver.
961 * @param event The event.
962 * @param handledFeedbackTypes The feedback types for which services have been notified.
963 * @return True if the listener should be notified, false otherwise.
965 private boolean canDispathEventLocked(Service service, AccessibilityEvent event,
966 int handledFeedbackTypes) {
968 if (!service.canReceiveEventsLocked()) {
972 if (!event.isImportantForAccessibility()
973 && (service.mFetchFlags
974 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) == 0) {
978 int eventType = event.getEventType();
979 if ((service.mEventTypes & eventType) != eventType) {
983 Set<String> packageNames = service.mPackageNames;
984 CharSequence packageName = event.getPackageName();
986 if (packageNames.isEmpty() || packageNames.contains(packageName)) {
987 int feedbackType = service.mFeedbackType;
988 if ((handledFeedbackTypes & feedbackType) != feedbackType
989 || feedbackType == AccessibilityServiceInfo.FEEDBACK_GENERIC) {
997 private void unbindAllServicesLocked(UserState userState) {
998 List<Service> services = userState.mBoundServices;
999 for (int i = 0, count = services.size(); i < count; i++) {
1000 Service service = services.get(i);
1001 if (service.unbindLocked()) {
1009 * Populates a set with the {@link ComponentName}s stored in a colon
1010 * separated value setting for a given user.
1012 * @param settingName The setting to parse.
1013 * @param userId The user id.
1014 * @param outComponentNames The output component names.
1016 private void readComponentNamesFromSettingLocked(String settingName, int userId,
1017 Set<ComponentName> outComponentNames) {
1018 String settingValue = Settings.Secure.getStringForUser(mContext.getContentResolver(),
1019 settingName, userId);
1020 outComponentNames.clear();
1021 if (settingValue != null) {
1022 TextUtils.SimpleStringSplitter splitter = mStringColonSplitter;
1023 splitter.setString(settingValue);
1024 while (splitter.hasNext()) {
1025 String str = splitter.next();
1026 if (str == null || str.length() <= 0) {
1029 ComponentName enabledService = ComponentName.unflattenFromString(str);
1030 if (enabledService != null) {
1031 outComponentNames.add(enabledService);
1038 * Persists the component names in the specified setting in a
1039 * colon separated fashion.
1041 * @param settingName The setting name.
1042 * @param componentNames The component names.
1044 private void persistComponentNamesToSettingLocked(String settingName,
1045 Set<ComponentName> componentNames, int userId) {
1046 StringBuilder builder = new StringBuilder();
1047 for (ComponentName componentName : componentNames) {
1048 if (builder.length() > 0) {
1049 builder.append(COMPONENT_NAME_SEPARATOR);
1051 builder.append(componentName.flattenToShortString());
1053 Settings.Secure.putStringForUser(mContext.getContentResolver(),
1054 settingName, builder.toString(), userId);
1057 private void manageServicesLocked(UserState userState) {
1058 Map<ComponentName, Service> componentNameToServiceMap =
1059 userState.mComponentNameToServiceMap;
1060 boolean isEnabled = userState.mIsAccessibilityEnabled;
1062 for (int i = 0, count = userState.mInstalledServices.size(); i < count; i++) {
1063 AccessibilityServiceInfo installedService = userState.mInstalledServices.get(i);
1064 ComponentName componentName = ComponentName.unflattenFromString(
1065 installedService.getId());
1066 Service service = componentNameToServiceMap.get(componentName);
1069 // Wait for the binding if it is in process.
1070 if (userState.mBindingServices.contains(componentName)) {
1073 if (userState.mEnabledServices.contains(componentName)) {
1074 if (service == null) {
1075 service = new Service(userState.mUserId, componentName, installedService);
1076 } else if (userState.mBoundServices.contains(service)) {
1079 service.bindLocked();
1081 if (service != null) {
1082 service.unbindLocked();
1086 if (service != null) {
1087 service.unbindLocked();
1089 userState.mBindingServices.remove(componentName);
1094 // No enabled installed services => disable accessibility to avoid
1095 // sending accessibility events with no recipient across processes.
1096 if (isEnabled && userState.mEnabledServices.isEmpty()) {
1097 userState.mIsAccessibilityEnabled = false;
1098 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1099 Settings.Secure.ACCESSIBILITY_ENABLED, 0, userState.mUserId);
1103 private void scheduleUpdateClientsIfNeededLocked(UserState userState) {
1104 final int clientState = userState.getClientState();
1105 if (userState.mLastSentClientState != clientState
1106 && (mGlobalClients.getRegisteredCallbackCount() > 0
1107 || userState.mClients.getRegisteredCallbackCount() > 0)) {
1108 userState.mLastSentClientState = clientState;
1109 mMainHandler.obtainMessage(MainHandler.MSG_SEND_STATE_TO_CLIENTS,
1110 clientState, userState.mUserId) .sendToTarget();
1114 private void scheduleUpdateInputFilter(UserState userState) {
1115 mMainHandler.obtainMessage(MainHandler.MSG_UPDATE_INPUT_FILTER, userState).sendToTarget();
1118 private void updateInputFilter(UserState userState) {
1119 boolean setInputFilter = false;
1120 AccessibilityInputFilter inputFilter = null;
1121 synchronized (mLock) {
1122 if ((userState.mIsAccessibilityEnabled && userState.mIsTouchExplorationEnabled)
1123 || userState.mIsDisplayMagnificationEnabled) {
1124 if (!mHasInputFilter) {
1125 mHasInputFilter = true;
1126 if (mInputFilter == null) {
1127 mInputFilter = new AccessibilityInputFilter(mContext,
1128 AccessibilityManagerService.this);
1130 inputFilter = mInputFilter;
1131 setInputFilter = true;
1134 if (userState.mIsDisplayMagnificationEnabled) {
1135 flags |= AccessibilityInputFilter.FLAG_FEATURE_SCREEN_MAGNIFIER;
1137 if (userState.mIsTouchExplorationEnabled) {
1138 flags |= AccessibilityInputFilter.FLAG_FEATURE_TOUCH_EXPLORATION;
1140 mInputFilter.setEnabledFeatures(flags);
1142 if (mHasInputFilter) {
1143 mHasInputFilter = false;
1144 mInputFilter.setEnabledFeatures(0);
1146 setInputFilter = true;
1150 if (setInputFilter) {
1152 mWindowManagerService.setInputFilter(inputFilter);
1153 } catch (RemoteException re) {
1159 private void showEnableTouchExplorationDialog(final Service service) {
1160 synchronized (mLock) {
1161 String label = service.mResolveInfo.loadLabel(
1162 mContext.getPackageManager()).toString();
1164 final UserState state = getCurrentUserStateLocked();
1165 if (state.mIsTouchExplorationEnabled) {
1168 if (mEnableTouchExplorationDialog != null
1169 && mEnableTouchExplorationDialog.isShowing()) {
1172 mEnableTouchExplorationDialog = new AlertDialog.Builder(mContext)
1173 .setIconAttribute(android.R.attr.alertDialogIcon)
1174 .setPositiveButton(android.R.string.ok, new OnClickListener() {
1176 public void onClick(DialogInterface dialog, int which) {
1177 // The user allowed the service to toggle touch exploration.
1178 state.mTouchExplorationGrantedServices.add(service.mComponentName);
1179 persistComponentNamesToSettingLocked(
1180 Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES,
1181 state.mTouchExplorationGrantedServices, state.mUserId);
1182 // Enable touch exploration.
1183 UserState userState = getUserStateLocked(service.mUserId);
1184 userState.mIsTouchExplorationEnabled = true;
1185 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1186 Settings.Secure.TOUCH_EXPLORATION_ENABLED, 1,
1188 onUserStateChangedLocked(userState);
1191 .setNegativeButton(android.R.string.cancel, new OnClickListener() {
1193 public void onClick(DialogInterface dialog, int which) {
1197 .setTitle(R.string.enable_explore_by_touch_warning_title)
1198 .setMessage(mContext.getString(
1199 R.string.enable_explore_by_touch_warning_message, label))
1201 mEnableTouchExplorationDialog.getWindow().setType(
1202 WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
1203 mEnableTouchExplorationDialog.getWindow().getAttributes().privateFlags
1204 |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
1205 mEnableTouchExplorationDialog.setCanceledOnTouchOutside(true);
1206 mEnableTouchExplorationDialog.show();
1210 private void onUserStateChangedLocked(UserState userState) {
1211 updateServicesLocked(userState);
1212 updateTouchExplorationLocked(userState);
1213 updateEnhancedWebAccessibilityLocked(userState);
1214 scheduleUpdateInputFilter(userState);
1215 scheduleUpdateClientsIfNeededLocked(userState);
1218 private void updateServicesLocked(UserState userState) {
1219 if (userState.mIsAccessibilityEnabled) {
1220 manageServicesLocked(userState);
1222 unbindAllServicesLocked(userState);
1226 private boolean readConfigurationForUserStateLocked(UserState userState) {
1227 boolean somthingChanged = false;
1228 somthingChanged |= readAccessibilityEnabledSettingLocked(userState);
1229 somthingChanged |= readInstalledAccessibilityServiceLocked(userState);
1230 somthingChanged |= readEnabledAccessibilityServicesLocked(userState);
1231 somthingChanged |= readTouchExplorationGrantedAccessibilityServicesLocked(userState);
1232 somthingChanged |= readTouchExplorationEnabledSettingLocked(userState);
1233 somthingChanged |= readEnhancedWebAccessibilityEnabledChangedLocked(userState);
1234 somthingChanged |= readDisplayMagnificationEnabledSettingLocked(userState);
1235 return somthingChanged;
1238 private boolean readAccessibilityEnabledSettingLocked(UserState userState) {
1239 final boolean accessibilityEnabled = Settings.Secure.getIntForUser(
1240 mContext.getContentResolver(),
1241 Settings.Secure.ACCESSIBILITY_ENABLED, 0, userState.mUserId) == 1;
1242 if (accessibilityEnabled != userState.mIsAccessibilityEnabled) {
1243 userState.mIsAccessibilityEnabled = accessibilityEnabled;
1249 private boolean readTouchExplorationEnabledSettingLocked(UserState userState) {
1250 final boolean touchExplorationEnabled = Settings.Secure.getIntForUser(
1251 mContext.getContentResolver(),
1252 Settings.Secure.TOUCH_EXPLORATION_ENABLED, 0, userState.mUserId) == 1;
1253 if (touchExplorationEnabled != userState.mIsTouchExplorationEnabled) {
1254 userState.mIsTouchExplorationEnabled = touchExplorationEnabled;
1260 private boolean readDisplayMagnificationEnabledSettingLocked(UserState userState) {
1261 final boolean displayMagnificationEnabled = Settings.Secure.getIntForUser(
1262 mContext.getContentResolver(),
1263 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED,
1264 0, userState.mUserId) == 1;
1265 if (displayMagnificationEnabled != userState.mIsDisplayMagnificationEnabled) {
1266 userState.mIsDisplayMagnificationEnabled = displayMagnificationEnabled;
1272 private boolean readEnhancedWebAccessibilityEnabledChangedLocked(UserState userState) {
1273 final boolean enhancedWeAccessibilityEnabled = Settings.Secure.getIntForUser(
1274 mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION,
1275 0, userState.mUserId) == 1;
1276 if (enhancedWeAccessibilityEnabled != userState.mIsEnhancedWebAccessibilityEnabled) {
1277 userState.mIsEnhancedWebAccessibilityEnabled = enhancedWeAccessibilityEnabled;
1283 private void updateTouchExplorationLocked(UserState userState) {
1284 userState.mIsTouchExplorationEnabled = false;
1285 final int serviceCount = userState.mBoundServices.size();
1286 for (int i = 0; i < serviceCount; i++) {
1287 Service service = userState.mBoundServices.get(i);
1288 if (tryEnableTouchExplorationLocked(service)) {
1294 private boolean tryEnableTouchExplorationLocked(Service service) {
1295 if (!service.canReceiveEventsLocked() || !service.mRequestTouchExplorationMode) {
1298 UserState userState = getUserStateLocked(service.mUserId);
1299 if (userState.mIsTouchExplorationEnabled) {
1302 // UI test automation service can always enable it.
1303 if (service.mIsAutomation) {
1304 userState.mIsTouchExplorationEnabled = true;
1305 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1306 Settings.Secure.TOUCH_EXPLORATION_ENABLED, 1, service.mUserId);
1309 if (service.mResolveInfo.serviceInfo.applicationInfo.targetSdkVersion
1310 <= Build.VERSION_CODES.JELLY_BEAN_MR1) {
1311 // Up to JB-MR1 we had a white list with services that can enable touch
1312 // exploration. When a service is first started we show a dialog to the
1313 // use to get a permission to white list the service.
1314 if (!userState.mTouchExplorationGrantedServices.contains(service.mComponentName)) {
1315 if (mEnableTouchExplorationDialog == null
1316 || (mEnableTouchExplorationDialog != null
1317 && !mEnableTouchExplorationDialog.isShowing())) {
1318 mMainHandler.obtainMessage(
1319 MainHandler.MSG_SHOW_ENABLED_TOUCH_EXPLORATION_DIALOG,
1320 service).sendToTarget();
1323 userState.mIsTouchExplorationEnabled = true;
1324 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1325 Settings.Secure.TOUCH_EXPLORATION_ENABLED, 1, service.mUserId);
1329 // Starting in JB-MR2 we request a permission to allow a service to enable
1330 // touch exploration and do not care if the service is in the white list.
1331 if (mContext.getPackageManager().checkPermission(
1332 android.Manifest.permission.CAN_REQUEST_TOUCH_EXPLORATION_MODE,
1333 service.mComponentName.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
1334 userState.mIsTouchExplorationEnabled = true;
1335 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1336 Settings.Secure.TOUCH_EXPLORATION_ENABLED, 1, service.mUserId);
1343 private void updateEnhancedWebAccessibilityLocked(UserState userState) {
1344 userState.mIsEnhancedWebAccessibilityEnabled = false;
1345 final int serviceCount = userState.mBoundServices.size();
1346 for (int i = 0; i < serviceCount; i++) {
1347 Service service = userState.mBoundServices.get(i);
1348 if (tryEnableEnhancedWebAccessibilityLocked(service)) {
1354 private boolean tryEnableEnhancedWebAccessibilityLocked(Service service) {
1355 if (!service.canReceiveEventsLocked() || !service.mRequestEnhancedWebAccessibility ) {
1358 UserState userState = getUserStateLocked(service.mUserId);
1359 if (userState.mIsEnhancedWebAccessibilityEnabled) {
1362 if (service.mIsAutomation || mContext.getPackageManager().checkPermission(
1363 android.Manifest.permission.CAN_REQUEST_ENHANCED_WEB_ACCESSIBILITY,
1364 service.mComponentName.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
1365 userState.mIsEnhancedWebAccessibilityEnabled = true;
1366 Settings.Secure.putIntForUser(mContext.getContentResolver(),
1367 Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION, 1, userState.mUserId);
1374 public void dump(FileDescriptor fd, final PrintWriter pw, String[] args) {
1375 mSecurityPolicy.enforceCallingPermission(Manifest.permission.DUMP, FUNCTION_DUMP);
1376 synchronized (mLock) {
1377 pw.println("ACCESSIBILITY MANAGER (dumpsys accessibility)");
1379 final int userCount = mUserStates.size();
1380 for (int i = 0; i < userCount; i++) {
1381 UserState userState = mUserStates.valueAt(i);
1382 pw.append("User state[attributes:{id=" + userState.mUserId);
1383 pw.append(", currentUser=" + (userState.mUserId == mCurrentUserId));
1384 pw.append(", accessibilityEnabled=" + userState.mIsAccessibilityEnabled);
1385 pw.append(", touchExplorationEnabled=" + userState.mIsTouchExplorationEnabled);
1386 pw.append(", displayMagnificationEnabled="
1387 + userState.mIsDisplayMagnificationEnabled);
1388 if (userState.mUiAutomationService != null) {
1390 userState.mUiAutomationService.dump(fd, pw, args);
1395 pw.append(" services:{");
1396 final int serviceCount = userState.mBoundServices.size();
1397 for (int j = 0; j < serviceCount; j++) {
1403 Service service = userState.mBoundServices.get(j);
1404 service.dump(fd, pw, args);
1412 private class AccessibilityConnectionWrapper implements DeathRecipient {
1413 private final int mWindowId;
1414 private final int mUserId;
1415 private final IAccessibilityInteractionConnection mConnection;
1417 public AccessibilityConnectionWrapper(int windowId,
1418 IAccessibilityInteractionConnection connection, int userId) {
1419 mWindowId = windowId;
1421 mConnection = connection;
1424 public void linkToDeath() throws RemoteException {
1425 mConnection.asBinder().linkToDeath(this, 0);
1428 public void unlinkToDeath() {
1429 mConnection.asBinder().unlinkToDeath(this, 0);
1433 public void binderDied() {
1435 synchronized (mLock) {
1436 removeAccessibilityInteractionConnectionLocked(mWindowId, mUserId);
1441 private final class MainHandler extends Handler {
1442 public static final int MSG_SEND_ACCESSIBILITY_EVENT_TO_INPUT_FILTER = 1;
1443 public static final int MSG_SEND_STATE_TO_CLIENTS = 2;
1444 public static final int MSG_SEND_CLEARED_STATE_TO_CLIENTS_FOR_USER = 3;
1445 public static final int MSG_UPDATE_ACTIVE_WINDOW = 4;
1446 public static final int MSG_ANNOUNCE_NEW_USER_IF_NEEDED = 5;
1447 public static final int MSG_UPDATE_INPUT_FILTER = 6;
1448 public static final int MSG_SHOW_ENABLED_TOUCH_EXPLORATION_DIALOG = 7;
1450 public MainHandler(Looper looper) {
1455 public void handleMessage(Message msg) {
1456 final int type = msg.what;
1458 case MSG_SEND_ACCESSIBILITY_EVENT_TO_INPUT_FILTER: {
1459 AccessibilityEvent event = (AccessibilityEvent) msg.obj;
1460 synchronized (mLock) {
1461 if (mHasInputFilter && mInputFilter != null) {
1462 mInputFilter.notifyAccessibilityEvent(event);
1467 case MSG_SEND_STATE_TO_CLIENTS: {
1468 final int clientState = msg.arg1;
1469 final int userId = msg.arg2;
1470 sendStateToClients(clientState, mGlobalClients);
1471 sendStateToClientsForUser(clientState, userId);
1473 case MSG_SEND_CLEARED_STATE_TO_CLIENTS_FOR_USER: {
1474 final int userId = msg.arg1;
1475 sendStateToClientsForUser(0, userId);
1477 case MSG_UPDATE_ACTIVE_WINDOW: {
1478 final int windowId = msg.arg1;
1479 final int eventType = msg.arg2;
1480 mSecurityPolicy.updateActiveWindow(windowId, eventType);
1482 case MSG_ANNOUNCE_NEW_USER_IF_NEEDED: {
1483 announceNewUserIfNeeded();
1485 case MSG_UPDATE_INPUT_FILTER: {
1486 UserState userState = (UserState) msg.obj;
1487 updateInputFilter(userState);
1489 case MSG_SHOW_ENABLED_TOUCH_EXPLORATION_DIALOG: {
1490 Service service = (Service) msg.obj;
1491 showEnableTouchExplorationDialog(service);
1496 private void announceNewUserIfNeeded() {
1497 synchronized (mLock) {
1498 UserState userState = getCurrentUserStateLocked();
1499 if (userState.mIsAccessibilityEnabled) {
1500 UserManager userManager = (UserManager) mContext.getSystemService(
1501 Context.USER_SERVICE);
1502 String message = mContext.getString(R.string.user_switched,
1503 userManager.getUserInfo(mCurrentUserId).name);
1504 AccessibilityEvent event = AccessibilityEvent.obtain(
1505 AccessibilityEvent.TYPE_ANNOUNCEMENT);
1506 event.getText().add(message);
1507 event.setWindowId(mSecurityPolicy.getRetrievalAllowingWindowLocked());
1508 sendAccessibilityEvent(event, mCurrentUserId);
1513 private void sendStateToClientsForUser(int clientState, int userId) {
1514 final UserState userState;
1515 synchronized (mLock) {
1516 userState = getUserStateLocked(userId);
1518 sendStateToClients(clientState, userState.mClients);
1521 private void sendStateToClients(int clientState,
1522 RemoteCallbackList<IAccessibilityManagerClient> clients) {
1524 final int userClientCount = clients.beginBroadcast();
1525 for (int i = 0; i < userClientCount; i++) {
1526 IAccessibilityManagerClient client = clients.getBroadcastItem(i);
1528 client.setState(clientState);
1529 } catch (RemoteException re) {
1534 clients.finishBroadcast();
1540 * This class represents an accessibility service. It stores all per service
1541 * data required for the service management, provides API for starting/stopping the
1542 * service and is responsible for adding/removing the service in the data structures
1543 * for service management. The class also exposes configuration interface that is
1544 * passed to the service it represents as soon it is bound. It also serves as the
1545 * connection for the service.
1547 class Service extends IAccessibilityServiceConnection.Stub
1548 implements ServiceConnection, DeathRecipient {
1550 // We pick the MSBs to avoid collision since accessibility event types are
1551 // used as message types allowing us to remove messages per event type.
1552 private static final int MSG_ON_GESTURE = 0x80000000;
1553 private static final int MSG_CLEAR_ACCESSIBILITY_NODE_INFO_CACHE = 0x40000000;
1559 AccessibilityServiceInfo mAccessibilityServiceInfo;
1563 IAccessibilityServiceClient mServiceInterface;
1569 Set<String> mPackageNames = new HashSet<String>();
1573 boolean mRequestTouchExplorationMode;
1575 boolean mRequestEnhancedWebAccessibility;
1579 long mNotificationTimeout;
1581 ComponentName mComponentName;
1585 boolean mCanRetrieveScreenContent;
1587 boolean mIsAutomation;
1589 final Rect mTempBounds = new Rect();
1591 final ResolveInfo mResolveInfo;
1593 // the events pending events to be dispatched to this service
1594 final SparseArray<AccessibilityEvent> mPendingEvents =
1595 new SparseArray<AccessibilityEvent>();
1598 * Handler for delayed event dispatch.
1600 public Handler mHandler = new Handler(mMainHandler.getLooper()) {
1602 public void handleMessage(Message message) {
1603 final int type = message.what;
1605 case MSG_ON_GESTURE: {
1606 final int gestureId = message.arg1;
1607 notifyGestureInternal(gestureId);
1609 case MSG_CLEAR_ACCESSIBILITY_NODE_INFO_CACHE: {
1610 notifyClearAccessibilityNodeInfoCacheInternal();
1613 final int eventType = type;
1614 notifyAccessibilityEventInternal(eventType);
1620 public Service(int userId, ComponentName componentName,
1621 AccessibilityServiceInfo accessibilityServiceInfo) {
1623 mResolveInfo = accessibilityServiceInfo.getResolveInfo();
1625 mComponentName = componentName;
1626 mAccessibilityServiceInfo = accessibilityServiceInfo;
1627 mIsAutomation = (sFakeAccessibilityServiceComponentName.equals(componentName));
1628 if (!mIsAutomation) {
1629 mCanRetrieveScreenContent = accessibilityServiceInfo.getCanRetrieveWindowContent();
1630 mIntent = new Intent().setComponent(mComponentName);
1631 mIntent.putExtra(Intent.EXTRA_CLIENT_LABEL,
1632 com.android.internal.R.string.accessibility_binding_label);
1633 mIntent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
1634 mContext, 0, new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS), 0));
1636 mCanRetrieveScreenContent = true;
1638 setDynamicallyConfigurableProperties(accessibilityServiceInfo);
1641 public void setDynamicallyConfigurableProperties(AccessibilityServiceInfo info) {
1642 mEventTypes = info.eventTypes;
1643 mFeedbackType = info.feedbackType;
1644 String[] packageNames = info.packageNames;
1645 if (packageNames != null) {
1646 mPackageNames.addAll(Arrays.asList(packageNames));
1648 mNotificationTimeout = info.notificationTimeout;
1649 mIsDefault = (info.flags & DEFAULT) != 0;
1651 if (mIsAutomation || info.getResolveInfo().serviceInfo.applicationInfo.targetSdkVersion
1652 >= Build.VERSION_CODES.JELLY_BEAN) {
1653 if ((info.flags & AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0) {
1654 mFetchFlags |= AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;
1656 mFetchFlags &= ~AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;
1660 if ((info.flags & AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS) != 0) {
1661 mFetchFlags |= AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS;
1663 mFetchFlags &= ~AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS;
1666 if (mResolveInfo != null) {
1667 mRequestTouchExplorationMode = (info.flags
1668 & AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE) != 0;
1669 mRequestEnhancedWebAccessibility = (info.flags
1670 & AccessibilityServiceInfo.FLAG_REQUEST_ENHANCED_WEB_ACCESSIBILITY) != 0;
1675 * Binds to the accessibility service.
1677 * @return True if binding is successful.
1679 public boolean bindLocked() {
1680 UserState userState = getUserStateLocked(mUserId);
1681 if (!mIsAutomation) {
1682 if (mService == null && mContext.bindServiceAsUser(
1683 mIntent, this, Context.BIND_AUTO_CREATE, new UserHandle(mUserId))) {
1684 userState.mBindingServices.add(mComponentName);
1687 userState.mBindingServices.add(mComponentName);
1688 mService = userState.mUiAutomationServiceClient.asBinder();
1689 onServiceConnected(mComponentName, mService);
1690 userState.mUiAutomationService = this;
1696 * Unbinds form the accessibility service and removes it from the data
1697 * structures for service management.
1699 * @return True if unbinding is successful.
1701 public boolean unbindLocked() {
1702 if (mService == null) {
1705 UserState userState = getUserStateLocked(mUserId);
1706 if (!mIsAutomation) {
1707 mContext.unbindService(this);
1709 userState.destroyUiAutomationService();
1711 removeServiceLocked(this, userState);
1716 public boolean canReceiveEventsLocked() {
1717 return (mEventTypes != 0 && mFeedbackType != 0 && mService != null);
1721 public AccessibilityServiceInfo getServiceInfo() {
1722 synchronized (mLock) {
1723 return mAccessibilityServiceInfo;
1728 public void setServiceInfo(AccessibilityServiceInfo info) {
1729 final long identity = Binder.clearCallingIdentity();
1731 synchronized (mLock) {
1732 // If the XML manifest had data to configure the service its info
1733 // should be already set. In such a case update only the dynamically
1734 // configurable properties.
1735 AccessibilityServiceInfo oldInfo = mAccessibilityServiceInfo;
1736 if (oldInfo != null) {
1737 oldInfo.updateDynamicallyConfigurableProperties(info);
1738 setDynamicallyConfigurableProperties(oldInfo);
1740 setDynamicallyConfigurableProperties(info);
1742 UserState userState = getUserStateLocked(mUserId);
1743 onUserStateChangedLocked(userState);
1746 Binder.restoreCallingIdentity(identity);
1751 public void onServiceConnected(ComponentName componentName, IBinder service) {
1752 synchronized (mLock) {
1754 mServiceInterface = IAccessibilityServiceClient.Stub.asInterface(service);
1755 UserState userState = getUserStateLocked(mUserId);
1756 addServiceLocked(this, userState);
1757 if (userState.mBindingServices.contains(mComponentName)) {
1758 userState.mBindingServices.remove(mComponentName);
1759 onUserStateChangedLocked(userState);
1761 mServiceInterface.setConnection(this, mId);
1762 } catch (RemoteException re) {
1763 Slog.w(LOG_TAG, "Error while setting connection for service: " + service, re);
1772 public boolean findAccessibilityNodeInfosByViewId(int accessibilityWindowId,
1773 long accessibilityNodeId, String viewIdResName, int interactionId,
1774 IAccessibilityInteractionConnectionCallback callback, long interrogatingTid)
1775 throws RemoteException {
1776 final int resolvedWindowId;
1777 IAccessibilityInteractionConnection connection = null;
1778 synchronized (mLock) {
1779 final int resolvedUserId = mSecurityPolicy
1780 .resolveCallingUserIdEnforcingPermissionsLocked(
1781 UserHandle.getCallingUserId());
1782 if (resolvedUserId != mCurrentUserId) {
1785 mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1786 final boolean permissionGranted = mSecurityPolicy.canRetrieveWindowContent(this);
1787 if (!permissionGranted) {
1790 resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1791 connection = getConnectionLocked(resolvedWindowId);
1792 if (connection == null) {
1797 final int interrogatingPid = Binder.getCallingPid();
1798 final long identityToken = Binder.clearCallingIdentity();
1799 MagnificationSpec spec = getCompatibleMagnificationSpec(resolvedWindowId);
1801 connection.findAccessibilityNodeInfosByViewId(accessibilityNodeId,
1802 viewIdResName, interactionId, callback, mFetchFlags, interrogatingPid,
1803 interrogatingTid, spec);
1805 } catch (RemoteException re) {
1807 Slog.e(LOG_TAG, "Error findAccessibilityNodeInfoByViewId().");
1810 Binder.restoreCallingIdentity(identityToken);
1816 public boolean findAccessibilityNodeInfosByText(int accessibilityWindowId,
1817 long accessibilityNodeId, String text, int interactionId,
1818 IAccessibilityInteractionConnectionCallback callback, long interrogatingTid)
1819 throws RemoteException {
1820 final int resolvedWindowId;
1821 IAccessibilityInteractionConnection connection = null;
1822 synchronized (mLock) {
1823 final int resolvedUserId = mSecurityPolicy
1824 .resolveCallingUserIdEnforcingPermissionsLocked(
1825 UserHandle.getCallingUserId());
1826 if (resolvedUserId != mCurrentUserId) {
1829 mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1830 resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1831 final boolean permissionGranted =
1832 mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId);
1833 if (!permissionGranted) {
1836 connection = getConnectionLocked(resolvedWindowId);
1837 if (connection == null) {
1842 final int interrogatingPid = Binder.getCallingPid();
1843 final long identityToken = Binder.clearCallingIdentity();
1844 MagnificationSpec spec = getCompatibleMagnificationSpec(resolvedWindowId);
1846 connection.findAccessibilityNodeInfosByText(accessibilityNodeId, text,
1847 interactionId, callback, mFetchFlags, interrogatingPid, interrogatingTid,
1850 } catch (RemoteException re) {
1852 Slog.e(LOG_TAG, "Error calling findAccessibilityNodeInfosByText()");
1855 Binder.restoreCallingIdentity(identityToken);
1861 public boolean findAccessibilityNodeInfoByAccessibilityId(
1862 int accessibilityWindowId, long accessibilityNodeId, int interactionId,
1863 IAccessibilityInteractionConnectionCallback callback, int flags,
1864 long interrogatingTid) throws RemoteException {
1865 final int resolvedWindowId;
1866 IAccessibilityInteractionConnection connection = null;
1867 synchronized (mLock) {
1868 final int resolvedUserId = mSecurityPolicy
1869 .resolveCallingUserIdEnforcingPermissionsLocked(
1870 UserHandle.getCallingUserId());
1871 if (resolvedUserId != mCurrentUserId) {
1874 mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1875 resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1876 final boolean permissionGranted =
1877 mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId);
1878 if (!permissionGranted) {
1881 connection = getConnectionLocked(resolvedWindowId);
1882 if (connection == null) {
1887 final int interrogatingPid = Binder.getCallingPid();
1888 final long identityToken = Binder.clearCallingIdentity();
1889 MagnificationSpec spec = getCompatibleMagnificationSpec(resolvedWindowId);
1891 connection.findAccessibilityNodeInfoByAccessibilityId(accessibilityNodeId,
1892 interactionId, callback, mFetchFlags | flags, interrogatingPid,
1893 interrogatingTid, spec);
1895 } catch (RemoteException re) {
1897 Slog.e(LOG_TAG, "Error calling findAccessibilityNodeInfoByAccessibilityId()");
1900 Binder.restoreCallingIdentity(identityToken);
1906 public boolean findFocus(int accessibilityWindowId, long accessibilityNodeId,
1907 int focusType, int interactionId,
1908 IAccessibilityInteractionConnectionCallback callback, long interrogatingTid)
1909 throws RemoteException {
1910 final int resolvedWindowId;
1911 IAccessibilityInteractionConnection connection = null;
1912 synchronized (mLock) {
1913 final int resolvedUserId = mSecurityPolicy
1914 .resolveCallingUserIdEnforcingPermissionsLocked(
1915 UserHandle.getCallingUserId());
1916 if (resolvedUserId != mCurrentUserId) {
1919 mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1920 resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1921 final boolean permissionGranted =
1922 mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId);
1923 if (!permissionGranted) {
1926 connection = getConnectionLocked(resolvedWindowId);
1927 if (connection == null) {
1932 final int interrogatingPid = Binder.getCallingPid();
1933 final long identityToken = Binder.clearCallingIdentity();
1934 MagnificationSpec spec = getCompatibleMagnificationSpec(resolvedWindowId);
1936 connection.findFocus(accessibilityNodeId, focusType, interactionId, callback,
1937 mFetchFlags, interrogatingPid, interrogatingTid, spec);
1939 } catch (RemoteException re) {
1941 Slog.e(LOG_TAG, "Error calling findAccessibilityFocus()");
1944 Binder.restoreCallingIdentity(identityToken);
1950 public boolean focusSearch(int accessibilityWindowId, long accessibilityNodeId,
1951 int direction, int interactionId,
1952 IAccessibilityInteractionConnectionCallback callback, long interrogatingTid)
1953 throws RemoteException {
1954 final int resolvedWindowId;
1955 IAccessibilityInteractionConnection connection = null;
1956 synchronized (mLock) {
1957 final int resolvedUserId = mSecurityPolicy
1958 .resolveCallingUserIdEnforcingPermissionsLocked(
1959 UserHandle.getCallingUserId());
1960 if (resolvedUserId != mCurrentUserId) {
1963 mSecurityPolicy.enforceCanRetrieveWindowContent(this);
1964 resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
1965 final boolean permissionGranted =
1966 mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId);
1967 if (!permissionGranted) {
1970 connection = getConnectionLocked(resolvedWindowId);
1971 if (connection == null) {
1976 final int interrogatingPid = Binder.getCallingPid();
1977 final long identityToken = Binder.clearCallingIdentity();
1978 MagnificationSpec spec = getCompatibleMagnificationSpec(resolvedWindowId);
1980 connection.focusSearch(accessibilityNodeId, direction, interactionId, callback,
1981 mFetchFlags, interrogatingPid, interrogatingTid, spec);
1983 } catch (RemoteException re) {
1985 Slog.e(LOG_TAG, "Error calling accessibilityFocusSearch()");
1988 Binder.restoreCallingIdentity(identityToken);
1994 public boolean performAccessibilityAction(int accessibilityWindowId,
1995 long accessibilityNodeId, int action, Bundle arguments, int interactionId,
1996 IAccessibilityInteractionConnectionCallback callback, long interrogatingTid)
1997 throws RemoteException {
1998 final int resolvedWindowId;
1999 IAccessibilityInteractionConnection connection = null;
2000 synchronized (mLock) {
2001 final int resolvedUserId = mSecurityPolicy
2002 .resolveCallingUserIdEnforcingPermissionsLocked(
2003 UserHandle.getCallingUserId());
2004 if (resolvedUserId != mCurrentUserId) {
2007 mSecurityPolicy.enforceCanRetrieveWindowContent(this);
2008 resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId);
2009 final boolean permissionGranted = mSecurityPolicy.canPerformActionLocked(this,
2010 resolvedWindowId, action, arguments);
2011 if (!permissionGranted) {
2014 connection = getConnectionLocked(resolvedWindowId);
2015 if (connection == null) {
2020 final int interrogatingPid = Binder.getCallingPid();
2021 final long identityToken = Binder.clearCallingIdentity();
2023 connection.performAccessibilityAction(accessibilityNodeId, action, arguments,
2024 interactionId, callback, mFetchFlags, interrogatingPid, interrogatingTid);
2025 } catch (RemoteException re) {
2027 Slog.e(LOG_TAG, "Error calling performAccessibilityAction()");
2030 Binder.restoreCallingIdentity(identityToken);
2035 public boolean performGlobalAction(int action) {
2036 synchronized (mLock) {
2037 final int resolvedUserId = mSecurityPolicy
2038 .resolveCallingUserIdEnforcingPermissionsLocked(
2039 UserHandle.getCallingUserId());
2040 if (resolvedUserId != mCurrentUserId) {
2044 final long identity = Binder.clearCallingIdentity();
2047 case AccessibilityService.GLOBAL_ACTION_BACK: {
2048 sendDownAndUpKeyEvents(KeyEvent.KEYCODE_BACK);
2050 case AccessibilityService.GLOBAL_ACTION_HOME: {
2051 sendDownAndUpKeyEvents(KeyEvent.KEYCODE_HOME);
2053 case AccessibilityService.GLOBAL_ACTION_RECENTS: {
2056 case AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS: {
2057 expandNotifications();
2059 case AccessibilityService.GLOBAL_ACTION_QUICK_SETTINGS: {
2060 expandQuickSettings();
2065 Binder.restoreCallingIdentity(identity);
2070 public void dump(FileDescriptor fd, final PrintWriter pw, String[] args) {
2071 mSecurityPolicy.enforceCallingPermission(Manifest.permission.DUMP, FUNCTION_DUMP);
2072 synchronized (mLock) {
2073 pw.append("Service[label=" + mAccessibilityServiceInfo.getResolveInfo()
2074 .loadLabel(mContext.getPackageManager()));
2075 pw.append(", feedbackType"
2076 + AccessibilityServiceInfo.feedbackTypeToString(mFeedbackType));
2077 pw.append(", canRetrieveScreenContent=" + mCanRetrieveScreenContent);
2078 pw.append(", eventTypes="
2079 + AccessibilityEvent.eventTypeToString(mEventTypes));
2080 pw.append(", notificationTimeout=" + mNotificationTimeout);
2086 public void onServiceDisconnected(ComponentName componentName) {
2087 /* do nothing - #binderDied takes care */
2090 public void linkToOwnDeath() throws RemoteException {
2091 mService.linkToDeath(this, 0);
2094 public void unlinkToOwnDeath() {
2095 mService.unlinkToDeath(this, 0);
2098 public void dispose() {
2100 // Clear the proxy in the other process so this
2101 // IAccessibilityServiceConnection can be garbage collected.
2102 mServiceInterface.setConnection(null, mId);
2103 } catch (RemoteException re) {
2107 mServiceInterface = null;
2110 public void binderDied() {
2111 synchronized (mLock) {
2112 UserState userState = getUserStateLocked(mUserId);
2113 // The death recipient is unregistered in removeServiceLocked
2114 removeServiceLocked(this, userState);
2116 if (mIsAutomation) {
2117 // We no longer have an automation service, so restore
2118 // the state based on values in the settings database.
2119 userState.mInstalledServices.remove(mAccessibilityServiceInfo);
2120 userState.mEnabledServices.remove(mComponentName);
2121 userState.destroyUiAutomationService();
2123 onUserStateChangedLocked(userState);
2128 * Performs a notification for an {@link AccessibilityEvent}.
2130 * @param event The event.
2132 public void notifyAccessibilityEvent(AccessibilityEvent event) {
2133 synchronized (mLock) {
2134 final int eventType = event.getEventType();
2135 // Make a copy since during dispatch it is possible the event to
2136 // be modified to remove its source if the receiving service does
2137 // not have permission to access the window content.
2138 AccessibilityEvent newEvent = AccessibilityEvent.obtain(event);
2139 AccessibilityEvent oldEvent = mPendingEvents.get(eventType);
2140 mPendingEvents.put(eventType, newEvent);
2142 final int what = eventType;
2143 if (oldEvent != null) {
2144 mHandler.removeMessages(what);
2148 Message message = mHandler.obtainMessage(what);
2149 mHandler.sendMessageDelayed(message, mNotificationTimeout);
2154 * Notifies an accessibility service client for a scheduled event given the event type.
2156 * @param eventType The type of the event to dispatch.
2158 private void notifyAccessibilityEventInternal(int eventType) {
2159 IAccessibilityServiceClient listener;
2160 AccessibilityEvent event;
2162 synchronized (mLock) {
2163 listener = mServiceInterface;
2165 // If the service died/was disabled while the message for dispatching
2166 // the accessibility event was propagating the listener may be null.
2167 if (listener == null) {
2171 event = mPendingEvents.get(eventType);
2173 // Check for null here because there is a concurrent scenario in which this
2174 // happens: 1) A binder thread calls notifyAccessibilityServiceDelayedLocked
2175 // which posts a message for dispatching an event. 2) The message is pulled
2176 // from the queue by the handler on the service thread and the latter is
2177 // just about to acquire the lock and call this method. 3) Now another binder
2178 // thread acquires the lock calling notifyAccessibilityServiceDelayedLocked
2179 // so the service thread waits for the lock; 4) The binder thread replaces
2180 // the event with a more recent one (assume the same event type) and posts a
2181 // dispatch request releasing the lock. 5) Now the main thread is unblocked and
2182 // dispatches the event which is removed from the pending ones. 6) And ... now
2183 // the service thread handles the last message posted by the last binder call
2184 // but the event is already dispatched and hence looking it up in the pending
2185 // ones yields null. This check is much simpler that keeping count for each
2186 // event type of each service to catch such a scenario since only one message
2187 // is processed at a time.
2188 if (event == null) {
2192 mPendingEvents.remove(eventType);
2193 if (mSecurityPolicy.canRetrieveWindowContent(this)) {
2194 event.setConnectionId(mId);
2196 event.setSource(null);
2198 event.setSealed(true);
2202 listener.onAccessibilityEvent(event);
2204 Slog.i(LOG_TAG, "Event " + event + " sent to " + listener);
2206 } catch (RemoteException re) {
2207 Slog.e(LOG_TAG, "Error during sending " + event + " to " + listener, re);
2213 public void notifyGesture(int gestureId) {
2214 mHandler.obtainMessage(MSG_ON_GESTURE, gestureId, 0).sendToTarget();
2217 public void notifyClearAccessibilityNodeInfoCache() {
2218 mHandler.sendEmptyMessage(MSG_CLEAR_ACCESSIBILITY_NODE_INFO_CACHE);
2221 private void notifyGestureInternal(int gestureId) {
2222 IAccessibilityServiceClient listener = mServiceInterface;
2223 if (listener != null) {
2225 listener.onGesture(gestureId);
2226 } catch (RemoteException re) {
2227 Slog.e(LOG_TAG, "Error during sending gesture " + gestureId
2228 + " to " + mService, re);
2233 private void notifyClearAccessibilityNodeInfoCacheInternal() {
2234 IAccessibilityServiceClient listener = mServiceInterface;
2235 if (listener != null) {
2237 listener.clearAccessibilityNodeInfoCache();
2238 } catch (RemoteException re) {
2239 Slog.e(LOG_TAG, "Error during requesting accessibility info cache"
2240 + " to be cleared.", re);
2245 private void sendDownAndUpKeyEvents(int keyCode) {
2246 final long token = Binder.clearCallingIdentity();
2249 final long downTime = SystemClock.uptimeMillis();
2250 KeyEvent down = KeyEvent.obtain(downTime, downTime, KeyEvent.ACTION_DOWN, keyCode, 0, 0,
2251 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FROM_SYSTEM,
2252 InputDevice.SOURCE_KEYBOARD, null);
2253 InputManager.getInstance().injectInputEvent(down,
2254 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
2258 final long upTime = SystemClock.uptimeMillis();
2259 KeyEvent up = KeyEvent.obtain(downTime, upTime, KeyEvent.ACTION_UP, keyCode, 0, 0,
2260 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FROM_SYSTEM,
2261 InputDevice.SOURCE_KEYBOARD, null);
2262 InputManager.getInstance().injectInputEvent(up,
2263 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
2266 Binder.restoreCallingIdentity(token);
2269 private void expandNotifications() {
2270 final long token = Binder.clearCallingIdentity();
2272 StatusBarManager statusBarManager = (StatusBarManager) mContext.getSystemService(
2273 android.app.Service.STATUS_BAR_SERVICE);
2274 statusBarManager.expandNotificationsPanel();
2276 Binder.restoreCallingIdentity(token);
2279 private void expandQuickSettings() {
2280 final long token = Binder.clearCallingIdentity();
2282 StatusBarManager statusBarManager = (StatusBarManager) mContext.getSystemService(
2283 android.app.Service.STATUS_BAR_SERVICE);
2284 statusBarManager.expandSettingsPanel();
2286 Binder.restoreCallingIdentity(token);
2289 private void openRecents() {
2290 final long token = Binder.clearCallingIdentity();
2292 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
2293 ServiceManager.getService("statusbar"));
2295 statusBarService.toggleRecentApps();
2296 } catch (RemoteException e) {
2297 Slog.e(LOG_TAG, "Error toggling recent apps.");
2300 Binder.restoreCallingIdentity(token);
2303 private IAccessibilityInteractionConnection getConnectionLocked(int windowId) {
2305 Slog.i(LOG_TAG, "Trying to get interaction connection to windowId: " + windowId);
2307 AccessibilityConnectionWrapper wrapper = mGlobalInteractionConnections.get(windowId);
2308 if (wrapper == null) {
2309 wrapper = getCurrentUserStateLocked().mInteractionConnections.get(windowId);
2311 if (wrapper != null && wrapper.mConnection != null) {
2312 return wrapper.mConnection;
2315 Slog.e(LOG_TAG, "No interaction connection to window: " + windowId);
2320 private int resolveAccessibilityWindowIdLocked(int accessibilityWindowId) {
2321 if (accessibilityWindowId == AccessibilityNodeInfo.ACTIVE_WINDOW_ID) {
2322 return mSecurityPolicy.mActiveWindowId;
2324 return accessibilityWindowId;
2327 private MagnificationSpec getCompatibleMagnificationSpec(int windowId) {
2329 IBinder windowToken = mGlobalWindowTokens.get(windowId);
2330 if (windowToken == null) {
2331 windowToken = getCurrentUserStateLocked().mWindowTokens.get(windowId);
2333 if (windowToken != null) {
2334 return mWindowManagerService.getCompatibleMagnificationSpecForWindow(
2337 } catch (RemoteException re) {
2344 final class SecurityPolicy {
2345 private static final int VALID_ACTIONS =
2346 AccessibilityNodeInfo.ACTION_CLICK
2347 | AccessibilityNodeInfo.ACTION_LONG_CLICK
2348 | AccessibilityNodeInfo.ACTION_FOCUS
2349 | AccessibilityNodeInfo.ACTION_CLEAR_FOCUS
2350 | AccessibilityNodeInfo.ACTION_SELECT
2351 | AccessibilityNodeInfo.ACTION_CLEAR_SELECTION
2352 | AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS
2353 | AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS
2354 | AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
2355 | AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY
2356 | AccessibilityNodeInfo.ACTION_NEXT_HTML_ELEMENT
2357 | AccessibilityNodeInfo.ACTION_PREVIOUS_HTML_ELEMENT
2358 | AccessibilityNodeInfo.ACTION_SCROLL_FORWARD
2359 | AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD
2360 | AccessibilityNodeInfo.ACTION_COPY
2361 | AccessibilityNodeInfo.ACTION_PASTE
2362 | AccessibilityNodeInfo.ACTION_CUT
2363 | AccessibilityNodeInfo.ACTION_SET_SELECTION;
2365 private static final int RETRIEVAL_ALLOWING_EVENT_TYPES =
2366 AccessibilityEvent.TYPE_VIEW_CLICKED
2367 | AccessibilityEvent.TYPE_VIEW_FOCUSED
2368 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
2369 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
2370 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
2371 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
2372 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
2373 | AccessibilityEvent.TYPE_VIEW_SELECTED
2374 | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED
2375 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED
2376 | AccessibilityEvent.TYPE_VIEW_SCROLLED
2377 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
2378 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED;
2380 private int mActiveWindowId;
2381 private boolean mTouchInteractionInProgress;
2383 private boolean canDispatchAccessibilityEvent(AccessibilityEvent event) {
2384 final int eventType = event.getEventType();
2385 switch (eventType) {
2386 // All events that are for changes in a global window
2387 // state should *always* be dispatched.
2388 case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
2389 case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
2390 // All events generated by the user touching the
2391 // screen should *always* be dispatched.
2392 case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START:
2393 case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END:
2394 case AccessibilityEvent.TYPE_GESTURE_DETECTION_START:
2395 case AccessibilityEvent.TYPE_GESTURE_DETECTION_END:
2396 case AccessibilityEvent.TYPE_TOUCH_INTERACTION_START:
2397 case AccessibilityEvent.TYPE_TOUCH_INTERACTION_END:
2398 // These will change the active window, so dispatch.
2399 case AccessibilityEvent.TYPE_VIEW_HOVER_ENTER:
2400 case AccessibilityEvent.TYPE_VIEW_HOVER_EXIT: {
2403 // All events for changes in window content should be
2404 // dispatched *only* if this window is the active one.
2406 return event.getWindowId() == mActiveWindowId;
2410 public void updateEventSourceLocked(AccessibilityEvent event) {
2411 if ((event.getEventType() & RETRIEVAL_ALLOWING_EVENT_TYPES) == 0) {
2412 event.setSource(null);
2416 public void updateActiveWindow(int windowId, int eventType) {
2417 // The active window is either the window that has input focus or
2418 // the window that the user is currently touching. If the user is
2419 // touching a window that does not have input focus as soon as the
2420 // the user stops touching that window the focused window becomes
2422 switch (eventType) {
2423 case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED: {
2424 if (getFocusedWindowId() == windowId) {
2425 mActiveWindowId = windowId;
2428 case AccessibilityEvent.TYPE_VIEW_HOVER_ENTER: {
2429 // Do not allow delayed hover events to confuse us
2430 // which the active window is.
2431 if (mTouchInteractionInProgress) {
2432 mActiveWindowId = windowId;
2438 public void onTouchInteractionStart() {
2439 mTouchInteractionInProgress = true;
2442 public void onTouchInteractionEnd() {
2443 mTouchInteractionInProgress = false;
2444 // We want to set the active window to be current immediately
2445 // after the user has stopped touching the screen since if the
2446 // user types with the IME he should get a feedback for the
2447 // letter typed in the text view which is in the input focused
2448 // window. Note that we always deliver hover accessibility events
2449 // (they are a result of user touching the screen) so change of
2450 // the active window before all hover accessibility events from
2451 // the touched window are delivered is fine.
2452 mActiveWindowId = getFocusedWindowId();
2455 public int getRetrievalAllowingWindowLocked() {
2456 return mActiveWindowId;
2459 public boolean canGetAccessibilityNodeInfoLocked(Service service, int windowId) {
2460 return canRetrieveWindowContent(service) && isRetrievalAllowingWindow(windowId);
2463 public boolean canPerformActionLocked(Service service, int windowId, int action,
2465 return canRetrieveWindowContent(service)
2466 && isRetrievalAllowingWindow(windowId)
2467 && isActionPermitted(action);
2470 public boolean canRetrieveWindowContent(Service service) {
2471 return service.mCanRetrieveScreenContent;
2474 public void enforceCanRetrieveWindowContent(Service service) throws RemoteException {
2475 // This happens due to incorrect registration so make it apparent.
2476 if (!canRetrieveWindowContent(service)) {
2477 Slog.e(LOG_TAG, "Accessibility serivce " + service.mComponentName + " does not " +
2478 "declare android:canRetrieveWindowContent.");
2479 throw new RemoteException();
2483 public int resolveCallingUserIdEnforcingPermissionsLocked(int userId) {
2484 final int callingUid = Binder.getCallingUid();
2485 if (callingUid == Process.SYSTEM_UID
2486 || callingUid == Process.SHELL_UID) {
2487 return mCurrentUserId;
2489 final int callingUserId = UserHandle.getUserId(callingUid);
2490 if (callingUserId == userId) {
2493 if (!hasPermission(Manifest.permission.INTERACT_ACROSS_USERS)
2494 && !hasPermission(Manifest.permission.INTERACT_ACROSS_USERS_FULL)) {
2495 throw new SecurityException("Call from user " + callingUserId + " as user "
2496 + userId + " without permission INTERACT_ACROSS_USERS or "
2497 + "INTERACT_ACROSS_USERS_FULL not allowed.");
2499 if (userId == UserHandle.USER_CURRENT
2500 || userId == UserHandle.USER_CURRENT_OR_SELF) {
2501 return mCurrentUserId;
2503 throw new IllegalArgumentException("Calling user can be changed to only "
2504 + "UserHandle.USER_CURRENT or UserHandle.USER_CURRENT_OR_SELF.");
2507 public boolean isCallerInteractingAcrossUsers(int userId) {
2508 final int callingUid = Binder.getCallingUid();
2509 return (Binder.getCallingPid() == android.os.Process.myPid()
2510 || callingUid == Process.SHELL_UID
2511 || userId == UserHandle.USER_CURRENT
2512 || userId == UserHandle.USER_CURRENT_OR_SELF);
2515 private boolean isRetrievalAllowingWindow(int windowId) {
2516 return (mActiveWindowId == windowId);
2519 private boolean isActionPermitted(int action) {
2520 return (VALID_ACTIONS & action) != 0;
2523 private void enforceCallingPermission(String permission, String function) {
2524 if (OWN_PROCESS_ID == Binder.getCallingPid()) {
2527 if (!hasPermission(permission)) {
2528 throw new SecurityException("You do not have " + permission
2529 + " required to call " + function + " from pid="
2530 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid());
2534 private boolean hasPermission(String permission) {
2535 return mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED;
2538 private int getFocusedWindowId() {
2540 // We call this only on window focus change or after touch
2541 // exploration gesture end and the shown windows are not that
2542 // many, so the linear look up is just fine.
2543 IBinder token = mWindowManagerService.getFocusedWindowToken();
2544 if (token != null) {
2545 synchronized (mLock) {
2546 int windowId = getFocusedWindowIdLocked(token, mGlobalWindowTokens);
2548 windowId = getFocusedWindowIdLocked(token,
2549 getCurrentUserStateLocked().mWindowTokens);
2554 } catch (RemoteException re) {
2560 private int getFocusedWindowIdLocked(IBinder token, SparseArray<IBinder> windows) {
2561 final int windowCount = windows.size();
2562 for (int i = 0; i < windowCount; i++) {
2563 if (windows.valueAt(i) == token) {
2564 return windows.keyAt(i);
2571 private class UserState {
2572 public final int mUserId;
2574 // Non-transient state.
2576 public final RemoteCallbackList<IAccessibilityManagerClient> mClients =
2577 new RemoteCallbackList<IAccessibilityManagerClient>();
2579 public final SparseArray<AccessibilityConnectionWrapper> mInteractionConnections =
2580 new SparseArray<AccessibilityConnectionWrapper>();
2582 public final SparseArray<IBinder> mWindowTokens = new SparseArray<IBinder>();
2586 public final CopyOnWriteArrayList<Service> mBoundServices =
2587 new CopyOnWriteArrayList<Service>();
2589 public final Map<ComponentName, Service> mComponentNameToServiceMap =
2590 new HashMap<ComponentName, Service>();
2592 public final List<AccessibilityServiceInfo> mInstalledServices =
2593 new ArrayList<AccessibilityServiceInfo>();
2595 public final Set<ComponentName> mBindingServices = new HashSet<ComponentName>();
2597 public final Set<ComponentName> mEnabledServices = new HashSet<ComponentName>();
2599 public final Set<ComponentName> mTouchExplorationGrantedServices =
2600 new HashSet<ComponentName>();
2602 public int mHandledFeedbackTypes = 0;
2604 public int mLastSentClientState = -1;
2606 public boolean mIsAccessibilityEnabled;
2607 public boolean mIsTouchExplorationEnabled;
2608 public boolean mIsEnhancedWebAccessibilityEnabled;
2609 public boolean mIsDisplayMagnificationEnabled;
2611 private Service mUiAutomationService;
2612 private IAccessibilityServiceClient mUiAutomationServiceClient;
2614 private IBinder mUiAutomationServiceOwner;
2615 private final DeathRecipient mUiAutomationSerivceOnwerDeathRecipient =
2616 new DeathRecipient() {
2618 public void binderDied() {
2619 mUiAutomationServiceOwner.unlinkToDeath(
2620 mUiAutomationSerivceOnwerDeathRecipient, 0);
2621 mUiAutomationServiceOwner = null;
2622 if (mUiAutomationService != null) {
2623 mUiAutomationService.binderDied();
2628 public UserState(int userId) {
2632 public int getClientState() {
2633 int clientState = 0;
2634 if (mIsAccessibilityEnabled) {
2635 clientState |= AccessibilityManager.STATE_FLAG_ACCESSIBILITY_ENABLED;
2637 // Touch exploration relies on enabled accessibility.
2638 if (mIsAccessibilityEnabled && mIsTouchExplorationEnabled) {
2639 clientState |= AccessibilityManager.STATE_FLAG_TOUCH_EXPLORATION_ENABLED;
2644 public void onSwitchToAnotherUser() {
2645 // Clear UI test automation state.
2646 if (mUiAutomationService != null) {
2647 mUiAutomationService.binderDied();
2650 // Unbind all services.
2651 unbindAllServicesLocked(this);
2653 // Clear service management state.
2654 mBoundServices.clear();
2655 mBindingServices.clear();
2657 // Clear event management state.
2658 mHandledFeedbackTypes = 0;
2659 mLastSentClientState = -1;
2661 // Clear state persisted in settings.
2662 mEnabledServices.clear();
2663 mTouchExplorationGrantedServices.clear();
2664 mIsAccessibilityEnabled = false;
2665 mIsTouchExplorationEnabled = false;
2666 mIsEnhancedWebAccessibilityEnabled = false;
2667 mIsDisplayMagnificationEnabled = false;
2670 public void destroyUiAutomationService() {
2671 mUiAutomationService = null;
2672 mUiAutomationServiceClient = null;
2673 if (mUiAutomationServiceOwner != null) {
2674 mUiAutomationServiceOwner.unlinkToDeath(
2675 mUiAutomationSerivceOnwerDeathRecipient, 0);
2676 mUiAutomationServiceOwner = null;
2681 private final class AccessibilityContentObserver extends ContentObserver {
2683 private final Uri mAccessibilityEnabledUri = Settings.Secure.getUriFor(
2684 Settings.Secure.ACCESSIBILITY_ENABLED);
2686 private final Uri mTouchExplorationEnabledUri = Settings.Secure.getUriFor(
2687 Settings.Secure.TOUCH_EXPLORATION_ENABLED);
2689 private final Uri mDisplayMagnificationEnabledUri = Settings.Secure.getUriFor(
2690 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED);
2692 private final Uri mEnabledAccessibilityServicesUri = Settings.Secure.getUriFor(
2693 Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
2695 private final Uri mTouchExplorationGrantedAccessibilityServicesUri = Settings.Secure
2696 .getUriFor(Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES);
2698 private final Uri mEnhancedWebAccessibilityUri = Settings.Secure
2699 .getUriFor(Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION);
2701 public AccessibilityContentObserver(Handler handler) {
2705 public void register(ContentResolver contentResolver) {
2706 contentResolver.registerContentObserver(mAccessibilityEnabledUri,
2707 false, this, UserHandle.USER_ALL);
2708 contentResolver.registerContentObserver(mTouchExplorationEnabledUri,
2709 false, this, UserHandle.USER_ALL);
2710 contentResolver.registerContentObserver(mDisplayMagnificationEnabledUri,
2711 false, this, UserHandle.USER_ALL);
2712 contentResolver.registerContentObserver(mEnabledAccessibilityServicesUri,
2713 false, this, UserHandle.USER_ALL);
2714 contentResolver.registerContentObserver(
2715 mTouchExplorationGrantedAccessibilityServicesUri,
2716 false, this, UserHandle.USER_ALL);
2717 contentResolver.registerContentObserver(mEnhancedWebAccessibilityUri,
2718 false, this, UserHandle.USER_ALL);
2722 public void onChange(boolean selfChange, Uri uri) {
2723 if (mAccessibilityEnabledUri.equals(uri)) {
2724 synchronized (mLock) {
2725 // We will update when the automation service dies.
2726 UserState userState = getCurrentUserStateLocked();
2727 if (userState.mUiAutomationService == null) {
2728 if (readAccessibilityEnabledSettingLocked(userState)) {
2729 onUserStateChangedLocked(userState);
2733 } else if (mTouchExplorationEnabledUri.equals(uri)) {
2734 synchronized (mLock) {
2735 // We will update when the automation service dies.
2736 UserState userState = getCurrentUserStateLocked();
2737 if (userState.mUiAutomationService == null) {
2738 if (readTouchExplorationEnabledSettingLocked(userState)) {
2739 onUserStateChangedLocked(userState);
2743 } else if (mDisplayMagnificationEnabledUri.equals(uri)) {
2744 synchronized (mLock) {
2745 // We will update when the automation service dies.
2746 UserState userState = getCurrentUserStateLocked();
2747 if (userState.mUiAutomationService == null) {
2748 if (readDisplayMagnificationEnabledSettingLocked(userState)) {
2749 onUserStateChangedLocked(userState);
2753 } else if (mEnabledAccessibilityServicesUri.equals(uri)) {
2754 synchronized (mLock) {
2755 // We will update when the automation service dies.
2756 UserState userState = getCurrentUserStateLocked();
2757 if (userState.mUiAutomationService == null) {
2758 if (readEnabledAccessibilityServicesLocked(userState)) {
2759 onUserStateChangedLocked(userState);
2763 } else if (mTouchExplorationGrantedAccessibilityServicesUri.equals(uri)) {
2764 synchronized (mLock) {
2765 // We will update when the automation service dies.
2766 UserState userState = getCurrentUserStateLocked();
2767 if (userState.mUiAutomationService == null) {
2768 if (readTouchExplorationGrantedAccessibilityServicesLocked(userState)) {
2769 onUserStateChangedLocked(userState);
2773 } else if (mEnhancedWebAccessibilityUri.equals(uri)) {
2774 synchronized (mLock) {
2775 // We will update when the automation service dies.
2776 UserState userState = getCurrentUserStateLocked();
2777 if (userState.mUiAutomationService == null) {
2778 if (readEnhancedWebAccessibilityEnabledChangedLocked(userState)) {
2779 onUserStateChangedLocked(userState);