private static void sendCloseSystemWindows(Context context, String reason) {
   if (ActivityManagerNative.isSystemReady()) {
     try {
       ActivityManagerNative.getDefault().closeSystemDialogs(reason);
     } catch (RemoteException e) {
     }
   }
 }
  private void initializeCarrierApps() {
    // Initialize carrier apps:
    // -Now (on system startup)
    // -Whenever new carrier privilege rules might change (new SIM is loaded)
    // -Whenever we switch to a new user
    mCurrentlyActiveUserId = 0;
    try {
      ActivityManagerNative.getDefault()
          .registerUserSwitchObserver(
              new IUserSwitchObserver.Stub() {
                @Override
                public void onUserSwitching(int newUserId, IRemoteCallback reply)
                    throws RemoteException {
                  mCurrentlyActiveUserId = newUserId;
                  CarrierAppUtils.disableCarrierAppsUntilPrivileged(
                      mContext.getOpPackageName(),
                      mPackageManager,
                      TelephonyManager.getDefault(),
                      mCurrentlyActiveUserId);

                  if (reply != null) {
                    try {
                      reply.sendResult(null);
                    } catch (RemoteException e) {
                    }
                  }
                }

                @Override
                public void onUserSwitchComplete(int newUserId) {
                  // Ignore.
                }

                @Override
                public void onForegroundProfileSwitch(int newProfileId) throws RemoteException {
                  // Ignore.
                }
              });
      mCurrentlyActiveUserId = ActivityManagerNative.getDefault().getCurrentUser().id;
    } catch (RemoteException e) {
      logd("Couldn't get current user ID; guessing it's 0: " + e.getMessage());
    }
    CarrierAppUtils.disableCarrierAppsUntilPrivileged(
        mContext.getOpPackageName(),
        mPackageManager,
        TelephonyManager.getDefault(),
        mCurrentlyActiveUserId);
  }
  private void run(String[] args) {
    if (args.length < 1) {
      showUsage();
      return;
    }

    mAm = ActivityManagerNative.getDefault();
    if (mAm == null) {
      System.err.println("Error type 2");
      System.err.println("Error: Unable to connect to activity manager; is the system running?");
      showUsage();
      return;
    }

    mArgs = args;

    String op = args[0];
    mNextArg = 1;
    if (op.equals("start")) {
      runStart();
    } else if (op.equals("instrument")) {
      runInstrument();
    } else if (op.equals("broadcast")) {
      sendBroadcast();
    } else if (op.equals("profile")) {
      runProfile();
    } else {
      System.err.println("Error: Unknown command: " + op);
      showUsage();
      return;
    }
  }
  /** Instantiates the clipboard. */
  public ClipboardService(Context context) {
    mContext = context;
    mAm = ActivityManagerNative.getDefault();
    mPm = context.getPackageManager();
    mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
    IBinder permOwner = null;
    try {
      permOwner = mAm.newUriPermissionOwner("clipboard");
    } catch (RemoteException e) {
      Slog.w("clipboard", "AM dead", e);
    }
    mPermissionOwner = permOwner;

    // Remove the clipboard if a user is removed
    IntentFilter userFilter = new IntentFilter();
    userFilter.addAction(Intent.ACTION_USER_REMOVED);
    mContext.registerReceiver(
        new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_USER_REMOVED.equals(action)) {
              removeClipboard(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
            }
          }
        },
        userFilter);
  }
  /** Check all running users' apps to see if they enter an idle state. */
  void checkIdleStates() {
    if (DEBUG) Slog.d(TAG, "Checking idle state");
    final int[] runningUsers;
    try {
      runningUsers = ActivityManagerNative.getDefault().getRunningUserIds();
    } catch (RemoteException re) {
      return;
    }

    for (int i = 0; i < runningUsers.length; i++) {
      final int userId = runningUsers[i];
      List<PackageInfo> packages =
          getContext()
              .getPackageManager()
              .getInstalledPackages(
                  PackageManager.GET_DISABLED_COMPONENTS | PackageManager.GET_UNINSTALLED_PACKAGES,
                  userId);
      synchronized (mLock) {
        final long timeNow = checkAndGetTimeLocked();
        final int packageCount = packages.size();
        for (int p = 0; p < packageCount; p++) {
          final String packageName = packages.get(p).packageName;
          final boolean isIdle = isAppIdleFiltered(packageName, userId);
          mHandler.sendMessage(
              mHandler.obtainMessage(MSG_INFORM_LISTENERS, userId, isIdle ? 1 : 0, packageName));
          mAppIdleHistory.addEntry(packageName, userId, isIdle, timeNow);
        }
      }
    }
    mHandler.sendEmptyMessageDelayed(MSG_CHECK_IDLE_STATES, mCheckIdleIntervalMillis);
  }
  /**
   * 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;
  }
 public void onNotificationError(
     String pkg, String tag, int id, int uid, int initialPid, String message) {
   Slog.d(
       TAG,
       "onNotification error pkg="
           + pkg
           + " tag="
           + tag
           + " id="
           + id
           + "; will crashApplication(uid="
           + uid
           + ", pid="
           + initialPid
           + ")");
   cancelNotification(pkg, tag, id, 0, 0, false);
   long ident = Binder.clearCallingIdentity();
   try {
     ActivityManagerNative.getDefault()
         .crashApplication(
             uid,
             initialPid,
             pkg,
             "Bad notification posted from package " + pkg + ": " + message);
   } catch (RemoteException e) {
   }
   Binder.restoreCallingIdentity(ident);
 }
    public void uncaughtException(Thread t, Throwable e) {
      try {
        // Don't re-enter -- avoid infinite loops if crash-reporting crashes.
        if (mCrashing) return;
        mCrashing = true;

        // Try to end profiling. If a profiler is running at this point, and we kill the
        // process (below), the in-memory buffer will be lost. So try to stop, which will
        // flush the buffer. (This makes method trace profiling useful to debug crashes.)
        if (ActivityThread.currentActivityThread() != null) {
          ActivityThread.currentActivityThread().stopProfiling();
        }

        // Bring up crash dialog, wait for it to be dismissed
        ActivityManagerNative.getDefault()
            .handleApplicationCrash(mApplicationObject, new ApplicationErrorReport.CrashInfo(e));
      } catch (Throwable t2) {
        try {
          Clog_e(TAG, "Error reporting crash", t2);
        } catch (Throwable t3) {
          // Even Clog_e() fails!  Oh well.
        }
      } finally {
        // Try everything to make sure this process goes away.
        Process.killProcess(Process.myPid());
        System.exit(10);
      }
    }
 /**
  * Checks if a media session is created from the most recent app.
  *
  * @param record A media session record to be examined.
  * @return true if the media session's package name equals to the most recent app, false
  *     otherwise.
  */
 private static boolean isFromMostRecentApp(MediaSessionRecord record) {
   if (ActivityManager.getCurrentUser() != record.getUserId()) {
     return false;
   }
   try {
     List<ActivityManager.RecentTaskInfo> tasks =
         ActivityManagerNative.getDefault()
             .getRecentTasks(
                 1,
                 ActivityManager.RECENT_IGNORE_HOME_STACK_TASKS
                     | ActivityManager.RECENT_IGNORE_UNAVAILABLE
                     | ActivityManager.RECENT_INCLUDE_PROFILES
                     | ActivityManager.RECENT_WITH_EXCLUDED,
                 record.getUserId());
     if (tasks != null && !tasks.isEmpty()) {
       ActivityManager.RecentTaskInfo recentTask = tasks.get(0);
       if (recentTask.baseIntent != null)
         return recentTask
             .baseIntent
             .getComponent()
             .getPackageName()
             .equals(record.getPackageName());
     }
   } catch (RemoteException e) {
     return false;
   }
   return false;
 }
  private static boolean killForegroundAppInternal(Context context, int userId)
      throws RemoteException {
    final IActivityManager am = ActivityManagerNative.getDefault();
    String defaultHomePackage = resolveCurrentLauncherPackage(context, userId);

    for (ActivityManager.RunningAppProcessInfo appInfo : am.getRunningAppProcesses()) {
      // Make sure it's a foreground user application (not system, root, phone, etc.)
      int uid = appInfo.uid, importance = appInfo.importance;
      if (uid < Process.FIRST_APPLICATION_UID
          || uid > Process.LAST_APPLICATION_UID
          || importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
        continue;
      }

      if (appInfo.pkgList != null && appInfo.pkgList.length > 0) {
        for (String pkg : appInfo.pkgList) {
          if (!pkg.equals(SYSTEMUI_PACKAGE) && !pkg.equals(defaultHomePackage)) {
            am.forceStopPackage(pkg, userId);
            return true;
          }
        }
      } else {
        Process.killProcess(appInfo.pid);
        return true;
      }
    }

    return false;
  }
 private void writeAppProcessLimitOptions(Object newValue) {
   try {
     int limit = Integer.parseInt(newValue.toString());
     ActivityManagerNative.getDefault().setProcessLimit(limit);
     updateAppProcessLimitOptions();
   } catch (RemoteException e) {
   }
 }
 public void writeFontSizePreference(Object objValue) {
   try {
     mCurConfig.fontScale = Float.parseFloat(objValue.toString());
     ActivityManagerNative.getDefault().updatePersistentConfiguration(mCurConfig);
   } catch (RemoteException e) {
     Log.w(TAG, "Unable to save font size");
   }
 }
 private void handleToggleLargeTextPreferenceClick() {
   try {
     mCurConfig.fontScale = mToggleLargeTextPreference.isChecked() ? LARGE_FONT_SCALE : 1;
     ActivityManagerNative.getDefault().updatePersistentConfiguration(mCurConfig);
   } catch (RemoteException re) {
     /* ignore */
   }
 }
 public RecentsHorizontalScrollView(Context context, AttributeSet attrs) {
   super(context, attrs, 0);
   initScrollView();
   float densityScale = getResources().getDisplayMetrics().density;
   float pagingTouchSlop = ViewConfiguration.get(context).getScaledPagingTouchSlop();
   mSwipeHelper = new SwipeHelper(SwipeHelper.Y, this, context);
   mFadedEdgeDrawHelper = FadedEdgeDrawHelper.create(context, attrs, this, false);
   mRecycledViews = new HashSet<View>();
   mAm = ActivityManagerNative.getDefault();
 }
 private final void shutdownIfNoPower() {
   // shut down gracefully if our battery is critically low and we are not powered.
   // wait until the system has booted before attempting to display the shutdown dialog.
   if (mBatteryLevel <= 5 && !isPowered() && ActivityManagerNative.isSystemReady()) {
     Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
     intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     mContext.startActivity(intent);
   }
 }
 private final void shutdownIfOverTemp() {
   // shut down gracefully if temperature is too high (> 68.0C)
   // wait until the system has booted before attempting to display the shutdown dialog.
   if (mBatteryTemperature > 680 && ActivityManagerNative.isSystemReady()) {
     Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
     intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     mContext.startActivity(intent);
   }
 }
