AccessibilityManagerService.java revision fc9c4cd51b3bdca27726dd6d8a00d47e388ca2aa
1/* 2 ** Copyright 2009, The Android Open Source Project 3 ** 4 ** Licensed under the Apache License, Version 2.0 (the "License"); 5 ** you may not use this file except in compliance with the License. 6 ** You may obtain a copy of the License at 7 ** 8 ** http://www.apache.org/licenses/LICENSE-2.0 9 ** 10 ** Unless required by applicable law or agreed to in writing, software 11 ** distributed under the License is distributed on an "AS IS" BASIS, 12 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 ** See the License for the specific language governing permissions and 14 ** limitations under the License. 15 */ 16 17package com.android.server.accessibility; 18 19import static android.accessibilityservice.AccessibilityServiceInfo.DEFAULT; 20import static android.accessibilityservice.AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS; 21 22import android.Manifest; 23import android.accessibilityservice.AccessibilityService; 24import android.accessibilityservice.AccessibilityServiceInfo; 25import android.accessibilityservice.IAccessibilityServiceClient; 26import android.accessibilityservice.IAccessibilityServiceConnection; 27import android.app.AlertDialog; 28import android.app.PendingIntent; 29import android.app.StatusBarManager; 30import android.content.BroadcastReceiver; 31import android.content.ComponentName; 32import android.content.ContentResolver; 33import android.content.Context; 34import android.content.DialogInterface; 35import android.content.DialogInterface.OnClickListener; 36import android.content.Intent; 37import android.content.IntentFilter; 38import android.content.ServiceConnection; 39import android.content.pm.PackageManager; 40import android.content.pm.ResolveInfo; 41import android.content.pm.ServiceInfo; 42import android.database.ContentObserver; 43import android.graphics.Rect; 44import android.hardware.input.InputManager; 45import android.net.Uri; 46import android.os.Binder; 47import android.os.Build; 48import android.os.Bundle; 49import android.os.Handler; 50import android.os.IBinder; 51import android.os.Looper; 52import android.os.Message; 53import android.os.Process; 54import android.os.RemoteCallbackList; 55import android.os.RemoteException; 56import android.os.ServiceManager; 57import android.os.SystemClock; 58import android.os.UserHandle; 59import android.os.UserManager; 60import android.provider.Settings; 61import android.text.TextUtils; 62import android.text.TextUtils.SimpleStringSplitter; 63import android.util.Slog; 64import android.util.SparseArray; 65import android.view.IWindow; 66import android.view.IWindowManager; 67import android.view.InputDevice; 68import android.view.KeyCharacterMap; 69import android.view.KeyEvent; 70import android.view.WindowInfo; 71import android.view.WindowManager; 72import android.view.accessibility.AccessibilityEvent; 73import android.view.accessibility.AccessibilityInteractionClient; 74import android.view.accessibility.AccessibilityManager; 75import android.view.accessibility.AccessibilityNodeInfo; 76import android.view.accessibility.IAccessibilityInteractionConnection; 77import android.view.accessibility.IAccessibilityInteractionConnectionCallback; 78import android.view.accessibility.IAccessibilityManager; 79import android.view.accessibility.IAccessibilityManagerClient; 80 81import com.android.internal.R; 82import com.android.internal.content.PackageMonitor; 83import com.android.internal.statusbar.IStatusBarService; 84 85import org.xmlpull.v1.XmlPullParserException; 86 87import java.io.IOException; 88import java.util.ArrayList; 89import java.util.Arrays; 90import java.util.HashMap; 91import java.util.HashSet; 92import java.util.Iterator; 93import java.util.List; 94import java.util.Map; 95import java.util.Set; 96import java.util.concurrent.CopyOnWriteArrayList; 97 98/** 99 * This class is instantiated by the system as a system level service and can be 100 * accessed only by the system. The task of this service is to be a centralized 101 * event dispatch for {@link AccessibilityEvent}s generated across all processes 102 * on the device. Events are dispatched to {@link AccessibilityService}s. 103 * 104 * @hide 105 */ 106public class AccessibilityManagerService extends IAccessibilityManager.Stub { 107 108 private static final boolean DEBUG = false; 109 110 private static final String LOG_TAG = "AccessibilityManagerService"; 111 112 // TODO: This is arbitrary. When there is time implement this by watching 113 // when that accessibility services are bound. 114 private static final int WAIT_FOR_USER_STATE_FULLY_INITIALIZED_MILLIS = 3000; 115 116 private static final String FUNCTION_REGISTER_UI_TEST_AUTOMATION_SERVICE = 117 "registerUiTestAutomationService"; 118 119 private static final String TEMPORARY_ENABLE_ACCESSIBILITY_UNTIL_KEYGUARD_REMOVED = 120 "temporaryEnableAccessibilityStateUntilKeyguardRemoved"; 121 122 private static final char COMPONENT_NAME_SEPARATOR = ':'; 123 124 private static final int OWN_PROCESS_ID = android.os.Process.myPid(); 125 126 private static int sIdCounter = 0; 127 128 private static int sNextWindowId; 129 130 private final Context mContext; 131 132 private final Object mLock = new Object(); 133 134 private final SimpleStringSplitter mStringColonSplitter = 135 new SimpleStringSplitter(COMPONENT_NAME_SEPARATOR); 136 137 private final List<AccessibilityServiceInfo> mEnabledServicesForFeedbackTempList = 138 new ArrayList<AccessibilityServiceInfo>(); 139 140 private final PackageManager mPackageManager; 141 142 private final IWindowManager mWindowManagerService; 143 144 private final SecurityPolicy mSecurityPolicy; 145 146 private final MainHandler mMainHandler; 147 148 private Service mUiAutomationService; 149 150 private Service mQueryBridge; 151 152 private AlertDialog mEnableTouchExplorationDialog; 153 154 private AccessibilityInputFilter mInputFilter; 155 156 private boolean mHasInputFilter; 157 158 private final RemoteCallbackList<IAccessibilityManagerClient> mGlobalClients = 159 new RemoteCallbackList<IAccessibilityManagerClient>(); 160 161 private final SparseArray<AccessibilityConnectionWrapper> mGlobalInteractionConnections = 162 new SparseArray<AccessibilityConnectionWrapper>(); 163 164 private final SparseArray<IBinder> mGlobalWindowTokens = new SparseArray<IBinder>(); 165 166 private final SparseArray<UserState> mUserStates = new SparseArray<UserState>(); 167 168 private final TempUserStateChangeMemento mTempStateChangeForCurrentUserMemento = 169 new TempUserStateChangeMemento(); 170 171 private int mCurrentUserId = UserHandle.USER_OWNER; 172 173 private UserState getCurrentUserStateLocked() { 174 return getUserStateLocked(mCurrentUserId); 175 } 176 177 private UserState getUserStateLocked(int userId) { 178 UserState state = mUserStates.get(userId); 179 if (state == null) { 180 state = new UserState(userId); 181 mUserStates.put(userId, state); 182 } 183 return state; 184 } 185 186 /** 187 * Creates a new instance. 188 * 189 * @param context A {@link Context} instance. 190 */ 191 public AccessibilityManagerService(Context context) { 192 mContext = context; 193 mPackageManager = mContext.getPackageManager(); 194 mWindowManagerService = (IWindowManager) ServiceManager.getService(Context.WINDOW_SERVICE); 195 mSecurityPolicy = new SecurityPolicy(); 196 mMainHandler = new MainHandler(mContext.getMainLooper()); 197 registerBroadcastReceivers(); 198 new AccessibilityContentObserver(mMainHandler).register( 199 context.getContentResolver()); 200 } 201 202 private void registerBroadcastReceivers() { 203 PackageMonitor monitor = new PackageMonitor() { 204 @Override 205 public void onSomePackagesChanged() { 206 synchronized (mLock) { 207 if (getChangingUserId() != mCurrentUserId) { 208 return; 209 } 210 // We will update when the automation service dies. 211 if (mUiAutomationService == null) { 212 UserState userState = getCurrentUserStateLocked(); 213 populateInstalledAccessibilityServiceLocked(userState); 214 manageServicesLocked(userState); 215 } 216 } 217 } 218 219 @Override 220 public void onPackageRemoved(String packageName, int uid) { 221 synchronized (mLock) { 222 final int userId = getChangingUserId(); 223 if (userId != mCurrentUserId) { 224 return; 225 } 226 UserState state = getUserStateLocked(userId); 227 Iterator<ComponentName> it = state.mEnabledServices.iterator(); 228 while (it.hasNext()) { 229 ComponentName comp = it.next(); 230 String compPkg = comp.getPackageName(); 231 if (compPkg.equals(packageName)) { 232 it.remove(); 233 // Update the enabled services setting. 234 persistComponentNamesToSettingLocked( 235 Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, 236 state.mEnabledServices, userId); 237 // Update the touch exploration granted services setting. 238 state.mTouchExplorationGrantedServices.remove(comp); 239 persistComponentNamesToSettingLocked( 240 Settings.Secure. 241 TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES, 242 state.mEnabledServices, userId); 243 return; 244 } 245 } 246 } 247 } 248 249 @Override 250 public boolean onHandleForceStop(Intent intent, String[] packages, 251 int uid, boolean doit) { 252 synchronized (mLock) { 253 final int userId = getChangingUserId(); 254 if (userId != mCurrentUserId) { 255 return false; 256 } 257 UserState state = getUserStateLocked(userId); 258 Iterator<ComponentName> it = state.mEnabledServices.iterator(); 259 while (it.hasNext()) { 260 ComponentName comp = it.next(); 261 String compPkg = comp.getPackageName(); 262 for (String pkg : packages) { 263 if (compPkg.equals(pkg)) { 264 if (!doit) { 265 return true; 266 } 267 it.remove(); 268 persistComponentNamesToSettingLocked( 269 Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, 270 state.mEnabledServices, userId); 271 } 272 } 273 } 274 return false; 275 } 276 } 277 }; 278 279 // package changes 280 monitor.register(mContext, null, UserHandle.ALL, true); 281 282 // user change and unlock 283 IntentFilter intentFilter = new IntentFilter(); 284 intentFilter.addAction(Intent.ACTION_USER_SWITCHED); 285 intentFilter.addAction(Intent.ACTION_USER_REMOVED); 286 intentFilter.addAction(Intent.ACTION_USER_PRESENT); 287 288 mContext.registerReceiverAsUser(new BroadcastReceiver() { 289 @Override 290 public void onReceive(Context context, Intent intent) { 291 String action = intent.getAction(); 292 if (Intent.ACTION_USER_SWITCHED.equals(action)) { 293 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0)); 294 } else if (Intent.ACTION_USER_REMOVED.equals(action)) { 295 removeUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0)); 296 } else if (Intent.ACTION_USER_PRESENT.equals(action)) { 297 restoreStateFromMementoIfNeeded(); 298 } 299 } 300 }, UserHandle.ALL, intentFilter, null, null); 301 } 302 303 public int addClient(IAccessibilityManagerClient client, int userId) { 304 synchronized (mLock) { 305 final int resolvedUserId = mSecurityPolicy 306 .resolveCallingUserIdEnforcingPermissionsLocked(userId); 307 // If the client is from a process that runs across users such as 308 // the system UI or the system we add it to the global state that 309 // is shared across users. 310 UserState userState = getUserStateLocked(resolvedUserId); 311 if (mSecurityPolicy.isCallerInteractingAcrossUsers(userId)) { 312 mGlobalClients.register(client); 313 if (DEBUG) { 314 Slog.i(LOG_TAG, "Added global client for pid:" + Binder.getCallingPid()); 315 } 316 return getClientState(userState); 317 } else { 318 userState.mClients.register(client); 319 // If this client is not for the current user we do not 320 // return a state since it is not for the foreground user. 321 // We will send the state to the client on a user switch. 322 if (DEBUG) { 323 Slog.i(LOG_TAG, "Added user client for pid:" + Binder.getCallingPid() 324 + " and userId:" + mCurrentUserId); 325 } 326 return (resolvedUserId == mCurrentUserId) ? getClientState(userState) : 0; 327 } 328 } 329 } 330 331 public boolean sendAccessibilityEvent(AccessibilityEvent event, int userId) { 332 synchronized (mLock) { 333 final int resolvedUserId = mSecurityPolicy 334 .resolveCallingUserIdEnforcingPermissionsLocked(userId); 335 // This method does nothing for a background user. 336 if (resolvedUserId != mCurrentUserId) { 337 return true; // yes, recycle the event 338 } 339 if (mSecurityPolicy.canDispatchAccessibilityEvent(event)) { 340 mSecurityPolicy.updateEventSourceLocked(event); 341 mMainHandler.obtainMessage(MainHandler.MSG_UPDATE_ACTIVE_WINDOW, 342 event.getWindowId(), event.getEventType()).sendToTarget(); 343 notifyAccessibilityServicesDelayedLocked(event, false); 344 notifyAccessibilityServicesDelayedLocked(event, true); 345 } 346 if (mHasInputFilter && mInputFilter != null) { 347 mMainHandler.obtainMessage(MainHandler.MSG_SEND_ACCESSIBILITY_EVENT_TO_INPUT_FILTER, 348 AccessibilityEvent.obtain(event)).sendToTarget(); 349 } 350 event.recycle(); 351 getUserStateLocked(resolvedUserId).mHandledFeedbackTypes = 0; 352 } 353 return (OWN_PROCESS_ID != Binder.getCallingPid()); 354 } 355 356 public List<AccessibilityServiceInfo> getInstalledAccessibilityServiceList(int userId) { 357 synchronized (mLock) { 358 final int resolvedUserId = mSecurityPolicy 359 .resolveCallingUserIdEnforcingPermissionsLocked(userId); 360 return getUserStateLocked(resolvedUserId).mInstalledServices; 361 } 362 } 363 364 public List<AccessibilityServiceInfo> getEnabledAccessibilityServiceList(int feedbackType, 365 int userId) { 366 List<AccessibilityServiceInfo> result = null; 367 synchronized (mLock) { 368 final int resolvedUserId = mSecurityPolicy 369 .resolveCallingUserIdEnforcingPermissionsLocked(userId); 370 result = mEnabledServicesForFeedbackTempList; 371 result.clear(); 372 List<Service> services = getUserStateLocked(resolvedUserId).mServices; 373 while (feedbackType != 0) { 374 final int feedbackTypeBit = (1 << Integer.numberOfTrailingZeros(feedbackType)); 375 feedbackType &= ~feedbackTypeBit; 376 final int serviceCount = services.size(); 377 for (int i = 0; i < serviceCount; i++) { 378 Service service = services.get(i); 379 if ((service.mFeedbackType & feedbackTypeBit) != 0) { 380 result.add(service.mAccessibilityServiceInfo); 381 } 382 } 383 } 384 } 385 return result; 386 } 387 388 public void interrupt(int userId) { 389 CopyOnWriteArrayList<Service> services; 390 synchronized (mLock) { 391 final int resolvedUserId = mSecurityPolicy 392 .resolveCallingUserIdEnforcingPermissionsLocked(userId); 393 // This method does nothing for a background user. 394 if (resolvedUserId != mCurrentUserId) { 395 return; 396 } 397 services = getUserStateLocked(resolvedUserId).mServices; 398 } 399 for (int i = 0, count = services.size(); i < count; i++) { 400 Service service = services.get(i); 401 try { 402 service.mServiceInterface.onInterrupt(); 403 } catch (RemoteException re) { 404 Slog.e(LOG_TAG, "Error during sending interrupt request to " 405 + service.mService, re); 406 } 407 } 408 } 409 410 public int addAccessibilityInteractionConnection(IWindow windowToken, 411 IAccessibilityInteractionConnection connection, int userId) throws RemoteException { 412 synchronized (mLock) { 413 final int resolvedUserId = mSecurityPolicy 414 .resolveCallingUserIdEnforcingPermissionsLocked(userId); 415 final int windowId = sNextWindowId++; 416 // If the window is from a process that runs across users such as 417 // the system UI or the system we add it to the global state that 418 // is shared across users. 419 if (mSecurityPolicy.isCallerInteractingAcrossUsers(userId)) { 420 AccessibilityConnectionWrapper wrapper = new AccessibilityConnectionWrapper( 421 windowId, connection, UserHandle.USER_ALL); 422 wrapper.linkToDeath(); 423 mGlobalInteractionConnections.put(windowId, wrapper); 424 mGlobalWindowTokens.put(windowId, windowToken.asBinder()); 425 if (DEBUG) { 426 Slog.i(LOG_TAG, "Added global connection for pid:" + Binder.getCallingPid() 427 + " with windowId: " + windowId); 428 } 429 } else { 430 AccessibilityConnectionWrapper wrapper = new AccessibilityConnectionWrapper( 431 windowId, connection, resolvedUserId); 432 wrapper.linkToDeath(); 433 UserState userState = getUserStateLocked(resolvedUserId); 434 userState.mInteractionConnections.put(windowId, wrapper); 435 userState.mWindowTokens.put(windowId, windowToken.asBinder()); 436 if (DEBUG) { 437 Slog.i(LOG_TAG, "Added user connection for pid:" + Binder.getCallingPid() 438 + " with windowId: " + windowId + " and userId:" + mCurrentUserId); 439 } 440 } 441 if (DEBUG) { 442 Slog.i(LOG_TAG, "Adding interaction connection to windowId: " + windowId); 443 } 444 return windowId; 445 } 446 } 447 448 public void removeAccessibilityInteractionConnection(IWindow window) { 449 synchronized (mLock) { 450 mSecurityPolicy.resolveCallingUserIdEnforcingPermissionsLocked( 451 UserHandle.getCallingUserId()); 452 IBinder token = window.asBinder(); 453 final int removedWindowId = removeAccessibilityInteractionConnectionInternalLocked( 454 token, mGlobalWindowTokens, mGlobalInteractionConnections); 455 if (removedWindowId >= 0) { 456 if (DEBUG) { 457 Slog.i(LOG_TAG, "Removed global connection for pid:" + Binder.getCallingPid() 458 + " with windowId: " + removedWindowId); 459 } 460 return; 461 } 462 final int userCount = mUserStates.size(); 463 for (int i = 0; i < userCount; i++) { 464 UserState userState = mUserStates.valueAt(i); 465 final int removedWindowIdForUser = 466 removeAccessibilityInteractionConnectionInternalLocked( 467 token, userState.mWindowTokens, userState.mInteractionConnections); 468 if (removedWindowIdForUser >= 0) { 469 if (DEBUG) { 470 Slog.i(LOG_TAG, "Removed user connection for pid:" + Binder.getCallingPid() 471 + " with windowId: " + removedWindowIdForUser + " and userId:" 472 + mUserStates.keyAt(i)); 473 } 474 return; 475 } 476 } 477 } 478 } 479 480 private int removeAccessibilityInteractionConnectionInternalLocked(IBinder windowToken, 481 SparseArray<IBinder> windowTokens, 482 SparseArray<AccessibilityConnectionWrapper> interactionConnections) { 483 final int count = windowTokens.size(); 484 for (int i = 0; i < count; i++) { 485 if (windowTokens.valueAt(i) == windowToken) { 486 final int windowId = windowTokens.keyAt(i); 487 windowTokens.removeAt(i); 488 AccessibilityConnectionWrapper wrapper = interactionConnections.get(windowId); 489 wrapper.unlinkToDeath(); 490 interactionConnections.remove(windowId); 491 return windowId; 492 } 493 } 494 return -1; 495 } 496 497 public void registerUiTestAutomationService(IAccessibilityServiceClient serviceClient, 498 AccessibilityServiceInfo accessibilityServiceInfo) { 499 mSecurityPolicy.enforceCallingPermission(Manifest.permission.RETRIEVE_WINDOW_CONTENT, 500 FUNCTION_REGISTER_UI_TEST_AUTOMATION_SERVICE); 501 ComponentName componentName = new ComponentName("foo.bar", 502 "AutomationAccessibilityService"); 503 synchronized (mLock) { 504 // If an automation services is connected to the system all services are stopped 505 // so the automation one is the only one running. Settings are not changed so when 506 // the automation service goes away the state is restored from the settings. 507 UserState userState = getCurrentUserStateLocked(); 508 unbindAllServicesLocked(userState); 509 510 // If necessary enable accessibility and announce that. 511 if (!userState.mIsAccessibilityEnabled) { 512 userState.mIsAccessibilityEnabled = true; 513 } 514 // No touch exploration. 515 userState.mIsTouchExplorationEnabled = false; 516 517 // Hook the automation service up. 518 mUiAutomationService = new Service(mCurrentUserId, componentName, 519 accessibilityServiceInfo, true); 520 mUiAutomationService.onServiceConnected(componentName, serviceClient.asBinder()); 521 522 updateInputFilterLocked(userState); 523 scheduleSendStateToClientsLocked(userState); 524 } 525 } 526 527 public void temporaryEnableAccessibilityStateUntilKeyguardRemoved( 528 ComponentName service, boolean touchExplorationEnabled) { 529 mSecurityPolicy.enforceCallingPermission( 530 Manifest.permission.TEMPORARY_ENABLE_ACCESSIBILITY, 531 TEMPORARY_ENABLE_ACCESSIBILITY_UNTIL_KEYGUARD_REMOVED); 532 try { 533 if (!mWindowManagerService.isKeyguardLocked()) { 534 return; 535 } 536 } catch (RemoteException re) { 537 return; 538 } 539 synchronized (mLock) { 540 UserState userState = getCurrentUserStateLocked(); 541 // Stash the old state so we can restore it when the keyguard is gone. 542 mTempStateChangeForCurrentUserMemento.initialize(mCurrentUserId, getCurrentUserStateLocked()); 543 // Set the temporary state. 544 userState.mIsAccessibilityEnabled = true; 545 userState.mIsTouchExplorationEnabled= touchExplorationEnabled; 546 userState.mIsDisplayMagnificationEnabled = false; 547 userState.mEnabledServices.clear(); 548 userState.mEnabledServices.add(service); 549 userState.mTouchExplorationGrantedServices.clear(); 550 userState.mTouchExplorationGrantedServices.add(service); 551 // Update the internal state. 552 performServiceManagementLocked(userState); 553 updateInputFilterLocked(userState); 554 scheduleSendStateToClientsLocked(userState); 555 } 556 } 557 558 public void unregisterUiTestAutomationService(IAccessibilityServiceClient serviceClient) { 559 synchronized (mLock) { 560 // Automation service is not bound, so pretend it died to perform clean up. 561 if (mUiAutomationService != null && mUiAutomationService.mServiceInterface != null 562 && serviceClient != null && mUiAutomationService.mServiceInterface 563 .asBinder() == serviceClient.asBinder()) { 564 mUiAutomationService.binderDied(); 565 } 566 } 567 } 568 569 boolean onGesture(int gestureId) { 570 synchronized (mLock) { 571 boolean handled = notifyGestureLocked(gestureId, false); 572 if (!handled) { 573 handled = notifyGestureLocked(gestureId, true); 574 } 575 return handled; 576 } 577 } 578 579 /** 580 * Gets the bounds of the accessibility focus in the active window. 581 * 582 * @param outBounds The output to which to write the focus bounds. 583 * @return Whether accessibility focus was found and the bounds are populated. 584 */ 585 boolean getAccessibilityFocusBoundsInActiveWindow(Rect outBounds) { 586 // Instead of keeping track of accessibility focus events per 587 // window to be able to find the focus in the active window, 588 // we take a stateless approach and look it up. This is fine 589 // since we do this only when the user clicks/long presses. 590 Service service = getQueryBridge(); 591 final int connectionId = service.mId; 592 AccessibilityInteractionClient client = AccessibilityInteractionClient.getInstance(); 593 client.addConnection(connectionId, service); 594 try { 595 AccessibilityNodeInfo root = AccessibilityInteractionClient.getInstance() 596 .getRootInActiveWindow(connectionId); 597 if (root == null) { 598 return false; 599 } 600 AccessibilityNodeInfo focus = root.findFocus( 601 AccessibilityNodeInfo.FOCUS_ACCESSIBILITY); 602 if (focus == null) { 603 return false; 604 } 605 focus.getBoundsInScreen(outBounds); 606 return true; 607 } finally { 608 client.removeConnection(connectionId); 609 } 610 } 611 612 /** 613 * Gets the bounds of the active window. 614 * 615 * @param outBounds The output to which to write the bounds. 616 */ 617 boolean getActiveWindowBounds(Rect outBounds) { 618 IBinder token; 619 synchronized (mLock) { 620 final int windowId = mSecurityPolicy.mActiveWindowId; 621 token = mGlobalWindowTokens.get(windowId); 622 if (token == null) { 623 token = getCurrentUserStateLocked().mWindowTokens.get(windowId); 624 } 625 } 626 WindowInfo info = null; 627 try { 628 info = mWindowManagerService.getWindowInfo(token); 629 if (info != null) { 630 outBounds.set(info.frame); 631 return true; 632 } 633 } catch (RemoteException re) { 634 /* ignore */ 635 } finally { 636 if (info != null) { 637 info.recycle(); 638 } 639 } 640 return false; 641 } 642 643 int getActiveWindowId() { 644 return mSecurityPolicy.mActiveWindowId; 645 } 646 647 void onTouchInteractionStart() { 648 mSecurityPolicy.onTouchInteractionStart(); 649 } 650 651 void onTouchInteractionEnd() { 652 mSecurityPolicy.onTouchInteractionEnd(); 653 } 654 655 private void switchUser(int userId) { 656 synchronized (mLock) { 657 // The user switched so we do not need to restore the current user 658 // state since we will fully rebuild it when he becomes current again. 659 mTempStateChangeForCurrentUserMemento.clear(); 660 661 // Disconnect from services for the old user. 662 UserState oldUserState = getUserStateLocked(mCurrentUserId); 663 unbindAllServicesLocked(oldUserState); 664 665 // Disable the local managers for the old user. 666 if (oldUserState.mClients.getRegisteredCallbackCount() > 0) { 667 mMainHandler.obtainMessage(MainHandler.MSG_SEND_CLEARED_STATE_TO_CLIENTS_FOR_USER, 668 oldUserState.mUserId, 0).sendToTarget(); 669 } 670 671 // Announce user changes only if more that one exist. 672 UserManager userManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE); 673 final boolean announceNewUser = userManager.getUsers().size() > 1; 674 675 // The user changed. 676 mCurrentUserId = userId; 677 678 // Recreate the internal state for the new user. 679 mMainHandler.obtainMessage(MainHandler.MSG_SEND_RECREATE_INTERNAL_STATE, 680 mCurrentUserId, 0).sendToTarget(); 681 682 if (announceNewUser) { 683 // Schedule announcement of the current user if needed. 684 mMainHandler.sendEmptyMessageDelayed(MainHandler.MSG_ANNOUNCE_NEW_USER_IF_NEEDED, 685 WAIT_FOR_USER_STATE_FULLY_INITIALIZED_MILLIS); 686 } 687 } 688 } 689 690 private void removeUser(int userId) { 691 synchronized (mLock) { 692 mUserStates.remove(userId); 693 } 694 } 695 696 private void restoreStateFromMementoIfNeeded() { 697 synchronized (mLock) { 698 if (mTempStateChangeForCurrentUserMemento.mUserId != UserHandle.USER_NULL) { 699 UserState userState = getCurrentUserStateLocked(); 700 // Restore the state from the memento. 701 mTempStateChangeForCurrentUserMemento.applyTo(userState); 702 mTempStateChangeForCurrentUserMemento.clear(); 703 // Update the internal state. 704 performServiceManagementLocked(userState); 705 updateInputFilterLocked(userState); 706 scheduleSendStateToClientsLocked(userState); 707 } 708 } 709 } 710 711 private Service getQueryBridge() { 712 if (mQueryBridge == null) { 713 AccessibilityServiceInfo info = new AccessibilityServiceInfo(); 714 mQueryBridge = new Service(UserHandle.USER_NULL, null, info, true); 715 } 716 return mQueryBridge; 717 } 718 719 private boolean notifyGestureLocked(int gestureId, boolean isDefault) { 720 // TODO: Now we are giving the gestures to the last enabled 721 // service that can handle them which is the last one 722 // in our list since we write the last enabled as the 723 // last record in the enabled services setting. Ideally, 724 // the user should make the call which service handles 725 // gestures. However, only one service should handle 726 // gestures to avoid user frustration when different 727 // behavior is observed from different combinations of 728 // enabled accessibility services. 729 UserState state = getCurrentUserStateLocked(); 730 for (int i = state.mServices.size() - 1; i >= 0; i--) { 731 Service service = state.mServices.get(i); 732 if (service.mRequestTouchExplorationMode && service.mIsDefault == isDefault) { 733 service.notifyGesture(gestureId); 734 return true; 735 } 736 } 737 return false; 738 } 739 740 /** 741 * Removes an AccessibilityInteractionConnection. 742 * 743 * @param windowId The id of the window to which the connection is targeted. 744 * @param userId The id of the user owning the connection. UserHandle.USER_ALL 745 * if global. 746 */ 747 private void removeAccessibilityInteractionConnectionLocked(int windowId, int userId) { 748 if (userId == UserHandle.USER_ALL) { 749 mGlobalWindowTokens.remove(windowId); 750 mGlobalInteractionConnections.remove(windowId); 751 } else { 752 UserState userState = getCurrentUserStateLocked(); 753 userState.mWindowTokens.remove(windowId); 754 userState.mInteractionConnections.remove(windowId); 755 } 756 if (DEBUG) { 757 Slog.i(LOG_TAG, "Removing interaction connection to windowId: " + windowId); 758 } 759 } 760 761 private void populateInstalledAccessibilityServiceLocked(UserState userState) { 762 userState.mInstalledServices.clear(); 763 764 List<ResolveInfo> installedServices = mPackageManager.queryIntentServicesAsUser( 765 new Intent(AccessibilityService.SERVICE_INTERFACE), 766 PackageManager.GET_SERVICES | PackageManager.GET_META_DATA, 767 mCurrentUserId); 768 769 for (int i = 0, count = installedServices.size(); i < count; i++) { 770 ResolveInfo resolveInfo = installedServices.get(i); 771 ServiceInfo serviceInfo = resolveInfo.serviceInfo; 772 if (!android.Manifest.permission.BIND_ACCESSIBILITY_SERVICE.equals( 773 serviceInfo.permission)) { 774 Slog.w(LOG_TAG, "Skipping accessibilty service " + new ComponentName( 775 serviceInfo.packageName, serviceInfo.name).flattenToShortString() 776 + ": it does not require the permission " 777 + android.Manifest.permission.BIND_ACCESSIBILITY_SERVICE); 778 continue; 779 } 780 AccessibilityServiceInfo accessibilityServiceInfo; 781 try { 782 accessibilityServiceInfo = new AccessibilityServiceInfo(resolveInfo, mContext); 783 userState.mInstalledServices.add(accessibilityServiceInfo); 784 } catch (XmlPullParserException xppe) { 785 Slog.e(LOG_TAG, "Error while initializing AccessibilityServiceInfo", xppe); 786 } catch (IOException ioe) { 787 Slog.e(LOG_TAG, "Error while initializing AccessibilityServiceInfo", ioe); 788 } 789 } 790 } 791 792 private void populateEnabledAccessibilityServicesLocked(UserState userState) { 793 populateComponentNamesFromSettingLocked( 794 Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, 795 userState.mUserId, 796 userState.mEnabledServices); 797 } 798 799 private void populateTouchExplorationGrantedAccessibilityServicesLocked( 800 UserState userState) { 801 populateComponentNamesFromSettingLocked( 802 Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES, 803 userState.mUserId, 804 userState.mTouchExplorationGrantedServices); 805 } 806 807 /** 808 * Performs {@link AccessibilityService}s delayed notification. The delay is configurable 809 * and denotes the period after the last event before notifying the service. 810 * 811 * @param event The event. 812 * @param isDefault True to notify default listeners, not default services. 813 */ 814 private void notifyAccessibilityServicesDelayedLocked(AccessibilityEvent event, 815 boolean isDefault) { 816 try { 817 UserState state = getCurrentUserStateLocked(); 818 for (int i = 0, count = state.mServices.size(); i < count; i++) { 819 Service service = state.mServices.get(i); 820 821 if (service.mIsDefault == isDefault) { 822 if (canDispathEventLocked(service, event, state.mHandledFeedbackTypes)) { 823 state.mHandledFeedbackTypes |= service.mFeedbackType; 824 service.notifyAccessibilityEvent(event); 825 } 826 } 827 } 828 } catch (IndexOutOfBoundsException oobe) { 829 // An out of bounds exception can happen if services are going away 830 // as the for loop is running. If that happens, just bail because 831 // there are no more services to notify. 832 return; 833 } 834 } 835 836 /** 837 * Adds a service for a user. 838 * 839 * @param service The service to add. 840 * @param userId The user id. 841 */ 842 private void tryAddServiceLocked(Service service, int userId) { 843 try { 844 UserState userState = getUserStateLocked(userId); 845 if (userState.mServices.contains(service)) { 846 return; 847 } 848 service.linkToOwnDeath(); 849 userState.mServices.add(service); 850 userState.mComponentNameToServiceMap.put(service.mComponentName, service); 851 updateInputFilterLocked(userState); 852 tryEnableTouchExplorationLocked(service); 853 } catch (RemoteException e) { 854 /* do nothing */ 855 } 856 } 857 858 /** 859 * Removes a service. 860 * 861 * @param service The service. 862 * @return True if the service was removed, false otherwise. 863 */ 864 private boolean tryRemoveServiceLocked(Service service) { 865 UserState userState = getUserStateLocked(service.mUserId); 866 final boolean removed = userState.mServices.remove(service); 867 if (!removed) { 868 return false; 869 } 870 userState.mComponentNameToServiceMap.remove(service.mComponentName); 871 service.unlinkToOwnDeath(); 872 service.dispose(); 873 updateInputFilterLocked(userState); 874 tryDisableTouchExplorationLocked(service); 875 return removed; 876 } 877 878 /** 879 * Determines if given event can be dispatched to a service based on the package of the 880 * event source and already notified services for that event type. Specifically, a 881 * service is notified if it is interested in events from the package and no other service 882 * providing the same feedback type has been notified. Exception are services the 883 * provide generic feedback (feedback type left as a safety net for unforeseen feedback 884 * types) which are always notified. 885 * 886 * @param service The potential receiver. 887 * @param event The event. 888 * @param handledFeedbackTypes The feedback types for which services have been notified. 889 * @return True if the listener should be notified, false otherwise. 890 */ 891 private boolean canDispathEventLocked(Service service, AccessibilityEvent event, 892 int handledFeedbackTypes) { 893 894 if (!service.canReceiveEvents()) { 895 return false; 896 } 897 898 if (!event.isImportantForAccessibility() 899 && !service.mIncludeNotImportantViews) { 900 return false; 901 } 902 903 int eventType = event.getEventType(); 904 if ((service.mEventTypes & eventType) != eventType) { 905 return false; 906 } 907 908 Set<String> packageNames = service.mPackageNames; 909 CharSequence packageName = event.getPackageName(); 910 911 if (packageNames.isEmpty() || packageNames.contains(packageName)) { 912 int feedbackType = service.mFeedbackType; 913 if ((handledFeedbackTypes & feedbackType) != feedbackType 914 || feedbackType == AccessibilityServiceInfo.FEEDBACK_GENERIC) { 915 return true; 916 } 917 } 918 919 return false; 920 } 921 922 /** 923 * Manages services by starting enabled ones and stopping disabled ones. 924 */ 925 private void manageServicesLocked(UserState userState) { 926 final int enabledInstalledServicesCount = updateServicesStateLocked(userState); 927 // No enabled installed services => disable accessibility to avoid 928 // sending accessibility events with no recipient across processes. 929 if (userState.mIsAccessibilityEnabled && enabledInstalledServicesCount == 0) { 930 Settings.Secure.putIntForUser(mContext.getContentResolver(), 931 Settings.Secure.ACCESSIBILITY_ENABLED, 0, userState.mUserId); 932 } 933 } 934 935 /** 936 * Unbinds all bound services for a user. 937 * 938 * @param userState The user state. 939 */ 940 private void unbindAllServicesLocked(UserState userState) { 941 List<Service> services = userState.mServices; 942 for (int i = 0, count = services.size(); i < count; i++) { 943 Service service = services.get(i); 944 if (service.unbind()) { 945 i--; 946 count--; 947 } 948 } 949 } 950 951 /** 952 * Populates a set with the {@link ComponentName}s stored in a colon 953 * separated value setting for a given user. 954 * 955 * @param settingName The setting to parse. 956 * @param userId The user id. 957 * @param outComponentNames The output component names. 958 */ 959 private void populateComponentNamesFromSettingLocked(String settingName, int userId, 960 Set<ComponentName> outComponentNames) { 961 String settingValue = Settings.Secure.getStringForUser(mContext.getContentResolver(), 962 settingName, userId); 963 outComponentNames.clear(); 964 if (settingValue != null) { 965 TextUtils.SimpleStringSplitter splitter = mStringColonSplitter; 966 splitter.setString(settingValue); 967 while (splitter.hasNext()) { 968 String str = splitter.next(); 969 if (str == null || str.length() <= 0) { 970 continue; 971 } 972 ComponentName enabledService = ComponentName.unflattenFromString(str); 973 if (enabledService != null) { 974 outComponentNames.add(enabledService); 975 } 976 } 977 } 978 } 979 980 /** 981 * Persists the component names in the specified setting in a 982 * colon separated fashion. 983 * 984 * @param settingName The setting name. 985 * @param componentNames The component names. 986 */ 987 private void persistComponentNamesToSettingLocked(String settingName, 988 Set<ComponentName> componentNames, int userId) { 989 StringBuilder builder = new StringBuilder(); 990 for (ComponentName componentName : componentNames) { 991 if (builder.length() > 0) { 992 builder.append(COMPONENT_NAME_SEPARATOR); 993 } 994 builder.append(componentName.flattenToShortString()); 995 } 996 Settings.Secure.putStringForUser(mContext.getContentResolver(), 997 settingName, builder.toString(), userId); 998 } 999 1000 /** 1001 * Updates the state of each service by starting (or keeping running) enabled ones and 1002 * stopping the rest. 1003 * 1004 * @param userState The user state for which to do that. 1005 * @return The number of enabled installed services. 1006 */ 1007 private int updateServicesStateLocked(UserState userState) { 1008 Map<ComponentName, Service> componentNameToServiceMap = 1009 userState.mComponentNameToServiceMap; 1010 boolean isEnabled = userState.mIsAccessibilityEnabled; 1011 1012 int enabledInstalledServices = 0; 1013 for (int i = 0, count = userState.mInstalledServices.size(); i < count; i++) { 1014 AccessibilityServiceInfo installedService = userState.mInstalledServices.get(i); 1015 ComponentName componentName = ComponentName.unflattenFromString( 1016 installedService.getId()); 1017 Service service = componentNameToServiceMap.get(componentName); 1018 1019 if (isEnabled) { 1020 if (userState.mEnabledServices.contains(componentName)) { 1021 if (service == null) { 1022 service = new Service(userState.mUserId, componentName, 1023 installedService, false); 1024 } 1025 service.bind(); 1026 enabledInstalledServices++; 1027 } else { 1028 if (service != null) { 1029 service.unbind(); 1030 } 1031 } 1032 } else { 1033 if (service != null) { 1034 service.unbind(); 1035 } 1036 } 1037 } 1038 1039 return enabledInstalledServices; 1040 } 1041 1042 private void scheduleSendStateToClientsLocked(UserState userState) { 1043 if (mGlobalClients.getRegisteredCallbackCount() > 0 1044 || userState.mClients.getRegisteredCallbackCount() > 0) { 1045 final int clientState = getClientState(userState); 1046 mMainHandler.obtainMessage(MainHandler.MSG_SEND_STATE_TO_CLIENTS, 1047 clientState, userState.mUserId) .sendToTarget(); 1048 } 1049 } 1050 1051 private void updateInputFilterLocked(UserState userState) { 1052 boolean setInputFilter = false; 1053 AccessibilityInputFilter inputFilter = null; 1054 synchronized (mLock) { 1055 if ((userState.mIsAccessibilityEnabled && userState.mIsTouchExplorationEnabled) 1056 || userState.mIsDisplayMagnificationEnabled) { 1057 if (!mHasInputFilter) { 1058 mHasInputFilter = true; 1059 if (mInputFilter == null) { 1060 mInputFilter = new AccessibilityInputFilter(mContext, 1061 AccessibilityManagerService.this); 1062 } 1063 inputFilter = mInputFilter; 1064 setInputFilter = true; 1065 } 1066 int flags = 0; 1067 if (userState.mIsDisplayMagnificationEnabled) { 1068 flags |= AccessibilityInputFilter.FLAG_FEATURE_SCREEN_MAGNIFIER; 1069 } 1070 if (userState.mIsTouchExplorationEnabled) { 1071 flags |= AccessibilityInputFilter.FLAG_FEATURE_TOUCH_EXPLORATION; 1072 } 1073 mInputFilter.setEnabledFeatures(flags); 1074 } else { 1075 if (mHasInputFilter) { 1076 mHasInputFilter = false; 1077 mInputFilter.setEnabledFeatures(0); 1078 inputFilter = null; 1079 setInputFilter = true; 1080 } 1081 } 1082 } 1083 if (setInputFilter) { 1084 try { 1085 mWindowManagerService.setInputFilter(inputFilter); 1086 } catch (RemoteException re) { 1087 /* ignore */ 1088 } 1089 } 1090 } 1091 1092 private void showEnableTouchExplorationDialog(final Service service) { 1093 String label = service.mResolveInfo.loadLabel( 1094 mContext.getPackageManager()).toString(); 1095 synchronized (mLock) { 1096 final UserState state = getCurrentUserStateLocked(); 1097 if (state.mIsTouchExplorationEnabled) { 1098 return; 1099 } 1100 if (mEnableTouchExplorationDialog != null 1101 && mEnableTouchExplorationDialog.isShowing()) { 1102 return; 1103 } 1104 mEnableTouchExplorationDialog = new AlertDialog.Builder(mContext) 1105 .setIcon(android.R.drawable.ic_dialog_alert) 1106 .setPositiveButton(android.R.string.ok, new OnClickListener() { 1107 @Override 1108 public void onClick(DialogInterface dialog, int which) { 1109 // The user allowed the service to toggle touch exploration. 1110 state.mTouchExplorationGrantedServices.add(service.mComponentName); 1111 persistComponentNamesToSettingLocked( 1112 Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES, 1113 state.mTouchExplorationGrantedServices, state.mUserId); 1114 // Enable touch exploration. 1115 Settings.Secure.putIntForUser(mContext.getContentResolver(), 1116 Settings.Secure.TOUCH_EXPLORATION_ENABLED, 1, 1117 service.mUserId); 1118 } 1119 }) 1120 .setNegativeButton(android.R.string.cancel, new OnClickListener() { 1121 @Override 1122 public void onClick(DialogInterface dialog, int which) { 1123 dialog.dismiss(); 1124 } 1125 }) 1126 .setTitle(R.string.enable_explore_by_touch_warning_title) 1127 .setMessage(mContext.getString( 1128 R.string.enable_explore_by_touch_warning_message, label)) 1129 .create(); 1130 mEnableTouchExplorationDialog.getWindow().setType( 1131 WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); 1132 mEnableTouchExplorationDialog.getWindow().getAttributes().privateFlags 1133 |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS; 1134 mEnableTouchExplorationDialog.setCanceledOnTouchOutside(true); 1135 mEnableTouchExplorationDialog.show(); 1136 } 1137 } 1138 1139 private int getClientState(UserState userState) { 1140 int clientState = 0; 1141 if (userState.mIsAccessibilityEnabled) { 1142 clientState |= AccessibilityManager.STATE_FLAG_ACCESSIBILITY_ENABLED; 1143 } 1144 // Touch exploration relies on enabled accessibility. 1145 if (userState.mIsAccessibilityEnabled && userState.mIsTouchExplorationEnabled) { 1146 clientState |= AccessibilityManager.STATE_FLAG_TOUCH_EXPLORATION_ENABLED; 1147 } 1148 return clientState; 1149 } 1150 1151 private void recreateInternalStateLocked(UserState userState) { 1152 populateInstalledAccessibilityServiceLocked(userState); 1153 populateEnabledAccessibilityServicesLocked(userState); 1154 populateTouchExplorationGrantedAccessibilityServicesLocked(userState); 1155 1156 handleTouchExplorationEnabledSettingChangedLocked(userState); 1157 handleDisplayMagnificationEnabledSettingChangedLocked(userState); 1158 handleAccessibilityEnabledSettingChangedLocked(userState); 1159 1160 performServiceManagementLocked(userState); 1161 updateInputFilterLocked(userState); 1162 scheduleSendStateToClientsLocked(userState); 1163 } 1164 1165 private void handleAccessibilityEnabledSettingChangedLocked(UserState userState) { 1166 userState.mIsAccessibilityEnabled = Settings.Secure.getIntForUser( 1167 mContext.getContentResolver(), 1168 Settings.Secure.ACCESSIBILITY_ENABLED, 0, userState.mUserId) == 1; 1169 } 1170 1171 private void performServiceManagementLocked(UserState userState) { 1172 if (userState.mIsAccessibilityEnabled ) { 1173 manageServicesLocked(userState); 1174 } else { 1175 unbindAllServicesLocked(userState); 1176 } 1177 } 1178 1179 private void handleTouchExplorationEnabledSettingChangedLocked(UserState userState) { 1180 userState.mIsTouchExplorationEnabled = Settings.Secure.getIntForUser( 1181 mContext.getContentResolver(), 1182 Settings.Secure.TOUCH_EXPLORATION_ENABLED, 0, userState.mUserId) == 1; 1183 } 1184 1185 private void handleDisplayMagnificationEnabledSettingChangedLocked(UserState userState) { 1186 userState.mIsDisplayMagnificationEnabled = Settings.Secure.getIntForUser( 1187 mContext.getContentResolver(), 1188 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED, 1189 0, userState.mUserId) == 1; 1190 } 1191 1192 private void handleTouchExplorationGrantedAccessibilityServicesChangedLocked( 1193 UserState userState) { 1194 final int serviceCount = userState.mServices.size(); 1195 for (int i = 0; i < serviceCount; i++) { 1196 Service service = userState.mServices.get(i); 1197 if (service.mRequestTouchExplorationMode 1198 && userState.mTouchExplorationGrantedServices.contains( 1199 service.mComponentName)) { 1200 tryEnableTouchExplorationLocked(service); 1201 return; 1202 } 1203 } 1204 if (userState.mIsTouchExplorationEnabled) { 1205 Settings.Secure.putIntForUser(mContext.getContentResolver(), 1206 Settings.Secure.TOUCH_EXPLORATION_ENABLED, 0, userState.mUserId); 1207 } 1208 } 1209 1210 private void tryEnableTouchExplorationLocked(final Service service) { 1211 UserState userState = getUserStateLocked(service.mUserId); 1212 if (!userState.mIsTouchExplorationEnabled && service.mRequestTouchExplorationMode 1213 && service.canReceiveEvents()) { 1214 final boolean canToggleTouchExploration = 1215 userState.mTouchExplorationGrantedServices.contains(service.mComponentName); 1216 if (!service.mIsAutomation && !canToggleTouchExploration) { 1217 showEnableTouchExplorationDialog(service); 1218 } else { 1219 Settings.Secure.putIntForUser(mContext.getContentResolver(), 1220 Settings.Secure.TOUCH_EXPLORATION_ENABLED, 1, userState.mUserId); 1221 } 1222 } 1223 } 1224 1225 private void tryDisableTouchExplorationLocked(Service service) { 1226 UserState userState = getUserStateLocked(service.mUserId); 1227 if (userState.mIsTouchExplorationEnabled) { 1228 final int serviceCount = userState.mServices.size(); 1229 for (int i = 0; i < serviceCount; i++) { 1230 Service other = userState.mServices.get(i); 1231 if (other != service && other.mRequestTouchExplorationMode) { 1232 return; 1233 } 1234 } 1235 Settings.Secure.putIntForUser(mContext.getContentResolver(), 1236 Settings.Secure.TOUCH_EXPLORATION_ENABLED, 0, userState.mUserId); 1237 } 1238 } 1239 1240 private class AccessibilityConnectionWrapper implements DeathRecipient { 1241 private final int mWindowId; 1242 private final int mUserId; 1243 private final IAccessibilityInteractionConnection mConnection; 1244 1245 public AccessibilityConnectionWrapper(int windowId, 1246 IAccessibilityInteractionConnection connection, int userId) { 1247 mWindowId = windowId; 1248 mUserId = userId; 1249 mConnection = connection; 1250 } 1251 1252 public void linkToDeath() throws RemoteException { 1253 mConnection.asBinder().linkToDeath(this, 0); 1254 } 1255 1256 public void unlinkToDeath() { 1257 mConnection.asBinder().unlinkToDeath(this, 0); 1258 } 1259 1260 @Override 1261 public void binderDied() { 1262 unlinkToDeath(); 1263 synchronized (mLock) { 1264 removeAccessibilityInteractionConnectionLocked(mWindowId, mUserId); 1265 } 1266 } 1267 } 1268 1269 private final class MainHandler extends Handler { 1270 public static final int MSG_SEND_ACCESSIBILITY_EVENT_TO_INPUT_FILTER = 1; 1271 public static final int MSG_SEND_STATE_TO_CLIENTS = 2; 1272 public static final int MSG_SEND_CLEARED_STATE_TO_CLIENTS_FOR_USER = 3; 1273 public static final int MSG_SEND_RECREATE_INTERNAL_STATE = 4; 1274 public static final int MSG_UPDATE_ACTIVE_WINDOW = 5; 1275 public static final int MSG_ANNOUNCE_NEW_USER_IF_NEEDED = 6; 1276 1277 public MainHandler(Looper looper) { 1278 super(looper); 1279 } 1280 1281 @Override 1282 public void handleMessage(Message msg) { 1283 final int type = msg.what; 1284 switch (type) { 1285 case MSG_SEND_ACCESSIBILITY_EVENT_TO_INPUT_FILTER: { 1286 AccessibilityEvent event = (AccessibilityEvent) msg.obj; 1287 synchronized (mLock) { 1288 if (mHasInputFilter && mInputFilter != null) { 1289 mInputFilter.notifyAccessibilityEvent(event); 1290 } 1291 } 1292 event.recycle(); 1293 } break; 1294 case MSG_SEND_STATE_TO_CLIENTS: { 1295 final int clientState = msg.arg1; 1296 final int userId = msg.arg2; 1297 sendStateToClients(clientState, mGlobalClients); 1298 sendStateToClientsForUser(clientState, userId); 1299 } break; 1300 case MSG_SEND_CLEARED_STATE_TO_CLIENTS_FOR_USER: { 1301 final int userId = msg.arg1; 1302 sendStateToClientsForUser(0, userId); 1303 } break; 1304 case MSG_SEND_RECREATE_INTERNAL_STATE: { 1305 final int userId = msg.arg1; 1306 synchronized (mLock) { 1307 UserState userState = getUserStateLocked(userId); 1308 recreateInternalStateLocked(userState); 1309 } 1310 } break; 1311 case MSG_UPDATE_ACTIVE_WINDOW: { 1312 final int windowId = msg.arg1; 1313 final int eventType = msg.arg2; 1314 mSecurityPolicy.updateActiveWindow(windowId, eventType); 1315 } break; 1316 case MSG_ANNOUNCE_NEW_USER_IF_NEEDED: { 1317 announceNewUserIfNeeded(); 1318 } break; 1319 } 1320 } 1321 1322 private void announceNewUserIfNeeded() { 1323 synchronized (mLock) { 1324 UserState userState = getCurrentUserStateLocked(); 1325 if (userState.mIsAccessibilityEnabled) { 1326 UserManager userManager = (UserManager) mContext.getSystemService( 1327 Context.USER_SERVICE); 1328 String message = mContext.getString(R.string.user_switched, 1329 userManager.getUserInfo(mCurrentUserId).name); 1330 AccessibilityEvent event = AccessibilityEvent.obtain( 1331 AccessibilityEvent.TYPE_ANNOUNCEMENT); 1332 event.getText().add(message); 1333 event.setWindowId(mSecurityPolicy.getRetrievalAllowingWindowLocked()); 1334 sendAccessibilityEvent(event, mCurrentUserId); 1335 } 1336 } 1337 } 1338 1339 private void sendStateToClientsForUser(int clientState, int userId) { 1340 final UserState userState; 1341 synchronized (mLock) { 1342 userState = getUserStateLocked(userId); 1343 } 1344 sendStateToClients(clientState, userState.mClients); 1345 } 1346 1347 private void sendStateToClients(int clientState, 1348 RemoteCallbackList<IAccessibilityManagerClient> clients) { 1349 try { 1350 final int userClientCount = clients.beginBroadcast(); 1351 for (int i = 0; i < userClientCount; i++) { 1352 IAccessibilityManagerClient client = clients.getBroadcastItem(i); 1353 try { 1354 client.setState(clientState); 1355 } catch (RemoteException re) { 1356 /* ignore */ 1357 } 1358 } 1359 } finally { 1360 clients.finishBroadcast(); 1361 } 1362 } 1363 } 1364 1365 /** 1366 * This class represents an accessibility service. It stores all per service 1367 * data required for the service management, provides API for starting/stopping the 1368 * service and is responsible for adding/removing the service in the data structures 1369 * for service management. The class also exposes configuration interface that is 1370 * passed to the service it represents as soon it is bound. It also serves as the 1371 * connection for the service. 1372 */ 1373 class Service extends IAccessibilityServiceConnection.Stub 1374 implements ServiceConnection, DeathRecipient { 1375 1376 // We pick the MSB to avoid collision since accessibility event types are 1377 // used as message types allowing us to remove messages per event type. 1378 private static final int MSG_ON_GESTURE = 0x80000000; 1379 1380 final int mUserId; 1381 1382 int mId = 0; 1383 1384 AccessibilityServiceInfo mAccessibilityServiceInfo; 1385 1386 IBinder mService; 1387 1388 IAccessibilityServiceClient mServiceInterface; 1389 1390 int mEventTypes; 1391 1392 int mFeedbackType; 1393 1394 Set<String> mPackageNames = new HashSet<String>(); 1395 1396 boolean mIsDefault; 1397 1398 boolean mRequestTouchExplorationMode; 1399 1400 boolean mIncludeNotImportantViews; 1401 1402 long mNotificationTimeout; 1403 1404 ComponentName mComponentName; 1405 1406 Intent mIntent; 1407 1408 boolean mCanRetrieveScreenContent; 1409 1410 boolean mIsAutomation; 1411 1412 final Rect mTempBounds = new Rect(); 1413 1414 final ResolveInfo mResolveInfo; 1415 1416 // the events pending events to be dispatched to this service 1417 final SparseArray<AccessibilityEvent> mPendingEvents = 1418 new SparseArray<AccessibilityEvent>(); 1419 1420 /** 1421 * Handler for delayed event dispatch. 1422 */ 1423 public Handler mHandler = new Handler(mMainHandler.getLooper()) { 1424 @Override 1425 public void handleMessage(Message message) { 1426 final int type = message.what; 1427 switch (type) { 1428 case MSG_ON_GESTURE: { 1429 final int gestureId = message.arg1; 1430 notifyGestureInternal(gestureId); 1431 } break; 1432 default: { 1433 final int eventType = type; 1434 notifyAccessibilityEventInternal(eventType); 1435 } break; 1436 } 1437 } 1438 }; 1439 1440 public Service(int userId, ComponentName componentName, 1441 AccessibilityServiceInfo accessibilityServiceInfo, boolean isAutomation) { 1442 mUserId = userId; 1443 mResolveInfo = accessibilityServiceInfo.getResolveInfo(); 1444 mId = sIdCounter++; 1445 mComponentName = componentName; 1446 mAccessibilityServiceInfo = accessibilityServiceInfo; 1447 mIsAutomation = isAutomation; 1448 if (!isAutomation) { 1449 mCanRetrieveScreenContent = accessibilityServiceInfo.getCanRetrieveWindowContent(); 1450 mRequestTouchExplorationMode = 1451 (accessibilityServiceInfo.flags 1452 & AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE) != 0; 1453 mIntent = new Intent().setComponent(mComponentName); 1454 mIntent.putExtra(Intent.EXTRA_CLIENT_LABEL, 1455 com.android.internal.R.string.accessibility_binding_label); 1456 mIntent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity( 1457 mContext, 0, new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS), 0)); 1458 } else { 1459 mCanRetrieveScreenContent = true; 1460 } 1461 setDynamicallyConfigurableProperties(accessibilityServiceInfo); 1462 } 1463 1464 public void setDynamicallyConfigurableProperties(AccessibilityServiceInfo info) { 1465 mEventTypes = info.eventTypes; 1466 mFeedbackType = info.feedbackType; 1467 String[] packageNames = info.packageNames; 1468 if (packageNames != null) { 1469 mPackageNames.addAll(Arrays.asList(packageNames)); 1470 } 1471 mNotificationTimeout = info.notificationTimeout; 1472 mIsDefault = (info.flags & DEFAULT) != 0; 1473 1474 if (mIsAutomation || info.getResolveInfo().serviceInfo.applicationInfo.targetSdkVersion 1475 >= Build.VERSION_CODES.JELLY_BEAN) { 1476 mIncludeNotImportantViews = 1477 (info.flags & FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0; 1478 } 1479 1480 mRequestTouchExplorationMode = (info.flags 1481 & AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE) != 0; 1482 1483 // If this service is up and running we may have to enable touch 1484 // exploration, otherwise this will happen when the service connects. 1485 synchronized (mLock) { 1486 if (canReceiveEvents()) { 1487 if (mRequestTouchExplorationMode) { 1488 tryEnableTouchExplorationLocked(this); 1489 } else { 1490 tryDisableTouchExplorationLocked(this); 1491 } 1492 } 1493 } 1494 } 1495 1496 /** 1497 * Binds to the accessibility service. 1498 * 1499 * @return True if binding is successful. 1500 */ 1501 public boolean bind() { 1502 if (!mIsAutomation && mService == null) { 1503 return mContext.bindService(mIntent, this, Context.BIND_AUTO_CREATE, mUserId); 1504 } 1505 return false; 1506 } 1507 1508 /** 1509 * Unbinds form the accessibility service and removes it from the data 1510 * structures for service management. 1511 * 1512 * @return True if unbinding is successful. 1513 */ 1514 public boolean unbind() { 1515 if (mService != null) { 1516 synchronized (mLock) { 1517 tryRemoveServiceLocked(this); 1518 } 1519 if (!mIsAutomation) { 1520 mContext.unbindService(this); 1521 } 1522 return true; 1523 } 1524 return false; 1525 } 1526 1527 public boolean canReceiveEvents() { 1528 return (mEventTypes != 0 && mFeedbackType != 0 && mService != null); 1529 } 1530 1531 @Override 1532 public AccessibilityServiceInfo getServiceInfo() { 1533 synchronized (mLock) { 1534 return mAccessibilityServiceInfo; 1535 } 1536 } 1537 1538 @Override 1539 public void setServiceInfo(AccessibilityServiceInfo info) { 1540 final long identity = Binder.clearCallingIdentity(); 1541 try { 1542 synchronized (mLock) { 1543 // If the XML manifest had data to configure the service its info 1544 // should be already set. In such a case update only the dynamically 1545 // configurable properties. 1546 AccessibilityServiceInfo oldInfo = mAccessibilityServiceInfo; 1547 if (oldInfo != null) { 1548 oldInfo.updateDynamicallyConfigurableProperties(info); 1549 setDynamicallyConfigurableProperties(oldInfo); 1550 } else { 1551 setDynamicallyConfigurableProperties(info); 1552 } 1553 } 1554 } finally { 1555 Binder.restoreCallingIdentity(identity); 1556 } 1557 } 1558 1559 @Override 1560 public void onServiceConnected(ComponentName componentName, IBinder service) { 1561 mService = service; 1562 mServiceInterface = IAccessibilityServiceClient.Stub.asInterface(service); 1563 try { 1564 mServiceInterface.setConnection(this, mId); 1565 synchronized (mLock) { 1566 tryAddServiceLocked(this, mUserId); 1567 } 1568 } catch (RemoteException re) { 1569 Slog.w(LOG_TAG, "Error while setting Controller for service: " + service, re); 1570 } 1571 } 1572 1573 @Override 1574 public float findAccessibilityNodeInfoByViewId(int accessibilityWindowId, 1575 long accessibilityNodeId, int viewId, int interactionId, 1576 IAccessibilityInteractionConnectionCallback callback, long interrogatingTid) 1577 throws RemoteException { 1578 final int resolvedWindowId; 1579 IAccessibilityInteractionConnection connection = null; 1580 synchronized (mLock) { 1581 final int resolvedUserId = mSecurityPolicy 1582 .resolveCallingUserIdEnforcingPermissionsLocked( 1583 UserHandle.getCallingUserId()); 1584 if (resolvedUserId != mCurrentUserId) { 1585 return -1; 1586 } 1587 mSecurityPolicy.enforceCanRetrieveWindowContent(this); 1588 final boolean permissionGranted = mSecurityPolicy.canRetrieveWindowContent(this); 1589 if (!permissionGranted) { 1590 return 0; 1591 } else { 1592 resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId); 1593 connection = getConnectionLocked(resolvedWindowId); 1594 if (connection == null) { 1595 return 0; 1596 } 1597 } 1598 } 1599 final int flags = (mIncludeNotImportantViews) ? 1600 AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0; 1601 final int interrogatingPid = Binder.getCallingPid(); 1602 final long identityToken = Binder.clearCallingIdentity(); 1603 try { 1604 connection.findAccessibilityNodeInfoByViewId(accessibilityNodeId, viewId, 1605 interactionId, callback, flags, interrogatingPid, interrogatingTid); 1606 return getCompatibilityScale(resolvedWindowId); 1607 } catch (RemoteException re) { 1608 if (DEBUG) { 1609 Slog.e(LOG_TAG, "Error findAccessibilityNodeInfoByViewId()."); 1610 } 1611 } finally { 1612 Binder.restoreCallingIdentity(identityToken); 1613 } 1614 return 0; 1615 } 1616 1617 @Override 1618 public float findAccessibilityNodeInfosByText(int accessibilityWindowId, 1619 long accessibilityNodeId, String text, int interactionId, 1620 IAccessibilityInteractionConnectionCallback callback, long interrogatingTid) 1621 throws RemoteException { 1622 final int resolvedWindowId; 1623 IAccessibilityInteractionConnection connection = null; 1624 synchronized (mLock) { 1625 final int resolvedUserId = mSecurityPolicy 1626 .resolveCallingUserIdEnforcingPermissionsLocked( 1627 UserHandle.getCallingUserId()); 1628 if (resolvedUserId != mCurrentUserId) { 1629 return -1; 1630 } 1631 mSecurityPolicy.enforceCanRetrieveWindowContent(this); 1632 resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId); 1633 final boolean permissionGranted = 1634 mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId); 1635 if (!permissionGranted) { 1636 return 0; 1637 } else { 1638 connection = getConnectionLocked(resolvedWindowId); 1639 if (connection == null) { 1640 return 0; 1641 } 1642 } 1643 } 1644 final int flags = (mIncludeNotImportantViews) ? 1645 AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0; 1646 final int interrogatingPid = Binder.getCallingPid(); 1647 final long identityToken = Binder.clearCallingIdentity(); 1648 try { 1649 connection.findAccessibilityNodeInfosByText(accessibilityNodeId, text, 1650 interactionId, callback, flags, interrogatingPid, 1651 interrogatingTid); 1652 return getCompatibilityScale(resolvedWindowId); 1653 } catch (RemoteException re) { 1654 if (DEBUG) { 1655 Slog.e(LOG_TAG, "Error calling findAccessibilityNodeInfosByText()"); 1656 } 1657 } finally { 1658 Binder.restoreCallingIdentity(identityToken); 1659 } 1660 return 0; 1661 } 1662 1663 @Override 1664 public float findAccessibilityNodeInfoByAccessibilityId(int accessibilityWindowId, 1665 long accessibilityNodeId, int interactionId, 1666 IAccessibilityInteractionConnectionCallback callback, int flags, 1667 long interrogatingTid) throws RemoteException { 1668 final int resolvedWindowId; 1669 IAccessibilityInteractionConnection connection = null; 1670 synchronized (mLock) { 1671 final int resolvedUserId = mSecurityPolicy 1672 .resolveCallingUserIdEnforcingPermissionsLocked( 1673 UserHandle.getCallingUserId()); 1674 if (resolvedUserId != mCurrentUserId) { 1675 return -1; 1676 } 1677 mSecurityPolicy.enforceCanRetrieveWindowContent(this); 1678 resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId); 1679 final boolean permissionGranted = 1680 mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId); 1681 if (!permissionGranted) { 1682 return 0; 1683 } else { 1684 connection = getConnectionLocked(resolvedWindowId); 1685 if (connection == null) { 1686 return 0; 1687 } 1688 } 1689 } 1690 final int allFlags = flags | ((mIncludeNotImportantViews) ? 1691 AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0); 1692 final int interrogatingPid = Binder.getCallingPid(); 1693 final long identityToken = Binder.clearCallingIdentity(); 1694 try { 1695 connection.findAccessibilityNodeInfoByAccessibilityId(accessibilityNodeId, 1696 interactionId, callback, allFlags, interrogatingPid, interrogatingTid); 1697 return getCompatibilityScale(resolvedWindowId); 1698 } catch (RemoteException re) { 1699 if (DEBUG) { 1700 Slog.e(LOG_TAG, "Error calling findAccessibilityNodeInfoByAccessibilityId()"); 1701 } 1702 } finally { 1703 Binder.restoreCallingIdentity(identityToken); 1704 } 1705 return 0; 1706 } 1707 1708 @Override 1709 public float findFocus(int accessibilityWindowId, long accessibilityNodeId, 1710 int focusType, int interactionId, 1711 IAccessibilityInteractionConnectionCallback callback, long interrogatingTid) 1712 throws RemoteException { 1713 final int resolvedWindowId; 1714 IAccessibilityInteractionConnection connection = null; 1715 synchronized (mLock) { 1716 final int resolvedUserId = mSecurityPolicy 1717 .resolveCallingUserIdEnforcingPermissionsLocked( 1718 UserHandle.getCallingUserId()); 1719 if (resolvedUserId != mCurrentUserId) { 1720 return -1; 1721 } 1722 mSecurityPolicy.enforceCanRetrieveWindowContent(this); 1723 resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId); 1724 final boolean permissionGranted = 1725 mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId); 1726 if (!permissionGranted) { 1727 return 0; 1728 } else { 1729 connection = getConnectionLocked(resolvedWindowId); 1730 if (connection == null) { 1731 return 0; 1732 } 1733 } 1734 } 1735 final int flags = (mIncludeNotImportantViews) ? 1736 AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0; 1737 final int interrogatingPid = Binder.getCallingPid(); 1738 final long identityToken = Binder.clearCallingIdentity(); 1739 try { 1740 connection.findFocus(accessibilityNodeId, focusType, interactionId, callback, 1741 flags, interrogatingPid, interrogatingTid); 1742 return getCompatibilityScale(resolvedWindowId); 1743 } catch (RemoteException re) { 1744 if (DEBUG) { 1745 Slog.e(LOG_TAG, "Error calling findAccessibilityFocus()"); 1746 } 1747 } finally { 1748 Binder.restoreCallingIdentity(identityToken); 1749 } 1750 return 0; 1751 } 1752 1753 @Override 1754 public float focusSearch(int accessibilityWindowId, long accessibilityNodeId, 1755 int direction, int interactionId, 1756 IAccessibilityInteractionConnectionCallback callback, long interrogatingTid) 1757 throws RemoteException { 1758 final int resolvedWindowId; 1759 IAccessibilityInteractionConnection connection = null; 1760 synchronized (mLock) { 1761 final int resolvedUserId = mSecurityPolicy 1762 .resolveCallingUserIdEnforcingPermissionsLocked( 1763 UserHandle.getCallingUserId()); 1764 if (resolvedUserId != mCurrentUserId) { 1765 return -1; 1766 } 1767 mSecurityPolicy.enforceCanRetrieveWindowContent(this); 1768 resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId); 1769 final boolean permissionGranted = 1770 mSecurityPolicy.canGetAccessibilityNodeInfoLocked(this, resolvedWindowId); 1771 if (!permissionGranted) { 1772 return 0; 1773 } else { 1774 connection = getConnectionLocked(resolvedWindowId); 1775 if (connection == null) { 1776 return 0; 1777 } 1778 } 1779 } 1780 final int flags = (mIncludeNotImportantViews) ? 1781 AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0; 1782 final int interrogatingPid = Binder.getCallingPid(); 1783 final long identityToken = Binder.clearCallingIdentity(); 1784 try { 1785 connection.focusSearch(accessibilityNodeId, direction, interactionId, callback, 1786 flags, interrogatingPid, interrogatingTid); 1787 return getCompatibilityScale(resolvedWindowId); 1788 } catch (RemoteException re) { 1789 if (DEBUG) { 1790 Slog.e(LOG_TAG, "Error calling accessibilityFocusSearch()"); 1791 } 1792 } finally { 1793 Binder.restoreCallingIdentity(identityToken); 1794 } 1795 return 0; 1796 } 1797 1798 @Override 1799 public boolean performAccessibilityAction(int accessibilityWindowId, 1800 long accessibilityNodeId, int action, Bundle arguments, int interactionId, 1801 IAccessibilityInteractionConnectionCallback callback, long interrogatingTid) 1802 throws RemoteException { 1803 final int resolvedWindowId; 1804 IAccessibilityInteractionConnection connection = null; 1805 synchronized (mLock) { 1806 final int resolvedUserId = mSecurityPolicy 1807 .resolveCallingUserIdEnforcingPermissionsLocked( 1808 UserHandle.getCallingUserId()); 1809 if (resolvedUserId != mCurrentUserId) { 1810 return false; 1811 } 1812 mSecurityPolicy.enforceCanRetrieveWindowContent(this); 1813 resolvedWindowId = resolveAccessibilityWindowIdLocked(accessibilityWindowId); 1814 final boolean permissionGranted = mSecurityPolicy.canPerformActionLocked(this, 1815 resolvedWindowId, action, arguments); 1816 if (!permissionGranted) { 1817 return false; 1818 } else { 1819 connection = getConnectionLocked(resolvedWindowId); 1820 if (connection == null) { 1821 return false; 1822 } 1823 } 1824 } 1825 final int flags = (mIncludeNotImportantViews) ? 1826 AccessibilityNodeInfo.INCLUDE_NOT_IMPORTANT_VIEWS : 0; 1827 final int interrogatingPid = Binder.getCallingPid(); 1828 final long identityToken = Binder.clearCallingIdentity(); 1829 try { 1830 connection.performAccessibilityAction(accessibilityNodeId, action, arguments, 1831 interactionId, callback, flags, interrogatingPid, interrogatingTid); 1832 } catch (RemoteException re) { 1833 if (DEBUG) { 1834 Slog.e(LOG_TAG, "Error calling performAccessibilityAction()"); 1835 } 1836 } finally { 1837 Binder.restoreCallingIdentity(identityToken); 1838 } 1839 return true; 1840 } 1841 1842 public boolean performGlobalAction(int action) { 1843 synchronized (mLock) { 1844 final int resolvedUserId = mSecurityPolicy 1845 .resolveCallingUserIdEnforcingPermissionsLocked( 1846 UserHandle.getCallingUserId()); 1847 if (resolvedUserId != mCurrentUserId) { 1848 return false; 1849 } 1850 } 1851 final long identity = Binder.clearCallingIdentity(); 1852 try { 1853 switch (action) { 1854 case AccessibilityService.GLOBAL_ACTION_BACK: { 1855 sendDownAndUpKeyEvents(KeyEvent.KEYCODE_BACK); 1856 } return true; 1857 case AccessibilityService.GLOBAL_ACTION_HOME: { 1858 sendDownAndUpKeyEvents(KeyEvent.KEYCODE_HOME); 1859 } return true; 1860 case AccessibilityService.GLOBAL_ACTION_RECENTS: { 1861 openRecents(); 1862 } return true; 1863 case AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS: { 1864 expandNotifications(); 1865 } return true; 1866 case AccessibilityService.GLOBAL_ACTION_QUICK_SETTINGS: { 1867 expandQuickSettings(); 1868 } return true; 1869 } 1870 return false; 1871 } finally { 1872 Binder.restoreCallingIdentity(identity); 1873 } 1874 } 1875 1876 public void onServiceDisconnected(ComponentName componentName) { 1877 /* do nothing - #binderDied takes care */ 1878 } 1879 1880 public void linkToOwnDeath() throws RemoteException { 1881 mService.linkToDeath(this, 0); 1882 } 1883 1884 public void unlinkToOwnDeath() { 1885 mService.unlinkToDeath(this, 0); 1886 } 1887 1888 public void dispose() { 1889 try { 1890 // Clear the proxy in the other process so this 1891 // IAccessibilityServiceConnection can be garbage collected. 1892 mServiceInterface.setConnection(null, mId); 1893 } catch (RemoteException re) { 1894 /* ignore */ 1895 } 1896 mService = null; 1897 mServiceInterface = null; 1898 } 1899 1900 public void binderDied() { 1901 synchronized (mLock) { 1902 // The death recipient is unregistered in tryRemoveServiceLocked 1903 tryRemoveServiceLocked(this); 1904 // We no longer have an automation service, so restore 1905 // the state based on values in the settings database. 1906 if (mIsAutomation) { 1907 mUiAutomationService = null; 1908 recreateInternalStateLocked(getUserStateLocked(mUserId)); 1909 } 1910 } 1911 } 1912 1913 /** 1914 * Performs a notification for an {@link AccessibilityEvent}. 1915 * 1916 * @param event The event. 1917 */ 1918 public void notifyAccessibilityEvent(AccessibilityEvent event) { 1919 synchronized (mLock) { 1920 final int eventType = event.getEventType(); 1921 // Make a copy since during dispatch it is possible the event to 1922 // be modified to remove its source if the receiving service does 1923 // not have permission to access the window content. 1924 AccessibilityEvent newEvent = AccessibilityEvent.obtain(event); 1925 AccessibilityEvent oldEvent = mPendingEvents.get(eventType); 1926 mPendingEvents.put(eventType, newEvent); 1927 1928 final int what = eventType; 1929 if (oldEvent != null) { 1930 mHandler.removeMessages(what); 1931 oldEvent.recycle(); 1932 } 1933 1934 Message message = mHandler.obtainMessage(what); 1935 mHandler.sendMessageDelayed(message, mNotificationTimeout); 1936 } 1937 } 1938 1939 /** 1940 * Notifies an accessibility service client for a scheduled event given the event type. 1941 * 1942 * @param eventType The type of the event to dispatch. 1943 */ 1944 private void notifyAccessibilityEventInternal(int eventType) { 1945 IAccessibilityServiceClient listener; 1946 AccessibilityEvent event; 1947 1948 synchronized (mLock) { 1949 listener = mServiceInterface; 1950 1951 // If the service died/was disabled while the message for dispatching 1952 // the accessibility event was propagating the listener may be null. 1953 if (listener == null) { 1954 return; 1955 } 1956 1957 event = mPendingEvents.get(eventType); 1958 1959 // Check for null here because there is a concurrent scenario in which this 1960 // happens: 1) A binder thread calls notifyAccessibilityServiceDelayedLocked 1961 // which posts a message for dispatching an event. 2) The message is pulled 1962 // from the queue by the handler on the service thread and the latter is 1963 // just about to acquire the lock and call this method. 3) Now another binder 1964 // thread acquires the lock calling notifyAccessibilityServiceDelayedLocked 1965 // so the service thread waits for the lock; 4) The binder thread replaces 1966 // the event with a more recent one (assume the same event type) and posts a 1967 // dispatch request releasing the lock. 5) Now the main thread is unblocked and 1968 // dispatches the event which is removed from the pending ones. 6) And ... now 1969 // the service thread handles the last message posted by the last binder call 1970 // but the event is already dispatched and hence looking it up in the pending 1971 // ones yields null. This check is much simpler that keeping count for each 1972 // event type of each service to catch such a scenario since only one message 1973 // is processed at a time. 1974 if (event == null) { 1975 return; 1976 } 1977 1978 mPendingEvents.remove(eventType); 1979 if (mSecurityPolicy.canRetrieveWindowContent(this)) { 1980 event.setConnectionId(mId); 1981 } else { 1982 event.setSource(null); 1983 } 1984 event.setSealed(true); 1985 } 1986 1987 try { 1988 listener.onAccessibilityEvent(event); 1989 if (DEBUG) { 1990 Slog.i(LOG_TAG, "Event " + event + " sent to " + listener); 1991 } 1992 } catch (RemoteException re) { 1993 Slog.e(LOG_TAG, "Error during sending " + event + " to " + listener, re); 1994 } finally { 1995 event.recycle(); 1996 } 1997 } 1998 1999 public void notifyGesture(int gestureId) { 2000 mHandler.obtainMessage(MSG_ON_GESTURE, gestureId, 0).sendToTarget(); 2001 } 2002 2003 private void notifyGestureInternal(int gestureId) { 2004 IAccessibilityServiceClient listener = mServiceInterface; 2005 if (listener != null) { 2006 try { 2007 listener.onGesture(gestureId); 2008 } catch (RemoteException re) { 2009 Slog.e(LOG_TAG, "Error during sending gesture " + gestureId 2010 + " to " + mService, re); 2011 } 2012 } 2013 } 2014 2015 private void sendDownAndUpKeyEvents(int keyCode) { 2016 final long token = Binder.clearCallingIdentity(); 2017 2018 // Inject down. 2019 final long downTime = SystemClock.uptimeMillis(); 2020 KeyEvent down = KeyEvent.obtain(downTime, downTime, KeyEvent.ACTION_DOWN, keyCode, 0, 0, 2021 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FROM_SYSTEM, 2022 InputDevice.SOURCE_KEYBOARD, null); 2023 InputManager.getInstance().injectInputEvent(down, 2024 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC); 2025 down.recycle(); 2026 2027 // Inject up. 2028 final long upTime = SystemClock.uptimeMillis(); 2029 KeyEvent up = KeyEvent.obtain(downTime, upTime, KeyEvent.ACTION_UP, keyCode, 0, 0, 2030 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, KeyEvent.FLAG_FROM_SYSTEM, 2031 InputDevice.SOURCE_KEYBOARD, null); 2032 InputManager.getInstance().injectInputEvent(up, 2033 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC); 2034 up.recycle(); 2035 2036 Binder.restoreCallingIdentity(token); 2037 } 2038 2039 private void expandNotifications() { 2040 final long token = Binder.clearCallingIdentity(); 2041 2042 StatusBarManager statusBarManager = (StatusBarManager) mContext.getSystemService( 2043 android.app.Service.STATUS_BAR_SERVICE); 2044 statusBarManager.expandNotificationsPanel(); 2045 2046 Binder.restoreCallingIdentity(token); 2047 } 2048 2049 private void expandQuickSettings() { 2050 final long token = Binder.clearCallingIdentity(); 2051 2052 StatusBarManager statusBarManager = (StatusBarManager) mContext.getSystemService( 2053 android.app.Service.STATUS_BAR_SERVICE); 2054 statusBarManager.expandSettingsPanel(); 2055 2056 Binder.restoreCallingIdentity(token); 2057 } 2058 2059 private void openRecents() { 2060 final long token = Binder.clearCallingIdentity(); 2061 2062 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface( 2063 ServiceManager.getService("statusbar")); 2064 try { 2065 statusBarService.toggleRecentApps(); 2066 } catch (RemoteException e) { 2067 Slog.e(LOG_TAG, "Error toggling recent apps."); 2068 } 2069 2070 Binder.restoreCallingIdentity(token); 2071 } 2072 2073 private IAccessibilityInteractionConnection getConnectionLocked(int windowId) { 2074 if (DEBUG) { 2075 Slog.i(LOG_TAG, "Trying to get interaction connection to windowId: " + windowId); 2076 } 2077 AccessibilityConnectionWrapper wrapper = mGlobalInteractionConnections.get(windowId); 2078 if (wrapper == null) { 2079 wrapper = getCurrentUserStateLocked().mInteractionConnections.get(windowId); 2080 } 2081 if (wrapper != null && wrapper.mConnection != null) { 2082 return wrapper.mConnection; 2083 } 2084 if (DEBUG) { 2085 Slog.e(LOG_TAG, "No interaction connection to window: " + windowId); 2086 } 2087 return null; 2088 } 2089 2090 private int resolveAccessibilityWindowIdLocked(int accessibilityWindowId) { 2091 if (accessibilityWindowId == AccessibilityNodeInfo.ACTIVE_WINDOW_ID) { 2092 return mSecurityPolicy.mActiveWindowId; 2093 } 2094 return accessibilityWindowId; 2095 } 2096 2097 private float getCompatibilityScale(int windowId) { 2098 try { 2099 IBinder windowToken = mGlobalWindowTokens.get(windowId); 2100 if (windowToken != null) { 2101 return mWindowManagerService.getWindowCompatibilityScale(windowToken); 2102 } 2103 windowToken = getCurrentUserStateLocked().mWindowTokens.get(windowId); 2104 if (windowToken != null) { 2105 return mWindowManagerService.getWindowCompatibilityScale(windowToken); 2106 } 2107 } catch (RemoteException re) { 2108 /* ignore */ 2109 } 2110 return 1.0f; 2111 } 2112 } 2113 2114 final class SecurityPolicy { 2115 private static final int VALID_ACTIONS = 2116 AccessibilityNodeInfo.ACTION_CLICK 2117 | AccessibilityNodeInfo.ACTION_LONG_CLICK 2118 | AccessibilityNodeInfo.ACTION_FOCUS 2119 | AccessibilityNodeInfo.ACTION_CLEAR_FOCUS 2120 | AccessibilityNodeInfo.ACTION_SELECT 2121 | AccessibilityNodeInfo.ACTION_CLEAR_SELECTION 2122 | AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS 2123 | AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS 2124 | AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 2125 | AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY 2126 | AccessibilityNodeInfo.ACTION_NEXT_HTML_ELEMENT 2127 | AccessibilityNodeInfo.ACTION_PREVIOUS_HTML_ELEMENT 2128 | AccessibilityNodeInfo.ACTION_SCROLL_FORWARD 2129 | AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD; 2130 2131 private static final int RETRIEVAL_ALLOWING_EVENT_TYPES = 2132 AccessibilityEvent.TYPE_VIEW_CLICKED 2133 | AccessibilityEvent.TYPE_VIEW_FOCUSED 2134 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 2135 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 2136 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 2137 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 2138 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 2139 | AccessibilityEvent.TYPE_VIEW_SELECTED 2140 | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED 2141 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 2142 | AccessibilityEvent.TYPE_VIEW_SCROLLED 2143 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 2144 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED; 2145 2146 private int mActiveWindowId; 2147 private boolean mTouchInteractionInProgress; 2148 2149 private boolean canDispatchAccessibilityEvent(AccessibilityEvent event) { 2150 final int eventType = event.getEventType(); 2151 switch (eventType) { 2152 // All events that are for changes in a global window 2153 // state should *always* be dispatched. 2154 case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED: 2155 case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED: 2156 // All events generated by the user touching the 2157 // screen should *always* be dispatched. 2158 case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_START: 2159 case AccessibilityEvent.TYPE_TOUCH_EXPLORATION_GESTURE_END: 2160 case AccessibilityEvent.TYPE_GESTURE_DETECTION_START: 2161 case AccessibilityEvent.TYPE_GESTURE_DETECTION_END: 2162 case AccessibilityEvent.TYPE_TOUCH_INTERACTION_START: 2163 case AccessibilityEvent.TYPE_TOUCH_INTERACTION_END: 2164 // These will change the active window, so dispatch. 2165 case AccessibilityEvent.TYPE_VIEW_HOVER_ENTER: 2166 case AccessibilityEvent.TYPE_VIEW_HOVER_EXIT: { 2167 return true; 2168 } 2169 // All events for changes in window content should be 2170 // dispatched *only* if this window is the active one. 2171 default: 2172 return event.getWindowId() == mActiveWindowId; 2173 } 2174 } 2175 2176 public void updateEventSourceLocked(AccessibilityEvent event) { 2177 if ((event.getEventType() & RETRIEVAL_ALLOWING_EVENT_TYPES) == 0) { 2178 event.setSource(null); 2179 } 2180 } 2181 2182 public void updateActiveWindow(int windowId, int eventType) { 2183 // The active window is either the window that has input focus or 2184 // the window that the user is currently touching. If the user is 2185 // touching a window that does not have input focus as soon as the 2186 // the user stops touching that window the focused window becomes 2187 // the active one. 2188 switch (eventType) { 2189 case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED: { 2190 if (getFocusedWindowId() == windowId) { 2191 mActiveWindowId = windowId; 2192 } 2193 } break; 2194 case AccessibilityEvent.TYPE_VIEW_HOVER_ENTER: { 2195 // Do not allow delayed hover events to confuse us 2196 // which the active window is. 2197 if (mTouchInteractionInProgress) { 2198 mActiveWindowId = windowId; 2199 } 2200 } break; 2201 } 2202 } 2203 2204 public void onTouchInteractionStart() { 2205 mTouchInteractionInProgress = true; 2206 } 2207 2208 public void onTouchInteractionEnd() { 2209 mTouchInteractionInProgress = false; 2210 // We want to set the active window to be current immediately 2211 // after the user has stopped touching the screen since if the 2212 // user types with the IME he should get a feedback for the 2213 // letter typed in the text view which is in the input focused 2214 // window. Note that we always deliver hover accessibility events 2215 // (they are a result of user touching the screen) so change of 2216 // the active window before all hover accessibility events from 2217 // the touched window are delivered is fine. 2218 mActiveWindowId = getFocusedWindowId(); 2219 } 2220 2221 public int getRetrievalAllowingWindowLocked() { 2222 return mActiveWindowId; 2223 } 2224 2225 public boolean canGetAccessibilityNodeInfoLocked(Service service, int windowId) { 2226 return canRetrieveWindowContent(service) && isRetrievalAllowingWindow(windowId); 2227 } 2228 2229 public boolean canPerformActionLocked(Service service, int windowId, int action, 2230 Bundle arguments) { 2231 return canRetrieveWindowContent(service) 2232 && isRetrievalAllowingWindow(windowId) 2233 && isActionPermitted(action); 2234 } 2235 2236 public boolean canRetrieveWindowContent(Service service) { 2237 return service.mCanRetrieveScreenContent; 2238 } 2239 2240 public void enforceCanRetrieveWindowContent(Service service) throws RemoteException { 2241 // This happens due to incorrect registration so make it apparent. 2242 if (!canRetrieveWindowContent(service)) { 2243 Slog.e(LOG_TAG, "Accessibility serivce " + service.mComponentName + " does not " + 2244 "declare android:canRetrieveWindowContent."); 2245 throw new RemoteException(); 2246 } 2247 } 2248 2249 public int resolveCallingUserIdEnforcingPermissionsLocked(int userId) { 2250 final int callingUid = Binder.getCallingUid(); 2251 if (callingUid == Process.SYSTEM_UID 2252 || callingUid == Process.SHELL_UID) { 2253 return mCurrentUserId; 2254 } 2255 final int callingUserId = UserHandle.getUserId(callingUid); 2256 if (callingUserId == userId) { 2257 return userId; 2258 } 2259 if (!hasPermission(Manifest.permission.INTERACT_ACROSS_USERS) 2260 && !hasPermission(Manifest.permission.INTERACT_ACROSS_USERS_FULL)) { 2261 throw new SecurityException("Call from user " + callingUserId + " as user " 2262 + userId + " without permission INTERACT_ACROSS_USERS or " 2263 + "INTERACT_ACROSS_USERS_FULL not allowed."); 2264 } 2265 if (userId == UserHandle.USER_CURRENT 2266 || userId == UserHandle.USER_CURRENT_OR_SELF) { 2267 return mCurrentUserId; 2268 } 2269 throw new IllegalArgumentException("Calling user can be changed to only " 2270 + "UserHandle.USER_CURRENT or UserHandle.USER_CURRENT_OR_SELF."); 2271 } 2272 2273 public boolean isCallerInteractingAcrossUsers(int userId) { 2274 final int callingUid = Binder.getCallingUid(); 2275 return (Binder.getCallingPid() == android.os.Process.myPid() 2276 || callingUid == Process.SHELL_UID 2277 || userId == UserHandle.USER_CURRENT 2278 || userId == UserHandle.USER_CURRENT_OR_SELF); 2279 } 2280 2281 private boolean isRetrievalAllowingWindow(int windowId) { 2282 return (mActiveWindowId == windowId); 2283 } 2284 2285 private boolean isActionPermitted(int action) { 2286 return (VALID_ACTIONS & action) != 0; 2287 } 2288 2289 private void enforceCallingPermission(String permission, String function) { 2290 if (OWN_PROCESS_ID == Binder.getCallingPid()) { 2291 return; 2292 } 2293 if (!hasPermission(permission)) { 2294 throw new SecurityException("You do not have " + permission 2295 + " required to call " + function); 2296 } 2297 } 2298 2299 private boolean hasPermission(String permission) { 2300 return mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED; 2301 } 2302 2303 private int getFocusedWindowId() { 2304 try { 2305 // We call this only on window focus change or after touch 2306 // exploration gesture end and the shown windows are not that 2307 // many, so the linear look up is just fine. 2308 IBinder token = mWindowManagerService.getFocusedWindowToken(); 2309 if (token != null) { 2310 synchronized (mLock) { 2311 int windowId = getFocusedWindowIdLocked(token, mGlobalWindowTokens); 2312 if (windowId < 0) { 2313 windowId = getFocusedWindowIdLocked(token, 2314 getCurrentUserStateLocked().mWindowTokens); 2315 } 2316 return windowId; 2317 } 2318 } 2319 } catch (RemoteException re) { 2320 /* ignore */ 2321 } 2322 return -1; 2323 } 2324 2325 private int getFocusedWindowIdLocked(IBinder token, SparseArray<IBinder> windows) { 2326 final int windowCount = windows.size(); 2327 for (int i = 0; i < windowCount; i++) { 2328 if (windows.valueAt(i) == token) { 2329 return windows.keyAt(i); 2330 } 2331 } 2332 return -1; 2333 } 2334 } 2335 2336 private class UserState { 2337 public final int mUserId; 2338 2339 public final CopyOnWriteArrayList<Service> mServices = new CopyOnWriteArrayList<Service>(); 2340 2341 public final RemoteCallbackList<IAccessibilityManagerClient> mClients = 2342 new RemoteCallbackList<IAccessibilityManagerClient>(); 2343 2344 public final Map<ComponentName, Service> mComponentNameToServiceMap = 2345 new HashMap<ComponentName, Service>(); 2346 2347 public final List<AccessibilityServiceInfo> mInstalledServices = 2348 new ArrayList<AccessibilityServiceInfo>(); 2349 2350 public final Set<ComponentName> mEnabledServices = new HashSet<ComponentName>(); 2351 2352 public final Set<ComponentName> mTouchExplorationGrantedServices = 2353 new HashSet<ComponentName>(); 2354 2355 public final SparseArray<AccessibilityConnectionWrapper> 2356 mInteractionConnections = 2357 new SparseArray<AccessibilityConnectionWrapper>(); 2358 2359 public final SparseArray<IBinder> mWindowTokens = new SparseArray<IBinder>(); 2360 2361 public int mHandledFeedbackTypes = 0; 2362 2363 public boolean mIsAccessibilityEnabled; 2364 public boolean mIsTouchExplorationEnabled; 2365 public boolean mIsDisplayMagnificationEnabled; 2366 2367 public UserState(int userId) { 2368 mUserId = userId; 2369 } 2370 } 2371 2372 private class TempUserStateChangeMemento { 2373 public int mUserId = UserHandle.USER_NULL; 2374 public boolean mIsAccessibilityEnabled; 2375 public boolean mIsTouchExplorationEnabled; 2376 public boolean mIsDisplayMagnificationEnabled; 2377 public final Set<ComponentName> mEnabledServices = new HashSet<ComponentName>(); 2378 public final Set<ComponentName> mTouchExplorationGrantedServices = 2379 new HashSet<ComponentName>(); 2380 2381 public void initialize(int userId, UserState userState) { 2382 mUserId = userId; 2383 mIsAccessibilityEnabled = userState.mIsAccessibilityEnabled; 2384 mIsTouchExplorationEnabled = userState.mIsTouchExplorationEnabled; 2385 mIsDisplayMagnificationEnabled = userState.mIsDisplayMagnificationEnabled; 2386 mEnabledServices.clear(); 2387 mEnabledServices.addAll(userState.mEnabledServices); 2388 mTouchExplorationGrantedServices.clear(); 2389 mTouchExplorationGrantedServices.addAll(userState.mTouchExplorationGrantedServices); 2390 } 2391 2392 public void applyTo(UserState userState) { 2393 userState.mIsAccessibilityEnabled = mIsAccessibilityEnabled; 2394 userState.mIsTouchExplorationEnabled = mIsTouchExplorationEnabled; 2395 userState.mIsDisplayMagnificationEnabled = mIsDisplayMagnificationEnabled; 2396 userState.mEnabledServices.clear(); 2397 userState.mEnabledServices.addAll(mEnabledServices); 2398 userState.mTouchExplorationGrantedServices.clear(); 2399 userState.mTouchExplorationGrantedServices.addAll(mTouchExplorationGrantedServices); 2400 } 2401 2402 public void clear() { 2403 mUserId = UserHandle.USER_NULL; 2404 mIsAccessibilityEnabled = false; 2405 mIsTouchExplorationEnabled = false; 2406 mIsDisplayMagnificationEnabled = false; 2407 mEnabledServices.clear(); 2408 mTouchExplorationGrantedServices.clear(); 2409 } 2410 } 2411 2412 private final class AccessibilityContentObserver extends ContentObserver { 2413 2414 private final Uri mAccessibilityEnabledUri = Settings.Secure.getUriFor( 2415 Settings.Secure.ACCESSIBILITY_ENABLED); 2416 2417 private final Uri mTouchExplorationEnabledUri = Settings.Secure.getUriFor( 2418 Settings.Secure.TOUCH_EXPLORATION_ENABLED); 2419 2420 private final Uri mDisplayMagnificationEnabledUri = Settings.Secure.getUriFor( 2421 Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED); 2422 2423 private final Uri mEnabledAccessibilityServicesUri = Settings.Secure.getUriFor( 2424 Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES); 2425 2426 private final Uri mTouchExplorationGrantedAccessibilityServicesUri = Settings.Secure 2427 .getUriFor(Settings.Secure.TOUCH_EXPLORATION_GRANTED_ACCESSIBILITY_SERVICES); 2428 2429 public AccessibilityContentObserver(Handler handler) { 2430 super(handler); 2431 } 2432 2433 public void register(ContentResolver contentResolver) { 2434 contentResolver.registerContentObserver(mAccessibilityEnabledUri, 2435 false, this, UserHandle.USER_ALL); 2436 contentResolver.registerContentObserver(mTouchExplorationEnabledUri, 2437 false, this, UserHandle.USER_ALL); 2438 contentResolver.registerContentObserver(mDisplayMagnificationEnabledUri, 2439 false, this, UserHandle.USER_ALL); 2440 contentResolver.registerContentObserver(mEnabledAccessibilityServicesUri, 2441 false, this, UserHandle.USER_ALL); 2442 contentResolver.registerContentObserver( 2443 mTouchExplorationGrantedAccessibilityServicesUri, 2444 false, this, UserHandle.USER_ALL); 2445 } 2446 2447 @Override 2448 public void onChange(boolean selfChange, Uri uri) { 2449 if (mAccessibilityEnabledUri.equals(uri)) { 2450 synchronized (mLock) { 2451 // We will update when the automation service dies. 2452 if (mUiAutomationService == null) { 2453 UserState userState = getCurrentUserStateLocked(); 2454 handleAccessibilityEnabledSettingChangedLocked(userState); 2455 performServiceManagementLocked(userState); 2456 updateInputFilterLocked(userState); 2457 scheduleSendStateToClientsLocked(userState); 2458 } 2459 } 2460 } else if (mTouchExplorationEnabledUri.equals(uri)) { 2461 synchronized (mLock) { 2462 // We will update when the automation service dies. 2463 if (mUiAutomationService == null) { 2464 UserState userState = getCurrentUserStateLocked(); 2465 handleTouchExplorationEnabledSettingChangedLocked(userState); 2466 updateInputFilterLocked(userState); 2467 scheduleSendStateToClientsLocked(userState); 2468 } 2469 } 2470 } else if (mDisplayMagnificationEnabledUri.equals(uri)) { 2471 synchronized (mLock) { 2472 // We will update when the automation service dies. 2473 if (mUiAutomationService == null) { 2474 UserState userState = getCurrentUserStateLocked(); 2475 handleDisplayMagnificationEnabledSettingChangedLocked(userState); 2476 updateInputFilterLocked(userState); 2477 scheduleSendStateToClientsLocked(userState); 2478 } 2479 } 2480 } else if (mEnabledAccessibilityServicesUri.equals(uri)) { 2481 synchronized (mLock) { 2482 // We will update when the automation service dies. 2483 if (mUiAutomationService == null) { 2484 UserState userState = getCurrentUserStateLocked(); 2485 populateEnabledAccessibilityServicesLocked(userState); 2486 manageServicesLocked(userState); 2487 } 2488 } 2489 } else if (mTouchExplorationGrantedAccessibilityServicesUri.equals(uri)) { 2490 synchronized (mLock) { 2491 // We will update when the automation service dies. 2492 if (mUiAutomationService == null) { 2493 UserState userState = getCurrentUserStateLocked(); 2494 populateTouchExplorationGrantedAccessibilityServicesLocked(userState); 2495 handleTouchExplorationGrantedAccessibilityServicesChangedLocked(userState); 2496 } 2497 } 2498 } 2499 } 2500 } 2501} 2502