/**
   * Attach to the required system interfaces.
   *
   * @return Returns true if all system interfaces were available.
   */
  private boolean getSystemInterfaces() {
    mAm = ActivityManagerNative.getDefault();
    if (mAm == null) {
      System.err.println(
          "** Error: Unable to connect to activity manager; is the system " + "running?");
      return false;
    }

    mWm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
    if (mWm == null) {
      System.err.println(
          "** Error: Unable to connect to window manager; is the system " + "running?");
      return false;
    }

    mPm = IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
    if (mPm == null) {
      System.err.println(
          "** Error: Unable to connect to package manager; is the system " + "running?");
      return false;
    }

    try {
      mAm.setActivityController(new ActivityController());
      mNetworkMonitor.register(mAm);
    } catch (RemoteException e) {
      System.err.println("** Failed talking with activity manager!");
      return false;
    }

    return true;
  }
Example #2
0
  @Override
  public void onCreate() {
    // Pick status bar or system bar.
    IWindowManager wm =
        IWindowManager.Stub.asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
    try {
      SERVICES[0] =
          wm.canStatusBarHide()
              // ? R.string.config_statusBarComponent
              ? R.string.config_systemBarComponent
              : R.string.config_systemBarComponent;
    } catch (RemoteException e) {
      Slog.w(TAG, "Failing checking whether status bar can hide", e);
    }

    final int N = SERVICES.length;
    mServices = new SystemUI[N];
    for (int i = 0; i < N; i++) {
      Class cl = chooseClass(SERVICES[i]);
      Slog.d(TAG, "loading: " + cl);
      try {
        mServices[i] = (SystemUI) cl.newInstance();
      } catch (IllegalAccessException ex) {
        throw new RuntimeException(ex);
      } catch (InstantiationException ex) {
        throw new RuntimeException(ex);
      }
      mServices[i].mContext = this;
      Slog.d(TAG, "running: " + mServices[i]);
      mServices[i].start();
    }
  }
 private int getCurrentDensity() {
   IWindowManager wm =
       IWindowManager.Stub.asInterface(ServiceManager.checkService(Context.WINDOW_SERVICE));
   try {
     return wm.getBaseDisplayDensity(Display.DEFAULT_DISPLAY);
   } catch (RemoteException e) {
     e.printStackTrace();
   }
   return DisplayMetrics.DENSITY_DEVICE;
 }
  private void handleToggleAutoRotateScreenPreferenceClick() {

    boolean enableDefaultRotation = getResources().getBoolean(R.bool.config_enableDefaultRotation);
    try {
      IWindowManager wm =
          IWindowManager.Stub.asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
      if (mToggleAutoRotateScreenPreference.isChecked()) {
        wm.thawRotation();
      } else {
        if (enableDefaultRotation) {
          wm.freezeRotation(-1);
        } else {
          wm.freezeRotation(Surface.ROTATION_0);
        }
      }
    } catch (RemoteException exc) {
      Log.w(TAG, "Unable to save auto-rotate setting");
    }
  }
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    mWindowManager = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
    mBackupManager =
        IBackupManager.Stub.asInterface(ServiceManager.getService(Context.BACKUP_SERVICE));

    addPreferencesFromResource(R.xml.development_prefs);

    mEnableAdb = (CheckBoxPreference) findPreference(ENABLE_ADB);
    mKeepScreenOn = (CheckBoxPreference) findPreference(KEEP_SCREEN_ON);
    mAllowMockLocation = (CheckBoxPreference) findPreference(ALLOW_MOCK_LOCATION);
    mPassword = (PreferenceScreen) findPreference(LOCAL_BACKUP_PASSWORD);

    mStrictMode = (CheckBoxPreference) findPreference(STRICT_MODE_KEY);
    mPointerLocation = (CheckBoxPreference) findPreference(POINTER_LOCATION_KEY);
    mShowTouches = (CheckBoxPreference) findPreference(SHOW_TOUCHES_KEY);
    mShowScreenUpdates = (CheckBoxPreference) findPreference(SHOW_SCREEN_UPDATES_KEY);
    mShowCpuUsage = (CheckBoxPreference) findPreference(SHOW_CPU_USAGE_KEY);
    mForceHardwareUi = (CheckBoxPreference) findPreference(FORCE_HARDWARE_UI_KEY);
    mWindowAnimationScale = (ListPreference) findPreference(WINDOW_ANIMATION_SCALE_KEY);
    mWindowAnimationScale.setOnPreferenceChangeListener(this);
    mTransitionAnimationScale = (ListPreference) findPreference(TRANSITION_ANIMATION_SCALE_KEY);
    mTransitionAnimationScale.setOnPreferenceChangeListener(this);

    mImmediatelyDestroyActivities =
        (CheckBoxPreference) findPreference(IMMEDIATELY_DESTROY_ACTIVITIES_KEY);
    mAppProcessLimit = (ListPreference) findPreference(APP_PROCESS_LIMIT_KEY);
    mAppProcessLimit.setOnPreferenceChangeListener(this);

    mShowAllANRs = (CheckBoxPreference) findPreference(SHOW_ALL_ANRS_KEY);

    final Preference verifierDeviceIdentifier = findPreference(VERIFIER_DEVICE_IDENTIFIER);
    final PackageManager pm = getActivity().getPackageManager();
    final VerifierDeviceIdentity verifierIndentity = pm.getVerifierDeviceIdentity();
    if (verifierIndentity != null) {
      verifierDeviceIdentifier.setSummary(verifierIndentity.toString());
    }

    removeHdcpOptionsForProduction();
  }
  private void writeLcdDensityPreference(final Context context, final int density) {
    final IActivityManager am =
        ActivityManagerNative.asInterface(ServiceManager.checkService("activity"));
    final IWindowManager wm =
        IWindowManager.Stub.asInterface(ServiceManager.checkService(Context.WINDOW_SERVICE));
    AsyncTask<Void, Void, Void> task =
        new AsyncTask<Void, Void, Void>() {
          @Override
          protected void onPreExecute() {
            ProgressDialog dialog = new ProgressDialog(context);
            dialog.setMessage(getResources().getString(R.string.restarting_ui));
            dialog.setCancelable(false);
            dialog.setIndeterminate(true);
            dialog.show();
          }

          @Override
          protected Void doInBackground(Void... params) {
            // Give the user a second to see the dialog
            try {
              Thread.sleep(1000);
            } catch (InterruptedException e) {
              // Ignore
            }

            try {
              wm.setForcedDisplayDensity(Display.DEFAULT_DISPLAY, density);
            } catch (RemoteException e) {
              Log.e(TAG, "Failed to set density to " + density, e);
            }

            // Restart the UI
            try {
              am.restart();
            } catch (RemoteException e) {
              Log.e(TAG, "Failed to restart");
            }
            return null;
          }
        };
    task.execute();
  }
  public PieController(
      Context context,
      BaseStatusBar statusBar,
      EdgeGestureManager pieManager,
      NavigationBarOverlay nbo) {
    mContext = context;
    mStatusBar = statusBar;
    mNavigationBarOverlay = nbo;

    mVibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
    mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
    mWm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));

    if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
      mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
    }

    mPieManager = pieManager;
    mPieManager.setEdgeGestureActivationListener(mPieActivationListener);
  }
  @Override
  public void onCreate() {
    mTvOut = new TvOut();
    mPref = PreferenceManager.getDefaultSharedPreferences(this);

    IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
    try {
      wm.watchRotation(
          new IRotationWatcher.Stub() {
            @Override
            public void onRotationChanged(int rotation) {
              TvOutService.this.onRotationChanged(rotation);
            }
          });
    } catch (RemoteException e) {
    }

    IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_SCREEN_ON);
    registerReceiver(mReceiver, filter);
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitle(R.string.title_navbar);

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.navbar_settings);

    PreferenceScreen prefs = getPreferenceScreen();

    mPicker = new ShortcutPickerHelper(this, this);
    mPackMan = getPackageManager();
    mResources = mContext.getResources();

    // Get NavBar Actions
    mActionCodes = NavBarHelpers.getNavBarActions();
    mActions = new String[mActionCodes.length];
    int actionqty = mActions.length;
    for (int i = 0; i < actionqty; i++) {
      mActions[i] = AwesomeConstants.getProperName(mContext, mActionCodes[i]);
    }

    menuDisplayLocation = (ListPreference) findPreference(PREF_MENU_UNLOCK);
    menuDisplayLocation.setOnPreferenceChangeListener(this);
    menuDisplayLocation.setValue(
        Settings.System.getInt(mContentRes, Settings.System.MENU_LOCATION, 0) + "");

    mNavBarMenuDisplay = (ListPreference) findPreference(PREF_NAVBAR_MENU_DISPLAY);
    mNavBarMenuDisplay.setOnPreferenceChangeListener(this);
    mNavBarMenuDisplay.setValue(
        Settings.System.getInt(mContentRes, Settings.System.MENU_VISIBILITY, 0) + "");

    mNavBarHideEnable = (CheckBoxPreference) findPreference(NAVBAR_HIDE_ENABLE);
    mNavBarHideEnable.setChecked(
        Settings.System.getBoolean(mContentRes, Settings.System.NAV_HIDE_ENABLE, false));

    final int defaultDragOpacity =
        Settings.System.getInt(mContentRes, Settings.System.DRAG_HANDLE_OPACITY, 50);
    mDragHandleOpacity = (SeekBarPreference) findPreference(DRAG_HANDLE_OPACITY);
    mDragHandleOpacity.setInitValue((int) (defaultDragOpacity));
    mDragHandleOpacity.setOnPreferenceChangeListener(this);

    final int defaultDragWidth =
        Settings.System.getInt(mContentRes, Settings.System.DRAG_HANDLE_WEIGHT, 5);
    mDragHandleWidth = (SeekBarPreference) findPreference(DRAG_HANDLE_WIDTH);
    mDragHandleWidth.setInitValue((int) (defaultDragWidth));
    mDragHandleWidth.setOnPreferenceChangeListener(this);

    mNavBarHideTimeout = (ListPreference) findPreference(NAVBAR_HIDE_TIMEOUT);
    mNavBarHideTimeout.setOnPreferenceChangeListener(this);
    mNavBarHideTimeout.setValue(
        Settings.System.getInt(mContentRes, Settings.System.NAV_HIDE_TIMEOUT, 3000) + "");

    boolean hasNavBarByDefault =
        mContext.getResources().getBoolean(com.android.internal.R.bool.config_showNavigationBar);
    mEnableNavigationBar = (CheckBoxPreference) findPreference(ENABLE_NAVIGATION_BAR);
    mEnableNavigationBar.setChecked(
        Settings.System.getBoolean(
            mContentRes, Settings.System.NAVIGATION_BAR_SHOW, hasNavBarByDefault));

    mNavigationColor = (ColorPickerPreference) findPreference(NAVIGATION_BAR_COLOR);
    mNavigationColor.setOnPreferenceChangeListener(this);

    mNavigationBarColor = (ColorPickerPreference) findPreference(PREF_NAV_COLOR);
    mNavigationBarColor.setOnPreferenceChangeListener(this);

    mColorizeAllIcons = (CheckBoxPreference) findPreference("navigation_bar_allcolor");
    mColorizeAllIcons.setChecked(
        Settings.System.getBoolean(mContentRes, Settings.System.NAVIGATION_BAR_ALLCOLOR, false));

    mNavigationBarGlowColor = (ColorPickerPreference) findPreference(PREF_NAV_GLOW_COLOR);
    mNavigationBarGlowColor.setOnPreferenceChangeListener(this);

    mGlowTimes = (ListPreference) findPreference(PREF_GLOW_TIMES);
    mGlowTimes.setOnPreferenceChangeListener(this);

    final float defaultButtonAlpha =
        Settings.System.getFloat(mContentRes, Settings.System.NAVIGATION_BAR_BUTTON_ALPHA, 0.6f);
    mButtonAlpha = (SeekBarPreference) findPreference("button_transparency");
    mButtonAlpha.setInitValue((int) (defaultButtonAlpha * 100));
    mButtonAlpha.setOnPreferenceChangeListener(this);

    mWidthHelp = (Preference) findPreference("width_help");

    float defaultPort =
        Settings.System.getFloat(mContentRes, Settings.System.NAVIGATION_BAR_WIDTH_PORT, 0f);
    mWidthPort = (SeekBarPreference) findPreference("width_port");
    mWidthPort.setInitValue((int) (defaultPort * 2.5f));
    mWidthPort.setOnPreferenceChangeListener(this);

    float defaultLand =
        Settings.System.getFloat(mContentRes, Settings.System.NAVIGATION_BAR_WIDTH_LAND, 0f);
    mWidthLand = (SeekBarPreference) findPreference("width_land");
    mWidthLand.setInitValue((int) (defaultLand * 2.5f));
    mWidthLand.setOnPreferenceChangeListener(this);

    mNavigationBarHeight = (ListPreference) findPreference("navigation_bar_height");
    mNavigationBarHeight.setOnPreferenceChangeListener(this);

    mNavigationBarHeightLandscape =
        (ListPreference) findPreference("navigation_bar_height_landscape");
    mNavigationBarHeightLandscape.setOnPreferenceChangeListener(this);

    mNavigationBarWidth = (ListPreference) findPreference("navigation_bar_width");
    mNavigationBarWidth.setOnPreferenceChangeListener(this);
    mConfigureWidgets = findPreference(NAVIGATION_BAR_WIDGETS);

    mMenuArrowKeysCheckBox = (CheckBoxPreference) findPreference(PREF_MENU_ARROWS);
    mMenuArrowKeysCheckBox.setChecked(
        Settings.System.getBoolean(
            mContentRes, Settings.System.NAVIGATION_BAR_MENU_ARROW_KEYS, true));

    // don't allow devices that must use a navigation bar to disable it
    if (hasNavBarByDefault) {
      prefs.removePreference(mEnableNavigationBar);
    }
    PreferenceGroup pg = (PreferenceGroup) prefs.findPreference("advanced_cat");
    if (isTablet(mContext)) {
      mNavigationBarHeight.setTitle(R.string.system_bar_height_title);
      mNavigationBarHeight.setSummary(R.string.system_bar_height_summary);
      mNavigationBarHeightLandscape.setTitle(R.string.system_bar_height_landscape_title);
      mNavigationBarHeightLandscape.setSummary(R.string.system_bar_height_landscape_summary);
      pg.removePreference(mNavigationBarWidth);
      mNavBarHideEnable.setEnabled(false);
      mDragHandleOpacity.setEnabled(false);
      mDragHandleWidth.setEnabled(false);
      mNavBarHideTimeout.setEnabled(false);
    } else { // Phones&Phablets don't have SystemBar
      pg.removePreference(mWidthPort);
      pg.removePreference(mWidthLand);
      pg.removePreference(mWidthHelp);
    }

    if (Integer.parseInt(menuDisplayLocation.getValue()) == 4) {
      mNavBarMenuDisplay.setEnabled(false);
    }

    // Only show the hardware keys config on a device that does not have a navbar
    IWindowManager windowManager =
        IWindowManager.Stub.asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));

    if (hasNavBarByDefault) {
      // Let's assume they don't have hardware keys
      getPreferenceScreen().removePreference(findPreference(KEY_HARDWARE_KEYS));
    }
    refreshSettings();
    setHasOptionsMenu(true);
    updateGlowTimesSummary();
  }