Exemple #17
0
  private CommonManager() {

    mActivityManager = ActivityManagerNative.getDefault();
    if (mActivityManager == null) {
      Log.e(TAG, "What's wrong with system server?");
    }
    mSwip = new SwipAdapter();
    // mSwip = new SwipAdapterTest();

  }
  NotificationManagerService(
      Context context, StatusBarManagerService statusBar, LightsService lights) {
    super();
    mContext = context;
    mAm = ActivityManagerNative.getDefault();
    mSound = new NotificationPlayer(TAG);
    mSound.setUsesWakeLock(context);
    mToastQueue = new ArrayList<ToastRecord>();
    mHandler = new WorkerHandler();

    mStatusBar = statusBar;
    statusBar.setNotificationCallbacks(mNotificationCallbacks);

    mNotificationLight = lights.getLight(LightsService.LIGHT_ID_NOTIFICATIONS);
    mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);

    Resources resources = mContext.getResources();
    mDefaultNotificationColor =
        resources.getColor(com.android.internal.R.color.config_defaultNotificationColor);
    mDefaultNotificationLedOn =
        resources.getInteger(com.android.internal.R.integer.config_defaultNotificationLedOn);
    mDefaultNotificationLedOff =
        resources.getInteger(com.android.internal.R.integer.config_defaultNotificationLedOff);

    // Don't start allowing notifications until the setup wizard has run once.
    // After that, including subsequent boots, init with notifications turned on.
    // This works on the first boot because the setup wizard will toggle this
    // flag at least once and we'll go back to 0 after that.
    if (0
        == Settings.Secure.getInt(
            mContext.getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 0)) {
      mDisabledNotifications = StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
    }

    // register for various Intents
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    filter.addAction(Intent.ACTION_USER_PRESENT);
    mContext.registerReceiver(mIntentReceiver, filter);
    IntentFilter pkgFilter = new IntentFilter();
    pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
    pkgFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
    pkgFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
    pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
    pkgFilter.addDataScheme("package");
    mContext.registerReceiver(mIntentReceiver, pkgFilter);
    IntentFilter sdFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
    mContext.registerReceiver(mIntentReceiver, sdFilter);

    SettingsObserver observer = new SettingsObserver(mHandler);
    observer.observe();
  }
    private void sendConfigurationLocked() {
        if (mSetUiMode != mConfiguration.uiMode) {
            mSetUiMode = mConfiguration.uiMode;

            try {
                ActivityManagerNative.getDefault().updateConfiguration(mConfiguration);
            } catch (RemoteException e) {
                Slog.w(TAG, "Failure communicating with activity manager", e);
            }
        }
    }
 private void handleToggleLargeTextPreferenceClick() {
   float updateFontScale =
       Settings.System.getFloat(getContentResolver(), Settings.System.FONT_SCALE_EXTRALARGE, -1);
   try {
     if (updateFontScale == -1) {
       if (sIsScreenLarge) {
         mCurConfig.fontScale =
             mToggleLargeTextPreference.isChecked() ? LARGE_FONT_SCALE_TABLET : 1;
       } else {
         mCurConfig.fontScale =
             mToggleLargeTextPreference.isChecked() ? LARGE_FONT_SCALE_PHONE : 1;
       }
       ActivityManagerNative.getDefault().updatePersistentConfiguration(mCurConfig);
     } else {
       mCurConfig.fontScale = mToggleLargeTextPreference.isChecked() ? updateFontScale : 1;
       ActivityManagerNative.getDefault().updatePersistentConfiguration(mCurConfig);
     }
   } catch (RemoteException re) {
     /* ignore */
   }
 }
  /** Reads the current font size and sets the value in the summary text */
  public void readFontSizePreference(Preference pref) {
    try {
      mCurConfig.updateFrom(ActivityManagerNative.getDefault().getConfiguration());
    } catch (RemoteException e) {
      Log.w(TAG, "Unable to retrieve font size");
    }

    // report the current size in the summary text
    final Resources res = getResources();
    String fontDesc = FontDialogPreference.getFontSizeDescription(res, mCurConfig.fontScale);
    pref.setSummary(getString(R.string.summary_font_size, fontDesc));
  }
  private final void sendIntent() {
    //  Pack up the values and broadcast them to everyone
    Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_REPLACE_PENDING);

    int icon = getIcon(mBatteryLevel);

    intent.putExtra(BatteryManager.EXTRA_STATUS, mBatteryStatus);
    intent.putExtra(BatteryManager.EXTRA_HEALTH, mBatteryHealth);
    intent.putExtra(BatteryManager.EXTRA_PRESENT, mBatteryPresent);
    intent.putExtra(BatteryManager.EXTRA_LEVEL, mBatteryLevel);
    intent.putExtra(BatteryManager.EXTRA_SCALE, BATTERY_SCALE);
    intent.putExtra(BatteryManager.EXTRA_ICON_SMALL, icon);
    intent.putExtra(BatteryManager.EXTRA_PLUGGED, mPlugType);
    intent.putExtra(BatteryManager.EXTRA_VOLTAGE, mBatteryVoltage);
    intent.putExtra(BatteryManager.EXTRA_TEMPERATURE, mBatteryTemperature);
    intent.putExtra(BatteryManager.EXTRA_TECHNOLOGY, mBatteryTechnology);
    intent.putExtra(BatteryManager.EXTRA_INVALID_CHARGER, mInvalidCharger);

    if (false) {
      Slog.d(
          TAG,
          "level:"
              + mBatteryLevel
              + " scale:"
              + BATTERY_SCALE
              + " status:"
              + mBatteryStatus
              + " health:"
              + mBatteryHealth
              + " present:"
              + mBatteryPresent
              + " voltage: "
              + mBatteryVoltage
              + " temperature: "
              + mBatteryTemperature
              + " technology: "
              + mBatteryTechnology
              + " AC powered:"
              + mAcOnline
              + " USB powered:"
              + mUsbOnline
              + " icon:"
              + icon
              + " invalid charger:"
              + mInvalidCharger);
    }

    ActivityManagerNative.broadcastStickyIntent(intent, null);
  }
 /**
  * Report a serious error in the current process. May or may not cause the process to terminate
  * (depends on system settings).
  *
  * @param tag to record with the error
  * @param t exception describing the error site and conditions
  */
 public static void wtf(String tag, Throwable t, boolean system) {
   try {
     if (ActivityManagerNative.getDefault()
         .handleApplicationWtf(
             mApplicationObject, tag, system, new ApplicationErrorReport.CrashInfo(t))) {
       // The Activity Manager has already written us off -- now exit.
       Process.killProcess(Process.myPid());
       System.exit(10);
     }
   } catch (Throwable t2) {
     Slog.e(TAG, "Error reporting WTF", t2);
     Slog.e(TAG, "Original WTF:", t);
   }
 }
  public void readFontSizePreference(ListPreference pref) {
    try {
      mCurConfig.updateFrom(ActivityManagerNative.getDefault().getConfiguration());
    } catch (RemoteException e) {
      Log.w(TAG, "Unable to retrieve font size");
    }

    // mark the appropriate item in the preferences list
    int index = floatToIndex(mCurConfig.fontScale);
    pref.setValueIndex(index);

    // report the current size in the summary text
    final Resources res = getResources();
    String[] fontSizeNames = res.getStringArray(R.array.entries_font_size);
    pref.setSummary(String.format(res.getString(R.string.summary_font_size), fontSizeNames[index]));
  }
