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);
  }
  /** 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);
  }
예제 #3
0
  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;
  }
  /** 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);
      }
    }
  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;
    }
  }
 /**
  * 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;
 }
예제 #10
0
 private void writeAppProcessLimitOptions(Object newValue) {
   try {
     int limit = Integer.parseInt(newValue.toString());
     ActivityManagerNative.getDefault().setProcessLimit(limit);
     updateAppProcessLimitOptions();
   } catch (RemoteException e) {
   }
 }
예제 #11
0
 private static void sendCloseSystemWindows(Context context, String reason) {
   if (ActivityManagerNative.isSystemReady()) {
     try {
       ActivityManagerNative.getDefault().closeSystemDialogs(reason);
     } catch (RemoteException e) {
     }
   }
 }
 private void handleToggleLargeTextPreferenceClick() {
   try {
     mCurConfig.fontScale = mToggleLargeTextPreference.isChecked() ? LARGE_FONT_SCALE : 1;
     ActivityManagerNative.getDefault().updatePersistentConfiguration(mCurConfig);
   } catch (RemoteException re) {
     /* ignore */
   }
 }
 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");
   }
 }
 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();
 }
예제 #15
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);
            }
        }
    }
  /** 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 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 */
   }
 }
 /**
  * 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]));
  }
예제 #22
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;
 }
예제 #23
0
 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) {
   }
 }
예제 #24
0
  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();
    }
  }
예제 #26
0
  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;
  }
    private void sendConfigurationAndStartDreamOrDockAppLocked(String category) {
        // Update the configuration but don't send it yet.
        mHoldingConfiguration = false;
        updateConfigurationLocked();

        // Start the dock app, if there is one.
        boolean dockAppStarted = false;
        if (category != null) {
            // Now we are going to be careful about switching the
            // configuration and starting the activity -- we need to
            // do this in a specific order under control of the
            // activity manager, to do it cleanly.  So compute the
            // new config, but don't set it yet, and let the
            // activity manager take care of both the start and config
            // change.
            Intent homeIntent = buildHomeIntent(category);
            if (Sandman.shouldStartDockApp(getContext(), homeIntent)) {
                try {
                    int result = ActivityManagerNative.getDefault().startActivityWithConfig(
                            null, null, homeIntent, null, null, null, 0, 0,
                            mConfiguration, null, UserHandle.USER_CURRENT);
                    if (result >= ActivityManager.START_SUCCESS) {
                        dockAppStarted = true;
                    } else if (result != ActivityManager.START_INTENT_NOT_RESOLVED) {
                        Slog.e(TAG, "Could not start dock app: " + homeIntent
                                + ", startActivityWithConfig result " + result);
                    }
                } catch (RemoteException ex) {
                    Slog.e(TAG, "Could not start dock app: " + homeIntent, ex);
                }
            }
        }

        // Send the new configuration.
        sendConfigurationLocked();

        // If we did not start a dock app, then start dreaming if supported.
        if (category != null && !dockAppStarted) {
            Sandman.startDreamWhenDockedIfAppropriate(getContext());
        }
    }
 private void killProcess() {
   try {
     final Intent intent = new Intent(Intent.ACTION_MAIN);
     String defaultHomePackage = "com.android.launcher";
     intent.addCategory(Intent.CATEGORY_HOME);
     final ResolveInfo res = mContext.getPackageManager().resolveActivity(intent, 0);
     if (res.activityInfo != null && !res.activityInfo.packageName.equals("android")) {
       defaultHomePackage = res.activityInfo.packageName;
     }
     boolean targetKilled = false;
     IActivityManager am = ActivityManagerNative.getDefault();
     List<RunningAppProcessInfo> apps = am.getRunningAppProcesses();
     for (RunningAppProcessInfo appInfo : apps) {
       int uid = appInfo.uid;
       // Make sure it's a foreground user application (not system,
       // root, phone, etc.)
       if (uid >= Process.FIRST_APPLICATION_UID
           && uid <= Process.LAST_APPLICATION_UID
           && appInfo.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
         if (appInfo.pkgList != null && (appInfo.pkgList.length > 0)) {
           for (String pkg : appInfo.pkgList) {
             if (!pkg.equals("com.android.systemui") && !pkg.equals(defaultHomePackage)) {
               am.forceStopPackage(pkg);
               targetKilled = true;
               break;
             }
           }
         } else {
           Process.killProcess(appInfo.pid);
           targetKilled = true;
         }
       }
       if (targetKilled) {
         Toast.makeText(mContext, R.string.app_killed_message, Toast.LENGTH_SHORT).show();
         break;
       }
     }
   } catch (RemoteException remoteException) {
     // Do nothing; just let it go.
   }
 }
예제 #29
0
  private static boolean switchToLastAppInternal(Context context, int userId)
      throws RemoteException {
    ActivityManager.RecentTaskInfo lastTask = getLastTask(context, userId);

    if (lastTask == null || lastTask.id < 0) {
      return false;
    }

    final String packageName = lastTask.baseIntent.getComponent().getPackageName();
    final IActivityManager am = ActivityManagerNative.getDefault();
    final ActivityOptions opts =
        ActivityOptions.makeCustomAnimation(
            context,
            com.android.internal.R.anim.last_app_in,
            com.android.internal.R.anim.last_app_out);

    if (DEBUG) Log.d(TAG, "switching to " + packageName);
    sendCloseSystemWindows(context, null);
    am.moveTaskToFront(lastTask.id, ActivityManager.MOVE_TASK_NO_USER_ACTION, opts.toBundle());

    return true;
  }
 @Override
 public boolean isAppInactive(String packageName, int userId) {
   try {
     userId =
         ActivityManagerNative.getDefault()
             .handleIncomingUser(
                 Binder.getCallingPid(),
                 Binder.getCallingUid(),
                 userId,
                 false,
                 true,
                 "isAppInactive",
                 null);
   } catch (RemoteException re) {
     return false;
   }
   final long token = Binder.clearCallingIdentity();
   try {
     return UsageStatsService.this.isAppIdleFiltered(packageName, userId);
   } finally {
     Binder.restoreCallingIdentity(token);
   }
 }