/**
 * This is a remote object that is passed from the shell to an instrumentation for enabling access
 * to privileged operations which the shell can do and the instrumentation cannot. These privileged
 * operations are needed for implementing a {@link UiAutomation} that enables across application
 * testing by simulating user actions and performing screen introspection.
 *
 * @hide
 */
public final class UiAutomationConnection extends IUiAutomationConnection.Stub {

  private static final int INITIAL_FROZEN_ROTATION_UNSPECIFIED = -1;

  private final IWindowManager mWindowManager =
      IWindowManager.Stub.asInterface(ServiceManager.getService(Service.WINDOW_SERVICE));

  private final IAccessibilityManager mAccessibilityManager =
      IAccessibilityManager.Stub.asInterface(
          ServiceManager.getService(Service.ACCESSIBILITY_SERVICE));

  private final IPackageManager mPackageManager =
      IPackageManager.Stub.asInterface(ServiceManager.getService("package"));

  private final Object mLock = new Object();

  private final Binder mToken = new Binder();

  private int mInitialFrozenRotation = INITIAL_FROZEN_ROTATION_UNSPECIFIED;

  private IAccessibilityServiceClient mClient;

  private boolean mIsShutdown;

  private int mOwningUid;

  public void connect(IAccessibilityServiceClient client) {
    if (client == null) {
      throw new IllegalArgumentException("Client cannot be null!");
    }
    synchronized (mLock) {
      throwIfShutdownLocked();
      if (isConnectedLocked()) {
        throw new IllegalStateException("Already connected.");
      }
      mOwningUid = Binder.getCallingUid();
      registerUiTestAutomationServiceLocked(client);
      storeRotationStateLocked();
    }
  }