Exemple #25
0
 private boolean isCameraDisabledByDpm() {
   final DevicePolicyManager dpm =
       (DevicePolicyManager) getContext().getSystemService(Context.DEVICE_POLICY_SERVICE);
   if (dpm != null) {
     try {
       final int userId = ActivityManagerNative.getDefault().getCurrentUser().id;
       final int disabledFlags = dpm.getKeyguardDisabledFeatures(null, userId);
       final boolean disabledBecauseKeyguardSecure =
           (disabledFlags & DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA) != 0
               && KeyguardTouchDelegate.getInstance(getContext()).isSecure();
       return dpm.getCameraDisabled(null) || disabledBecauseKeyguardSecure;
     } catch (RemoteException e) {
       Log.e(TAG, "Can't get userId", e);
     }
   }
   return false;
 }
 private void updateAppProcessLimitOptions() {
   try {
     int limit = ActivityManagerNative.getDefault().getProcessLimit();
     CharSequence[] values = mAppProcessLimit.getEntryValues();
     for (int i = 0; i < values.length; i++) {
       int val = Integer.parseInt(values[i].toString());
       if (val >= limit) {
         mAppProcessLimit.setValueIndex(i);
         mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[i]);
         return;
       }
     }
     mAppProcessLimit.setValueIndex(0);
     mAppProcessLimit.setSummary(mAppProcessLimit.getEntries()[0]);
   } catch (RemoteException e) {
   }
 }
  private void runClear() {
    int userId = 0;
    String option = nextOption();
    if (option != null && option.equals("--user")) {
      String optionData = nextOptionData();
      if (optionData == null || !isNumber(optionData)) {
        System.err.println("Error: no USER_ID specified");
        showUsage();
        return;
      } else {
        userId = Integer.parseInt(optionData);
      }
    }

    String pkg = nextArg();
    if (pkg == null) {
      System.err.println("Error: no package specified");
      showUsage();
      return;
    }

    ClearDataObserver obs = new ClearDataObserver();
    try {
      if (!ActivityManagerNative.getDefault().clearApplicationUserData(pkg, obs, userId)) {
        System.err.println("Failed");
      }

      synchronized (obs) {
        while (!obs.finished) {
          try {
            obs.wait();
          } catch (InterruptedException e) {
          }
        }
      }

      if (obs.result) {
        System.err.println("Success");
      } else {
        System.err.println("Failed");
      }
    } catch (RemoteException e) {
      System.err.println(e.toString());
      System.err.println(PM_NOT_RUNNING_ERR);
    }
  }
  /**
   * Handle message sent by {@link #showLocked}.
   *
   * @see #SHOW
   */
  private void handleShow() {
    synchronized (KeyguardViewMediator.this) {
      if (DEBUG) Log.d(TAG, "handleShow");
      if (!mSystemReady) return;

      playSounds(true);

      mKeyguardViewManager.show();
      mShowing = true;
      adjustUserActivityLocked();
      adjustStatusBarLocked();
      try {
        ActivityManagerNative.getDefault().closeSystemDialogs("lock");
      } catch (RemoteException e) {
      }
      mShowKeyguardWakeLock.release();
    }
  }
  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();
  }
  private static ActivityManager.RecentTaskInfo getLastTask(Context context, int userId)
      throws RemoteException {
    final String defaultHomePackage = resolveCurrentLauncherPackage(context, userId);
    final IActivityManager am = ActivityManagerNative.getDefault();
    final List<ActivityManager.RecentTaskInfo> tasks =
        am.getRecentTasks(5, ActivityManager.RECENT_IGNORE_UNAVAILABLE, userId);

    for (int i = 1; i < tasks.size(); i++) {
      ActivityManager.RecentTaskInfo task = tasks.get(i);
      if (task.origActivity != null) {
        task.baseIntent.setComponent(task.origActivity);
      }
      String packageName = task.baseIntent.getComponent().getPackageName();
      if (!packageName.equals(defaultHomePackage) && !packageName.equals(SYSTEMUI_PACKAGE)) {
        return tasks.get(i);
      }
    }

    return null;
  }