private static void ensureThreadLocked() {
   if (sInstance == null) {
     sInstance = new BackgroundThread();
     sInstance.start();
     sInstance.getLooper().setTraceTag(Trace.TRACE_TAG_ACTIVITY_MANAGER);
     sHandler = new Handler(sInstance.getLooper());
   }
 }
  @Override
  public void onStart() {
    mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
    mUserManager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);

    mHandler = new H(BackgroundThread.get().getLooper());

    File systemDataDir = new File(Environment.getDataDirectory(), "system");
    mUsageStatsDir = new File(systemDataDir, "usagestats");
    mUsageStatsDir.mkdirs();
    if (!mUsageStatsDir.exists()) {
      throw new IllegalStateException(
          "Usage stats directory does not exist: " + mUsageStatsDir.getAbsolutePath());
    }

    IntentFilter userActions = new IntentFilter(Intent.ACTION_USER_REMOVED);
    userActions.addAction(Intent.ACTION_USER_STARTED);
    getContext()
        .registerReceiverAsUser(new UserActionsReceiver(), UserHandle.ALL, userActions, null, null);

    IntentFilter deviceStates = new IntentFilter(BatteryManager.ACTION_CHARGING);
    deviceStates.addAction(BatteryManager.ACTION_DISCHARGING);
    deviceStates.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
    getContext().registerReceiver(new DeviceStateReceiver(), deviceStates);
    synchronized (mLock) {
      cleanUpRemovedUsersLocked();
    }

    mRealTimeSnapshot = SystemClock.elapsedRealtime();
    mSystemTimeSnapshot = System.currentTimeMillis();
    // Look at primary user's secure setting for this. TODO: Maybe apply different
    // thresholds for different users.
    mAppIdleDurationMillis =
        Settings.Secure.getLongForUser(
            getContext().getContentResolver(),
            Settings.Secure.APP_IDLE_DURATION,
            DEFAULT_APP_IDLE_THRESHOLD_MILLIS,
            UserHandle.USER_OWNER);

    publishLocalService(UsageStatsManagerInternal.class, new LocalService());
    publishBinderService(Context.USAGE_STATS_SERVICE, new BinderService());
  }