  @Override
  public void disconnect() {
    synchronized (mLock) {
      throwIfCalledByNotTrustedUidLocked();
      throwIfShutdownLocked();
      if (!isConnectedLocked()) {
        throw new IllegalStateException("Already disconnected.");
      }
      mOwningUid = -1;
      unregisterUiTestAutomationServiceLocked();
      restoreRotationStateLocked();
    }
  }

  @Override
  public boolean injectInputEvent(InputEvent event, boolean sync) {
    synchronized (mLock) {
      throwIfCalledByNotTrustedUidLocked();
      throwIfShutdownLocked();
      throwIfNotConnectedLocked();
    }
    final int mode =
        (sync)
            ? InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
            : InputManager.INJECT_INPUT_EVENT_MODE_ASYNC;
    final long identity = Binder.clearCallingIdentity();
    try {
      return InputManager.getInstance().injectInputEvent(event, mode);
    } finally {
      Binder.restoreCallingIdentity(identity);
    }
  }

  @Override
  public boolean setRotation(int rotation) {
    synchronized (mLock) {
      throwIfCalledByNotTrustedUidLocked();
      throwIfShutdownLocked();
      throwIfNotConnectedLocked();
    }
    final long identity = Binder.clearCallingIdentity();
    try {
      if (rotation == UiAutomation.ROTATION_UNFREEZE) {
        mWindowManager.thawRotation();
      } else {
        mWindowManager.freezeRotation(rotation);
      }
      return true;
    } catch (RemoteException re) {
      /* ignore */
    } finally {
      Binder.restoreCallingIdentity(identity);
    }
    return false;
  }

