下面列出了android.app.ActivityManager#getCurrentUser ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private boolean checkIfCallerIsForegroundUser() {
int foregroundUser;
int callingUser = UserHandle.getCallingUserId();
int callingUid = Binder.getCallingUid();
long callingIdentity = Binder.clearCallingIdentity();
UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
UserInfo ui = um.getProfileParent(callingUser);
int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
int callingAppId = UserHandle.getAppId(callingUid);
boolean valid = false;
try {
foregroundUser = ActivityManager.getCurrentUser();
valid = (callingUser == foregroundUser) || parentUser == foregroundUser
|| callingAppId == Process.NFC_UID || callingAppId == mSystemUiUid;
if (DBG && !valid) {
Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid + " callingUser="
+ callingUser + " parentUser=" + parentUser + " foregroundUser="
+ foregroundUser);
}
} finally {
Binder.restoreCallingIdentity(callingIdentity);
}
return valid;
}
public void onBootPhase(int phase) {
if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
Resources resources = mContext.getResources();
if (!isGestureLauncherEnabled(resources)) {
if (DBG) Slog.d(TAG, "Gesture launcher is disabled in system properties.");
return;
}
mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class);
mPowerManager = (PowerManager) mContext.getSystemService(
Context.POWER_SERVICE);
mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"GestureLauncherService");
updateCameraRegistered();
updateCameraDoubleTapPowerEnabled();
mUserId = ActivityManager.getCurrentUser();
mContext.registerReceiver(mUserReceiver, new IntentFilter(Intent.ACTION_USER_SWITCHED));
registerContentObservers();
}
}
void switchUser() {
synchronized (mLock) {
int userId = ActivityManager.getCurrentUser();
if (mCurrentUserId != userId) {
final int oldUserId = mCurrentUserId;
mCurrentUserId = userId; // do this first
UserRecord oldUser = mUserRecords.get(oldUserId);
if (oldUser != null) {
oldUser.mHandler.sendEmptyMessage(UserHandler.MSG_STOP);
disposeUserIfNeededLocked(oldUser); // since no longer current user
}
UserRecord newUser = mUserRecords.get(userId);
if (newUser != null) {
newUser.mHandler.sendEmptyMessage(UserHandler.MSG_START);
}
}
}
}
@Override // Binder call
public void testDream(ComponentName dream) {
if (dream == null) {
throw new IllegalArgumentException("dream must not be null");
}
checkPermission(android.Manifest.permission.WRITE_DREAM_STATE);
final int callingUserId = UserHandle.getCallingUserId();
final int currentUserId = ActivityManager.getCurrentUser();
if (callingUserId != currentUserId) {
// This check is inherently prone to races but at least it's something.
Slog.w(TAG, "Aborted attempt to start a test dream while a different "
+ " user is active: callingUserId=" + callingUserId
+ ", currentUserId=" + currentUserId);
return;
}
final long ident = Binder.clearCallingIdentity();
try {
testDreamInternal(dream, callingUserId);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
private boolean validateEventsAndUserLocked(Record r, int events) {
int foregroundUser;
long callingIdentity = Binder.clearCallingIdentity();
boolean valid = false;
try {
foregroundUser = ActivityManager.getCurrentUser();
valid = UserHandle.getUserId(r.callerUid) == foregroundUser
&& r.matchPhoneStateListenerEvent(events);
if (DBG | DBG_LOC) {
log("validateEventsAndUserLocked: valid=" + valid
+ " r.callerUid=" + r.callerUid + " foregroundUser=" + foregroundUser
+ " r.events=" + r.events + " events=" + events);
}
} finally {
Binder.restoreCallingIdentity(callingIdentity);
}
return valid;
}
private int handleIncomingUser(Uri uri, int pid, int uid, int modeFlags, boolean allowNonFull,
int userId) {
if (userId == UserHandle.USER_CURRENT) {
userId = ActivityManager.getCurrentUser();
}
if (userId == UserHandle.USER_ALL) {
mContext.enforceCallingOrSelfPermission(
Manifest.permission.INTERACT_ACROSS_USERS_FULL, TAG);
} else if (userId < 0) {
throw new IllegalArgumentException("Invalid user: " + userId);
} else if (userId != UserHandle.getCallingUserId()) {
if (checkUriPermission(uri, pid, uid, modeFlags,
userId) != PackageManager.PERMISSION_GRANTED) {
boolean allow = false;
if (mContext.checkCallingOrSelfPermission(
Manifest.permission.INTERACT_ACROSS_USERS_FULL)
== PackageManager.PERMISSION_GRANTED) {
allow = true;
} else if (allowNonFull && mContext.checkCallingOrSelfPermission(
Manifest.permission.INTERACT_ACROSS_USERS)
== PackageManager.PERMISSION_GRANTED) {
allow = true;
}
if (!allow) {
final String permissions = allowNonFull
? (Manifest.permission.INTERACT_ACROSS_USERS_FULL + " or " +
Manifest.permission.INTERACT_ACROSS_USERS)
: Manifest.permission.INTERACT_ACROSS_USERS_FULL;
throw new SecurityException(TAG + "Neither user " + uid
+ " nor current process has " + permissions);
}
}
}
return userId;
}
private int handleIncomingUser(Uri uri, int pid, int uid, int modeFlags, boolean allowNonFull,
int userId) {
if (userId == UserHandle.USER_CURRENT) {
userId = ActivityManager.getCurrentUser();
}
if (userId == UserHandle.USER_ALL) {
mContext.enforceCallingOrSelfPermission(
Manifest.permission.INTERACT_ACROSS_USERS_FULL, "No access to " + uri);
} else if (userId < 0) {
throw new IllegalArgumentException("Invalid user: " + userId);
} else if (userId != UserHandle.getCallingUserId()) {
if (checkUriPermission(uri, pid, uid, modeFlags,
userId) != PackageManager.PERMISSION_GRANTED) {
boolean allow = false;
if (mContext.checkCallingOrSelfPermission(
Manifest.permission.INTERACT_ACROSS_USERS_FULL)
== PackageManager.PERMISSION_GRANTED) {
allow = true;
} else if (allowNonFull && mContext.checkCallingOrSelfPermission(
Manifest.permission.INTERACT_ACROSS_USERS)
== PackageManager.PERMISSION_GRANTED) {
allow = true;
}
if (!allow) {
final String permissions = allowNonFull
? (Manifest.permission.INTERACT_ACROSS_USERS_FULL + " or " +
Manifest.permission.INTERACT_ACROSS_USERS)
: Manifest.permission.INTERACT_ACROSS_USERS_FULL;
throw new SecurityException("No access to " + uri + ": neither user " + uid
+ " nor current process has " + permissions);
}
}
}
return userId;
}
/**
* Start listening for brightness slider events
*
* @param initialBrightness the initial screen brightness
*/
public void start(float initialBrightness) {
if (DEBUG) {
Slog.d(TAG, "Start");
}
mCurrentUserId = ActivityManager.getCurrentUser();
mBgHandler.obtainMessage(MSG_BACKGROUND_START, (Float) initialBrightness).sendToTarget();
}
private int getLockoutMode() {
final int currentUser = ActivityManager.getCurrentUser();
final int failedAttempts = mFailedAttempts.get(currentUser, 0);
if (failedAttempts >= MAX_FAILED_ATTEMPTS_LOCKOUT_PERMANENT) {
return AuthenticationClient.LOCKOUT_PERMANENT;
} else if (failedAttempts > 0 &&
mTimedLockoutCleared.get(currentUser, false) == false
&& (failedAttempts % MAX_FAILED_ATTEMPTS_LOCKOUT_TIMED == 0)) {
return AuthenticationClient.LOCKOUT_TIMED;
}
return AuthenticationClient.LOCKOUT_NONE;
}
private int timeout(PrintWriter pw) throws Exception {
checkPermission("force timeout jobs");
int userId = UserHandle.USER_ALL;
String opt;
while ((opt = getNextOption()) != null) {
switch (opt) {
case "-u":
case "--user":
userId = UserHandle.parseUserArg(getNextArgRequired());
break;
default:
pw.println("Error: unknown option '" + opt + "'");
return -1;
}
}
if (userId == UserHandle.USER_CURRENT) {
userId = ActivityManager.getCurrentUser();
}
final String pkgName = getNextArg();
final String jobIdStr = getNextArg();
final int jobId = jobIdStr != null ? Integer.parseInt(jobIdStr) : -1;
final long ident = Binder.clearCallingIdentity();
try {
return mInternal.executeTimeoutCommand(pw, pkgName, userId, jobIdStr != null, jobId);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
private int getJobState(PrintWriter pw) throws Exception {
checkPermission("force timeout jobs");
int userId = UserHandle.USER_SYSTEM;
String opt;
while ((opt = getNextOption()) != null) {
switch (opt) {
case "-u":
case "--user":
userId = UserHandle.parseUserArg(getNextArgRequired());
break;
default:
pw.println("Error: unknown option '" + opt + "'");
return -1;
}
}
if (userId == UserHandle.USER_CURRENT) {
userId = ActivityManager.getCurrentUser();
}
final String pkgName = getNextArgRequired();
final String jobIdStr = getNextArgRequired();
final int jobId = Integer.parseInt(jobIdStr);
final long ident = Binder.clearCallingIdentity();
try {
int ret = mInternal.getJobState(pw, pkgName, userId, jobId);
printError(ret, pkgName, userId, jobId);
return ret;
} finally {
Binder.restoreCallingIdentity(ident);
}
}
/**
* Update the currently pinned files.
* Specifically, this only updates pinning for the apps that need to be pinned.
* The other files pinned in onStart will not need to be updated.
*/
public void update(ArraySet<String> updatedPackages, boolean force) {
int currentUser = ActivityManager.getCurrentUser();
for (int i = mPinKeys.size() - 1; i >= 0; i--) {
int key = mPinKeys.valueAt(i);
ApplicationInfo info = getInfoForKey(key, currentUser);
if (info != null && updatedPackages.contains(info.packageName)) {
Slog.i(TAG, "Updating pinned files for " + info.packageName + " force=" + force);
sendPinAppMessage(key, currentUser, force);
}
}
}
public KeyguardStateMonitor(Context context, IKeyguardService service, StateCallback callback) {
mLockPatternUtils = new LockPatternUtils(context);
mCurrentUserId = ActivityManager.getCurrentUser();
mCallback = callback;
mKeystoreService = IKeystoreService.Stub.asInterface(ServiceManager
.getService("android.security.keystore"));
try {
service.addStateMonitorCallback(this);
} catch (RemoteException e) {
Slog.w(TAG, "Remote Exception", e);
}
}
private int handleIncomingUser(Uri uri, int pid, int uid, int modeFlags, boolean allowNonFull,
int userId) {
if (userId == UserHandle.USER_CURRENT) {
userId = ActivityManager.getCurrentUser();
}
if (userId == UserHandle.USER_ALL) {
mContext.enforceCallingOrSelfPermission(
Manifest.permission.INTERACT_ACROSS_USERS_FULL, TAG);
} else if (userId < 0) {
throw new IllegalArgumentException("Invalid user: " + userId);
} else if (userId != UserHandle.getCallingUserId()) {
if (checkUriPermission(uri, pid, uid, modeFlags,
userId) != PackageManager.PERMISSION_GRANTED) {
boolean allow = false;
if (mContext.checkCallingOrSelfPermission(
Manifest.permission.INTERACT_ACROSS_USERS_FULL)
== PackageManager.PERMISSION_GRANTED) {
allow = true;
} else if (allowNonFull && mContext.checkCallingOrSelfPermission(
Manifest.permission.INTERACT_ACROSS_USERS)
== PackageManager.PERMISSION_GRANTED) {
allow = true;
}
if (!allow) {
final String permissions = allowNonFull
? (Manifest.permission.INTERACT_ACROSS_USERS_FULL + " or " +
Manifest.permission.INTERACT_ACROSS_USERS)
: Manifest.permission.INTERACT_ACROSS_USERS_FULL;
throw new SecurityException(TAG + "Neither user " + uid
+ " nor current process has " + permissions);
}
}
}
return userId;
}
@Override
public void removeAllUsers() {
if (UserHandle.USER_SYSTEM == ActivityManager.getCurrentUser()) {
// Remove the non-system users straight away.
removeNonSystemUsers();
} else {
// Switch to the system user first and then remove the other users.
BroadcastReceiver userSwitchedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int userId =
intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
if (userId != UserHandle.USER_SYSTEM) {
return;
}
mContext.unregisterReceiver(this);
removeNonSystemUsers();
}
};
IntentFilter userSwitchedFilter = new IntentFilter();
userSwitchedFilter.addAction(Intent.ACTION_USER_SWITCHED);
mContext.registerReceiver(
userSwitchedReceiver, userSwitchedFilter, null, mHandler);
// Switch to the system user.
ActivityManager am =
(ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
am.switchUser(UserHandle.USER_SYSTEM);
}
}
private void updateUser() {
synchronized (mLock) {
UserManager manager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
mFullUserIds.clear();
List<UserInfo> allUsers = manager.getUsers();
if (allUsers != null) {
for (UserInfo userInfo : allUsers) {
if (userInfo.isManagedProfile()) {
mFullUserIds.put(userInfo.id, userInfo.profileGroupId);
} else {
mFullUserIds.put(userInfo.id, userInfo.id);
if (mUserRecords.get(userInfo.id) == null) {
mUserRecords.put(userInfo.id, new FullUserRecord(userInfo.id));
}
}
}
}
// Ensure that the current full user exists.
int currentFullUserId = ActivityManager.getCurrentUser();
mCurrentFullUserRecord = mUserRecords.get(currentFullUserId);
if (mCurrentFullUserRecord == null) {
Log.w(TAG, "Cannot find FullUserInfo for the current user " + currentFullUserId);
mCurrentFullUserRecord = new FullUserRecord(currentFullUserId);
mUserRecords.put(currentFullUserId, mCurrentFullUserRecord);
}
mFullUserIds.put(currentFullUserId, currentFullUserId);
}
}
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Entered OnReceive in NetworkConnectedReceiver");
//Skipping non admin users
if (ActivityManager.getCurrentUser() != 0) {
Log.i(TAG, "The user serial number is " + ActivityManager.getCurrentUser());
} else {
Log.i(TAG, "The user is admin");
SharedPreferences prefs = context.getSharedPreferences(EMM_PREFERENCES, Context.MODE_PRIVATE);
Boolean isAgentCalled = prefs.getBoolean(EMM_AGENT_HAS_BEEN_CALLED, false);
if (!isAgentCalled) {
//Check network connected
if (isConnected(context)) {
Intent agentLauncherIntent = new Intent();
agentLauncherIntent.setComponent(new ComponentName(Constants.AGENT_APP_PACKAGE_NAME,
Constants.AGENT_APP_PACKAGE_NAME + Constants.AGENT_APP_LAUNCH_ACTIVITY));
agentLauncherIntent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
agentLauncherIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(agentLauncherIntent);
Editor editor = prefs.edit();
editor.putBoolean(EMM_AGENT_HAS_BEEN_CALLED, true);
editor.apply();
Log.i(TAG, "EMM agent has been called");
}
}
}
}
/**
* Called when a user, package, or setting changes that could affect whether or not the
* currently bound VrListenerService is changed.
*/
@Override
public void onEnabledComponentChanged() {
synchronized (mLock) {
int currentUser = ActivityManager.getCurrentUser();
// Update listeners
ArraySet<ComponentName> enabledListeners = mComponentObserver.getEnabled(currentUser);
ArraySet<String> enabledPackages = new ArraySet<>();
for (ComponentName n : enabledListeners) {
String pkg = n.getPackageName();
if (isDefaultAllowed(pkg)) {
enabledPackages.add(n.getPackageName());
}
}
mNotifAccessManager.update(enabledPackages);
if (!mVrModeAllowed) {
return; // Don't do anything, we shouldn't be in VR mode.
}
// If there is a pending state change, we'd better deal with that first
consumeAndApplyPendingStateLocked(false);
if (mCurrentVrService == null) {
return; // No active services
}
// There is an active service, update it if needed
updateCurrentVrServiceLocked(mVrModeEnabled, mRunning2dInVr,
mCurrentVrService.getComponent(), mCurrentVrService.getUserId(),
mVrAppProcessId, mCurrentVrModeComponent);
}
}
private void saveSnoozedLocked() {
final String setting = TextUtils.join(SEPARATOR, mSnoozedForAlarm);
final int currentUser = ActivityManager.getCurrentUser();
Settings.Secure.putStringForUser(mContext.getContentResolver(),
SCP_SETTING,
setting,
currentUser);
}
public void updateCache(@NonNull Context context) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
if (userManager != null) {
int currentUserId = ActivityManager.getCurrentUser();
List<UserInfo> profiles = userManager.getProfiles(currentUserId);
synchronized (mCurrentProfiles) {
mCurrentProfiles.clear();
for (UserInfo user : profiles) {
mCurrentProfiles.put(user.id, user);
}
}
}
}