  @Override
  public Bitmap takeScreenshot(int width, int height) {
    synchronized (mLock) {
      throwIfCalledByNotTrustedUidLocked();
      throwIfShutdownLocked();
      throwIfNotConnectedLocked();
    }
    final long identity = Binder.clearCallingIdentity();
    try {
      return SurfaceControl.screenshot(width, height);
    } finally {
      Binder.restoreCallingIdentity(identity);
    }
  }

  @Override
  public boolean clearWindowContentFrameStats(int windowId) throws RemoteException {
    synchronized (mLock) {
      throwIfCalledByNotTrustedUidLocked();
      throwIfShutdownLocked();
      throwIfNotConnectedLocked();
    }
    final long identity = Binder.clearCallingIdentity();
    try {
      IBinder token = mAccessibilityManager.getWindowToken(windowId);
      if (token == null) {
        return false;
      }
      return mWindowManager.clearWindowContentFrameStats(token);
    } finally {
      Binder.restoreCallingIdentity(identity);
    }
  }

  @Override
  public WindowContentFrameStats getWindowContentFrameStats(int windowId) throws RemoteException {
    synchronized (mLock) {
      throwIfCalledByNotTrustedUidLocked();
      throwIfShutdownLocked();
      throwIfNotConnectedLocked();
    }
    final long identity = Binder.clearCallingIdentity();
    try {
      IBinder token = mAccessibilityManager.getWindowToken(windowId);
      if (token == null) {
        return null;
      }
      return mWindowManager.getWindowContentFrameStats(token);
    } finally {
      Binder.restoreCallingIdentity(identity);
    }
  }

  @Override
  public void clearWindowAnimationFrameStats() {
    synchronized (mLock) {
      throwIfCalledByNotTrustedUidLocked();
      throwIfShutdownLocked();
      throwIfNotConnectedLocked();
    }
    final long identity = Binder.clearCallingIdentity();
    try {
      SurfaceControl.clearAnimationFrameStats();
    } finally {
      Binder.restoreCallingIdentity(identity);
    }
  }

  @Override
  public WindowAnimationFrameStats getWindowAnimationFrameStats() {
    synchronized (mLock) {
      throwIfCalledByNotTrustedUidLocked();
      throwIfShutdownLocked();
      throwIfNotConnectedLocked();
    }
    final long identity = Binder.clearCallingIdentity();
    try {
      WindowAnimationFrameStats stats = new WindowAnimationFrameStats();
      SurfaceControl.getAnimationFrameStats(stats);
      return stats;
    } finally {
      Binder.restoreCallingIdentity(identity);
    }
  }

  @Override
  public void grantRuntimePermission(String packageName, String permission, int userId)
      throws RemoteException {
    synchronized (mLock) {
      throwIfCalledByNotTrustedUidLocked();
      throwIfShutdownLocked();
      throwIfNotConnectedLocked();
    }
    final long identity = Binder.clearCallingIdentity();
    try {
      mPackageManager.grantRuntimePermission(packageName, permission, userId);
    } finally {
      Binder.restoreCallingIdentity(identity);
    }
  }

  @Override
  public void revokeRuntimePermission(String packageName, String permission, int userId)
      throws RemoteException {
    synchronized (mLock) {
      throwIfCalledByNotTrustedUidLocked();
      throwIfShutdownLocked();
      throwIfNotConnectedLocked();
    }
    final long identity = Binder.clearCallingIdentity();
    try {
      mPackageManager.revokeRuntimePermission(packageName, permission, userId);
    } finally {
      Binder.restoreCallingIdentity(identity);
    }
  }

  @Override
  public void executeShellCommand(final String command, final ParcelFileDescriptor sink)
      throws RemoteException {
    synchronized (mLock) {
      throwIfCalledByNotTrustedUidLocked();
      throwIfShutdownLocked();
      throwIfNotConnectedLocked();
    }

    Thread streamReader =
        new Thread() {
          public void run() {
            InputStream in = null;
            OutputStream out = null;
            java.lang.Process process = null;

            try {
              process = Runtime.getRuntime().exec(command);

              in = process.getInputStream();
              out = new FileOutputStream(sink.getFileDescriptor());

              final byte[] buffer = new byte[8192];
              while (true) {
                final int readByteCount = in.read(buffer);
                if (readByteCount < 0) {
                  break;
                }
                out.write(buffer, 0, readByteCount);
              }
            } catch (IOException ioe) {
              throw new RuntimeException("Error running shell command", ioe);
            } finally {
              if (process != null) {
                process.destroy();
              }
              IoUtils.closeQuietly(out);
              IoUtils.closeQuietly(sink);
            }
          };
        };
    streamReader.start();
  }

  @Override
  public void shutdown() {
    synchronized (mLock) {
      if (isConnectedLocked()) {
        throwIfCalledByNotTrustedUidLocked();
      }
      throwIfShutdownLocked();
      mIsShutdown = true;
      if (isConnectedLocked()) {
        disconnect();
      }
    }
  }

  private void registerUiTestAutomationServiceLocked(IAccessibilityServiceClient client) {
    IAccessibilityManager manager =
        IAccessibilityManager.Stub.asInterface(
            ServiceManager.getService(Context.ACCESSIBILITY_SERVICE));
    AccessibilityServiceInfo info = new AccessibilityServiceInfo();
    info.eventTypes = AccessibilityEvent.TYPES_ALL_MASK;
    info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
    info.flags |=
        AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
            | AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS;
    info.setCapabilities(
        AccessibilityServiceInfo.CAPABILITY_CAN_RETRIEVE_WINDOW_CONTENT
            | AccessibilityServiceInfo.CAPABILITY_CAN_REQUEST_TOUCH_EXPLORATION
            | AccessibilityServiceInfo.CAPABILITY_CAN_REQUEST_ENHANCED_WEB_ACCESSIBILITY
            | AccessibilityServiceInfo.CAPABILITY_CAN_REQUEST_FILTER_KEY_EVENTS);
    try {
      // Calling out with a lock held is fine since if the system
      // process is gone the client calling in will be killed.
      manager.registerUiTestAutomationService(mToken, client, info);
      mClient = client;
    } catch (RemoteException re) {
      throw new IllegalStateException("Error while registering UiTestAutomationService.", re);
    }
  }

  private void unregisterUiTestAutomationServiceLocked() {
    IAccessibilityManager manager =
        IAccessibilityManager.Stub.asInterface(
            ServiceManager.getService(Context.ACCESSIBILITY_SERVICE));
    try {
      // Calling out with a lock held is fine since if the system
      // process is gone the client calling in will be killed.
      manager.unregisterUiTestAutomationService(mClient);
      mClient = null;
    } catch (RemoteException re) {
      throw new IllegalStateException("Error while unregistering UiTestAutomationService", re);
    }
  }

  private void storeRotationStateLocked() {
    try {
      if (mWindowManager.isRotationFrozen()) {
        // Calling out with a lock held is fine since if the system
        // process is gone the client calling in will be killed.
        mInitialFrozenRotation = mWindowManager.getRotation();
      }
    } catch (RemoteException re) {
      /* ignore */
    }
  }

  private void restoreRotationStateLocked() {
    try {
      if (mInitialFrozenRotation != INITIAL_FROZEN_ROTATION_UNSPECIFIED) {
        // Calling out with a lock held is fine since if the system
        // process is gone the client calling in will be killed.
        mWindowManager.freezeRotation(mInitialFrozenRotation);
      } else {
        // Calling out with a lock held is fine since if the system
        // process is gone the client calling in will be killed.
        mWindowManager.thawRotation();
      }
    } catch (RemoteException re) {
      /* ignore */
    }
  }

  private boolean isConnectedLocked() {
    return mClient != null;
  }

  private void throwIfShutdownLocked() {
    if (mIsShutdown) {
      throw new IllegalStateException("Connection shutdown!");
    }
  }

  private void throwIfNotConnectedLocked() {
    if (!isConnectedLocked()) {
      throw new IllegalStateException("Not connected!");
    }
  }

  private void throwIfCalledByNotTrustedUidLocked() {
    final int callingUid = Binder.getCallingUid();
    if (callingUid != mOwningUid && mOwningUid != Process.SYSTEM_UID && callingUid != 0 /*root*/) {
      throw new SecurityException("Calling from not trusted UID!");
    }
  }
}
  private void runInstrument() {
    String profileFile = null;
    boolean wait = false;
    boolean rawMode = false;
    boolean no_window_animation = false;
    Bundle args = new Bundle();
    String argKey = null, argValue = null;
    IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));

    try {
      String opt;
      while ((opt = nextOption()) != null) {
        if (opt.equals("-p")) {
          profileFile = nextOptionData();
        } else if (opt.equals("-w")) {
          wait = true;
        } else if (opt.equals("-r")) {
          rawMode = true;
        } else if (opt.equals("-e")) {
          argKey = nextOptionData();
          argValue = nextOptionData();
          args.putString(argKey, argValue);
        } else if (opt.equals("--no_window_animation")) {
          no_window_animation = true;
        } else {
          System.err.println("Error: Unknown option: " + opt);
          showUsage();
          return;
        }
      }
    } catch (RuntimeException ex) {
      System.err.println("Error: " + ex.toString());
      showUsage();
      return;
    }

    String cnArg = nextArg();
    if (cnArg == null) {
      System.err.println("Error: No instrumentation component supplied");
      showUsage();
      return;
    }

    ComponentName cn = ComponentName.unflattenFromString(cnArg);
    if (cn == null) {
      System.err.println("Error: Bad component name: " + cnArg);
      showUsage();
      return;
    }

    InstrumentationWatcher watcher = null;
    if (wait) {
      watcher = new InstrumentationWatcher();
      watcher.setRawOutput(rawMode);
    }
    float[] oldAnims = null;
    if (no_window_animation) {
      try {
        oldAnims = wm.getAnimationScales();
        wm.setAnimationScale(0, 0.0f);
        wm.setAnimationScale(1, 0.0f);
      } catch (RemoteException e) {
      }
    }

    try {
      if (!mAm.startInstrumentation(cn, profileFile, 0, args, watcher)) {
        System.out.println("INSTRUMENTATION_FAILED: " + cn.flattenToString());
        showUsage();
        return;
      }
    } catch (RemoteException e) {
    }

    if (watcher != null) {
      if (!watcher.waitForFinish()) {
        System.out.println("INSTRUMENTATION_ABORTED: System has crashed.");
      }
    }

    if (oldAnims != null) {
      try {
        wm.setAnimationScales(oldAnims);
      } catch (RemoteException e) {
      }
    }
  }
  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    mWindowManager = IWindowManager.Stub.asInterface(ServiceManager.getService("window"));
    mBackupManager =
        IBackupManager.Stub.asInterface(ServiceManager.getService(Context.BACKUP_SERVICE));
    mDpm = (DevicePolicyManager) getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE);

    addPreferencesFromResource(R.xml.development_prefs);

    mEnableAdb = findAndInitCheckboxPref(ENABLE_ADB);
    mBugreport = findPreference(BUGREPORT);
    mBugreportInPower = findAndInitCheckboxPref(BUGREPORT_IN_POWER_KEY);
    mKeepScreenOn = findAndInitCheckboxPref(KEEP_SCREEN_ON);
    mEnforceReadExternal = findAndInitCheckboxPref(ENFORCE_READ_EXTERNAL);
    mAllowMockLocation = findAndInitCheckboxPref(ALLOW_MOCK_LOCATION);
    mPassword = (PreferenceScreen) findPreference(LOCAL_BACKUP_PASSWORD);
    mAllPrefs.add(mPassword);

    mDebugAppPref = findPreference(DEBUG_APP_KEY);
    mAllPrefs.add(mDebugAppPref);
    mWaitForDebugger = findAndInitCheckboxPref(WAIT_FOR_DEBUGGER_KEY);
    mVerifyAppsOverUsb = findAndInitCheckboxPref(VERIFY_APPS_OVER_USB_KEY);
    if (!showVerifierSetting()) {
      PreferenceGroup debugDebuggingCategory =
          (PreferenceGroup) findPreference(DEBUG_DEBUGGING_CATEGORY_KEY);
      if (debugDebuggingCategory != null) {
        debugDebuggingCategory.removePreference(mVerifyAppsOverUsb);
      } else {
        mVerifyAppsOverUsb.setEnabled(false);
      }
    }
    mStrictMode = findAndInitCheckboxPref(STRICT_MODE_KEY);
    mPointerLocation = findAndInitCheckboxPref(POINTER_LOCATION_KEY);
    mShowTouches = findAndInitCheckboxPref(SHOW_TOUCHES_KEY);
    mShowScreenUpdates = findAndInitCheckboxPref(SHOW_SCREEN_UPDATES_KEY);
    mDisableOverlays = findAndInitCheckboxPref(DISABLE_OVERLAYS_KEY);
    mShowCpuUsage = findAndInitCheckboxPref(SHOW_CPU_USAGE_KEY);
    mForceHardwareUi = findAndInitCheckboxPref(FORCE_HARDWARE_UI_KEY);
    mForceMsaa = findAndInitCheckboxPref(FORCE_MSAA_KEY);
    mTrackFrameTime = findAndInitCheckboxPref(TRACK_FRAME_TIME_KEY);
    mShowHwScreenUpdates = findAndInitCheckboxPref(SHOW_HW_SCREEN_UPDATES_KEY);
    mShowHwLayersUpdates = findAndInitCheckboxPref(SHOW_HW_LAYERS_UPDATES_KEY);
    mShowHwOverdraw = findAndInitCheckboxPref(SHOW_HW_OVERDRAW_KEY);
    mDebugLayout = findAndInitCheckboxPref(DEBUG_LAYOUT_KEY);
    mWindowAnimationScale = (ListPreference) findPreference(WINDOW_ANIMATION_SCALE_KEY);
    mAllPrefs.add(mWindowAnimationScale);
    mWindowAnimationScale.setOnPreferenceChangeListener(this);
    mTransitionAnimationScale = (ListPreference) findPreference(TRANSITION_ANIMATION_SCALE_KEY);
    mAllPrefs.add(mTransitionAnimationScale);
    mTransitionAnimationScale.setOnPreferenceChangeListener(this);
    mAnimatorDurationScale = (ListPreference) findPreference(ANIMATOR_DURATION_SCALE_KEY);
    mAllPrefs.add(mAnimatorDurationScale);
    mAnimatorDurationScale.setOnPreferenceChangeListener(this);
    mOverlayDisplayDevices = (ListPreference) findPreference(OVERLAY_DISPLAY_DEVICES_KEY);
    mAllPrefs.add(mOverlayDisplayDevices);
    mOverlayDisplayDevices.setOnPreferenceChangeListener(this);
    mOpenGLTraces = (ListPreference) findPreference(OPENGL_TRACES_KEY);
    mAllPrefs.add(mOpenGLTraces);
    mOpenGLTraces.setOnPreferenceChangeListener(this);
    mEnableTracesPref = (MultiCheckPreference) findPreference(ENABLE_TRACES_KEY);
    String[] traceValues = new String[Trace.TRACE_TAGS.length];
    for (int i = Trace.TRACE_FLAGS_START_BIT; i < traceValues.length; i++) {
      traceValues[i] = Integer.toString(1 << i);
    }
    mEnableTracesPref.setEntries(Trace.TRACE_TAGS);
    mEnableTracesPref.setEntryValues(traceValues);
    mAllPrefs.add(mEnableTracesPref);
    mEnableTracesPref.setOnPreferenceChangeListener(this);

    mImmediatelyDestroyActivities =
        (CheckBoxPreference) findPreference(IMMEDIATELY_DESTROY_ACTIVITIES_KEY);
    mAllPrefs.add(mImmediatelyDestroyActivities);
    mResetCbPrefs.add(mImmediatelyDestroyActivities);
    mAppProcessLimit = (ListPreference) findPreference(APP_PROCESS_LIMIT_KEY);
    mAllPrefs.add(mAppProcessLimit);
    mAppProcessLimit.setOnPreferenceChangeListener(this);

    mShowAllANRs = (CheckBoxPreference) findPreference(SHOW_ALL_ANRS_KEY);
    mAllPrefs.add(mShowAllANRs);
    mResetCbPrefs.add(mShowAllANRs);

    mKillAppLongpressBack = findAndInitCheckboxPref(KILL_APP_LONGPRESS_BACK);

    Preference hdcpChecking = findPreference(HDCP_CHECKING_KEY);
    if (hdcpChecking != null) {
      mAllPrefs.add(hdcpChecking);
    }
    removeHdcpOptionsForProduction();
  }