Java Code Examples for android.os.UserHandle#getUserId()
The following examples show how to use
android.os.UserHandle#getUserId() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RemoteViews.java From android_9.0.0_r45 with Apache License 2.0 | 7 votes |
private Context getContextForResources(Context context) { if (mApplication != null) { if (context.getUserId() == UserHandle.getUserId(mApplication.uid) && context.getPackageName().equals(mApplication.packageName)) { return context; } try { return context.createApplicationContext(mApplication, Context.CONTEXT_RESTRICTED); } catch (NameNotFoundException e) { Log.e(LOG_TAG, "Package name " + mApplication.packageName + " not found"); } } return context; }
Example 2
Source File: ContextImpl.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
@Override public Context createApplicationContext(ApplicationInfo application, int flags) throws NameNotFoundException { LoadedApk pi = mMainThread.getPackageInfo(application, mResources.getCompatibilityInfo(), flags | CONTEXT_REGISTER_PACKAGE); if (pi != null) { ContextImpl c = new ContextImpl(this, mMainThread, pi, null, mActivityToken, new UserHandle(UserHandle.getUserId(application.uid)), flags, null); final int displayId = mDisplay != null ? mDisplay.getDisplayId() : Display.DEFAULT_DISPLAY; c.setResources(createResources(mActivityToken, pi, null, displayId, null, getDisplayAdjustments(displayId).getCompatibilityInfo())); if (c.mResources != null) { return c; } } throw new PackageManager.NameNotFoundException( "Application package " + application.packageName + " not found"); }
Example 3
Source File: ServiceRecord.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
ServiceRecord(ActivityManagerService ams, BatteryStatsImpl.Uid.Pkg.Serv servStats, ComponentName name, Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg, Runnable restarter) { this.ams = ams; this.stats = servStats; this.name = name; shortName = name.flattenToShortString(); this.intent = intent; serviceInfo = sInfo; appInfo = sInfo.applicationInfo; packageName = sInfo.applicationInfo.packageName; processName = sInfo.processName; permission = sInfo.permission; exported = sInfo.exported; this.restarter = restarter; createRealTime = SystemClock.elapsedRealtime(); lastActivity = SystemClock.uptimeMillis(); userId = UserHandle.getUserId(appInfo.uid); createdFromFg = callerIsFg; }
Example 4
Source File: DragState.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
void broadcastDragStartedLocked(final float touchX, final float touchY) { mOriginalX = mCurrentX = touchX; mOriginalY = mCurrentY = touchY; // Cache a base-class instance of the clip metadata so that parceling // works correctly in calling out to the apps. mDataDescription = (mData != null) ? mData.getDescription() : null; mNotifiedWindows.clear(); mDragInProgress = true; mSourceUserId = UserHandle.getUserId(mUid); final UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.class); mCrossProfileCopyAllowed = !userManager.getUserRestriction( mSourceUserId, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE); if (DEBUG_DRAG) { Slog.d(TAG_WM, "broadcasting DRAG_STARTED at (" + touchX + ", " + touchY + ")"); } mDisplayContent.forAllWindows(w -> { sendDragStartedLocked(w, touchX, touchY, mDataDescription); }, false /* traverseTopToBottom */ ); }
Example 5
Source File: AppOpsService.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
private boolean isOpRestrictedLocked(int uid, int code, String packageName) { int userHandle = UserHandle.getUserId(uid); final int restrictionSetCount = mOpUserRestrictions.size(); for (int i = 0; i < restrictionSetCount; i++) { // For each client, check that the given op is not restricted, or that the given // package is exempt from the restriction. ClientRestrictionState restrictionState = mOpUserRestrictions.valueAt(i); if (restrictionState.hasRestriction(code, packageName, userHandle)) { if (AppOpsManager.opAllowSystemBypassRestriction(code)) { // If we are the system, bypass user restrictions for certain codes synchronized (this) { Ops ops = getOpsRawLocked(uid, packageName, true /* edit */, false /* uidMismatchExpected */); if ((ops != null) && ops.isPrivileged) { return false; } } } return true; } } return false; }
Example 6
Source File: RegisteredServicesCache.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Read all sync status back in to the initial engine state. */ private void readPersistentServicesLocked(InputStream is) throws XmlPullParserException, IOException { XmlPullParser parser = Xml.newPullParser(); parser.setInput(is, StandardCharsets.UTF_8.name()); int eventType = parser.getEventType(); while (eventType != XmlPullParser.START_TAG && eventType != XmlPullParser.END_DOCUMENT) { eventType = parser.next(); } String tagName = parser.getName(); if ("services".equals(tagName)) { eventType = parser.next(); do { if (eventType == XmlPullParser.START_TAG && parser.getDepth() == 2) { tagName = parser.getName(); if ("service".equals(tagName)) { V service = mSerializerAndParser.createFromXml(parser); if (service == null) { break; } String uidString = parser.getAttributeValue(null, "uid"); final int uid = Integer.parseInt(uidString); final int userId = UserHandle.getUserId(uid); final UserServices<V> user = findOrCreateUserLocked(userId, false /*loadFromFileIfNew*/) ; user.persistentServices.put(service, uid); } } eventType = parser.next(); } while (eventType != XmlPullParser.END_DOCUMENT); } }
Example 7
Source File: ActiveServices.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) { int userId = UserHandle.getUserId(Binder.getCallingUid()); ServiceRecord r = getServiceByNameLocked(name, userId); if (r != null) { for (int conni=r.connections.size()-1; conni>=0; conni--) { ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni); for (int i=0; i<conn.size(); i++) { if (conn.get(i).clientIntent != null) { return conn.get(i).clientIntent; } } } } return null; }
Example 8
Source File: AppOpsService.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
private void removeUidsForUserLocked(int userHandle) { for (int i = mUidStates.size() - 1; i >= 0; --i) { final int uid = mUidStates.keyAt(i); if (UserHandle.getUserId(uid) == userHandle) { mUidStates.removeAt(i); } } }
Example 9
Source File: UserManagerService.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
@Override public long getUserStartRealtime() { final int userId = UserHandle.getUserId(Binder.getCallingUid()); synchronized (mUsersLock) { final UserData user = getUserDataLU(userId); if (user != null) { return user.startRealtime; } return 0; } }
Example 10
Source File: AppErrors.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
void resetProcessCrashTimeLocked(boolean resetEntireUser, int appId, int userId) { final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap(); for (int ip = pmap.size() - 1; ip >= 0; ip--) { SparseArray<Long> ba = pmap.valueAt(ip); for (int i = ba.size() - 1; i >= 0; i--) { boolean remove = false; final int entUid = ba.keyAt(i); if (!resetEntireUser) { if (userId == UserHandle.USER_ALL) { if (UserHandle.getAppId(entUid) == appId) { remove = true; } } else { if (entUid == UserHandle.getUid(userId, appId)) { remove = true; } } } else if (UserHandle.getUserId(entUid) == userId) { remove = true; } if (remove) { ba.removeAt(i); } } if (ba.size() == 0) { pmap.removeAt(ip); } } }
Example 11
Source File: AlarmManagerService.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Adjusts the alarm delivery time based on the current app standby bucket. * @param alarm The alarm to adjust * @return true if the alarm delivery time was updated. */ private boolean adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) { if (isExemptFromAppStandby(alarm)) { return false; } if (mAppStandbyParole) { if (alarm.whenElapsed > alarm.expectedWhenElapsed) { // We did defer this alarm earlier, restore original requirements alarm.whenElapsed = alarm.expectedWhenElapsed; alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed; return true; } return false; } final long oldWhenElapsed = alarm.whenElapsed; final long oldMaxWhenElapsed = alarm.maxWhenElapsed; final String sourcePackage = alarm.sourcePackage; final int sourceUserId = UserHandle.getUserId(alarm.creatorUid); final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket( sourcePackage, sourceUserId, SystemClock.elapsedRealtime()); final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId); final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L); if (lastElapsed > 0) { final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket); if (alarm.expectedWhenElapsed < minElapsed) { alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed; } else { // app is now eligible to run alarms at the originally requested window. // Restore original requirements in case they were changed earlier. alarm.whenElapsed = alarm.expectedWhenElapsed; alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed; } } return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed); }
Example 12
Source File: AccountManagerBackupHelper.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
@Override public void onPackageAdded(String packageName, int uid) { synchronized (mLock) { if (mRestorePendingAppPermissions == null) { return; } if (UserHandle.getUserId(uid) != UserHandle.USER_SYSTEM) { return; } final int count = mRestorePendingAppPermissions.size(); for (int i = count - 1; i >= 0; i--) { PendingAppPermission pendingAppPermission = mRestorePendingAppPermissions.get(i); if (!pendingAppPermission.packageName.equals(packageName)) { continue; } if (pendingAppPermission.apply( mAccountManagerService.mContext.getPackageManager())) { mRestorePendingAppPermissions.remove(i); } } if (mRestorePendingAppPermissions.isEmpty() && mRestoreCancelCommand != null) { mAccountManagerService.mHandler.removeCallbacks(mRestoreCancelCommand); mRestoreCancelCommand.run(); mRestoreCancelCommand = null; } } }
Example 13
Source File: JobStatus.java From android_9.0.0_r45 with Apache License 2.0 | 4 votes |
/** * Core constructor for JobStatus instances. All other ctors funnel down to this one. * * @param job The actual requested parameters for the job * @param callingUid Identity of the app that is scheduling the job. This may not be the * app in which the job is implemented; such as with sync jobs. * @param targetSdkVersion The targetSdkVersion of the app in which the job will run. * @param sourcePackageName The package name of the app in which the job will run. * @param sourceUserId The user in which the job will run * @param standbyBucket The standby bucket that the source package is currently assigned to, * cached here for speed of handling during runnability evaluations (and updated when bucket * assignments are changed) * @param heartbeat Timestamp of when the job was created, in the standby-related * timebase. * @param tag A string associated with the job for debugging/logging purposes. * @param numFailures Count of how many times this job has requested a reschedule because * its work was not yet finished. * @param earliestRunTimeElapsedMillis Milestone: earliest point in time at which the job * is to be considered runnable * @param latestRunTimeElapsedMillis Milestone: point in time at which the job will be * considered overdue * @param lastSuccessfulRunTime When did we last run this job to completion? * @param lastFailedRunTime When did we last run this job only to have it stop incomplete? * @param internalFlags Non-API property flags about this job */ private JobStatus(JobInfo job, int callingUid, int targetSdkVersion, String sourcePackageName, int sourceUserId, int standbyBucket, long heartbeat, String tag, int numFailures, long earliestRunTimeElapsedMillis, long latestRunTimeElapsedMillis, long lastSuccessfulRunTime, long lastFailedRunTime, int internalFlags) { this.job = job; this.callingUid = callingUid; this.targetSdkVersion = targetSdkVersion; this.standbyBucket = standbyBucket; this.baseHeartbeat = heartbeat; int tempSourceUid = -1; if (sourceUserId != -1 && sourcePackageName != null) { try { tempSourceUid = AppGlobals.getPackageManager().getPackageUid(sourcePackageName, 0, sourceUserId); } catch (RemoteException ex) { // Can't happen, PackageManager runs in the same process. } } if (tempSourceUid == -1) { this.sourceUid = callingUid; this.sourceUserId = UserHandle.getUserId(callingUid); this.sourcePackageName = job.getService().getPackageName(); this.sourceTag = null; } else { this.sourceUid = tempSourceUid; this.sourceUserId = sourceUserId; this.sourcePackageName = sourcePackageName; this.sourceTag = tag; } this.batteryName = this.sourceTag != null ? this.sourceTag + ":" + job.getService().getPackageName() : job.getService().flattenToShortString(); this.tag = "*job*/" + this.batteryName; this.earliestRunTimeElapsedMillis = earliestRunTimeElapsedMillis; this.latestRunTimeElapsedMillis = latestRunTimeElapsedMillis; this.numFailures = numFailures; int requiredConstraints = job.getConstraintFlags(); if (job.getRequiredNetwork() != null) { requiredConstraints |= CONSTRAINT_CONNECTIVITY; } if (earliestRunTimeElapsedMillis != NO_EARLIEST_RUNTIME) { requiredConstraints |= CONSTRAINT_TIMING_DELAY; } if (latestRunTimeElapsedMillis != NO_LATEST_RUNTIME) { requiredConstraints |= CONSTRAINT_DEADLINE; } if (job.getTriggerContentUris() != null) { requiredConstraints |= CONSTRAINT_CONTENT_TRIGGER; } this.requiredConstraints = requiredConstraints; mLastSuccessfulRunTime = lastSuccessfulRunTime; mLastFailedRunTime = lastFailedRunTime; mInternalFlags = internalFlags; updateEstimatedNetworkBytesLocked(); if (job.getRequiredNetwork() != null) { // Later, when we check if a given network satisfies the required // network, we need to know the UID that is requesting it, so push // our source UID into place. job.getRequiredNetwork().networkCapabilities.setSingleUid(this.sourceUid); } }
Example 14
Source File: JobStatus.java From android_9.0.0_r45 with Apache License 2.0 | 4 votes |
public int getUserId() { return UserHandle.getUserId(callingUid); }
Example 15
Source File: StorageManagerService.java From android_9.0.0_r45 with Apache License 2.0 | 4 votes |
@Override public StorageVolume[] getVolumeList(int uid, String packageName, int flags) { final int userId = UserHandle.getUserId(uid); final boolean forWrite = (flags & StorageManager.FLAG_FOR_WRITE) != 0; final boolean realState = (flags & StorageManager.FLAG_REAL_STATE) != 0; final boolean includeInvisible = (flags & StorageManager.FLAG_INCLUDE_INVISIBLE) != 0; final boolean userKeyUnlocked; final boolean storagePermission; final long token = Binder.clearCallingIdentity(); try { userKeyUnlocked = isUserKeyUnlocked(userId); storagePermission = mStorageManagerInternal.hasExternalStorage(uid, packageName); } finally { Binder.restoreCallingIdentity(token); } boolean foundPrimary = false; final ArrayList<StorageVolume> res = new ArrayList<>(); synchronized (mLock) { for (int i = 0; i < mVolumes.size(); i++) { final VolumeInfo vol = mVolumes.valueAt(i); switch (vol.getType()) { case VolumeInfo.TYPE_PUBLIC: case VolumeInfo.TYPE_EMULATED: break; default: continue; } boolean match = false; if (forWrite) { match = vol.isVisibleForWrite(userId); } else { match = vol.isVisibleForRead(userId) || (includeInvisible && vol.getPath() != null); } if (!match) continue; boolean reportUnmounted = false; if ((vol.getType() == VolumeInfo.TYPE_EMULATED) && !userKeyUnlocked) { reportUnmounted = true; } else if (!storagePermission && !realState) { reportUnmounted = true; } final StorageVolume userVol = vol.buildStorageVolume(mContext, userId, reportUnmounted); if (vol.isPrimary()) { res.add(0, userVol); foundPrimary = true; } else { res.add(userVol); } } } if (!foundPrimary) { Log.w(TAG, "No primary storage defined yet; hacking together a stub"); final boolean primaryPhysical = SystemProperties.getBoolean( StorageManager.PROP_PRIMARY_PHYSICAL, false); final String id = "stub_primary"; final File path = Environment.getLegacyExternalStorageDirectory(); final String description = mContext.getString(android.R.string.unknownName); final boolean primary = true; final boolean removable = primaryPhysical; final boolean emulated = !primaryPhysical; final boolean allowMassStorage = false; final long maxFileSize = 0L; final UserHandle owner = new UserHandle(userId); final String uuid = null; final String state = Environment.MEDIA_REMOVED; res.add(0, new StorageVolume(id, path, path, description, primary, removable, emulated, allowMassStorage, maxFileSize, owner, uuid, state)); } return res.toArray(new StorageVolume[res.size()]); }
Example 16
Source File: PackageInstallerService.java From android_9.0.0_r45 with Apache License 2.0 | 4 votes |
@Override public void uninstall(VersionedPackage versionedPackage, String callerPackageName, int flags, IntentSender statusReceiver, int userId) throws RemoteException { final int callingUid = Binder.getCallingUid(); mPermissionManager.enforceCrossUserPermission(callingUid, userId, true, true, "uninstall"); if ((callingUid != Process.SHELL_UID) && (callingUid != Process.ROOT_UID)) { mAppOps.checkPackage(callingUid, callerPackageName); } // Check whether the caller is device owner or affiliated profile owner, in which case we do // it silently. final int callingUserId = UserHandle.getUserId(callingUid); DevicePolicyManagerInternal dpmi = LocalServices.getService(DevicePolicyManagerInternal.class); final boolean isDeviceOwnerOrAffiliatedProfileOwner = dpmi != null && dpmi.isActiveAdminWithPolicy(callingUid, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) && dpmi.isUserAffiliatedWithDevice(callingUserId); final PackageDeleteObserverAdapter adapter = new PackageDeleteObserverAdapter(mContext, statusReceiver, versionedPackage.getPackageName(), isDeviceOwnerOrAffiliatedProfileOwner, userId); if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DELETE_PACKAGES) == PackageManager.PERMISSION_GRANTED) { // Sweet, call straight through! mPm.deletePackageVersioned(versionedPackage, adapter.getBinder(), userId, flags); } else if (isDeviceOwnerOrAffiliatedProfileOwner) { // Allow the device owner and affiliated profile owner to silently delete packages // Need to clear the calling identity to get DELETE_PACKAGES permission long ident = Binder.clearCallingIdentity(); try { mPm.deletePackageVersioned(versionedPackage, adapter.getBinder(), userId, flags); } finally { Binder.restoreCallingIdentity(ident); } } else { ApplicationInfo appInfo = mPm.getApplicationInfo(callerPackageName, 0, userId); if (appInfo.targetSdkVersion >= Build.VERSION_CODES.P) { mContext.enforceCallingOrSelfPermission(Manifest.permission.REQUEST_DELETE_PACKAGES, null); } // Take a short detour to confirm with user final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); intent.setData(Uri.fromParts("package", versionedPackage.getPackageName(), null)); intent.putExtra(PackageInstaller.EXTRA_CALLBACK, adapter.getBinder().asBinder()); adapter.onUserActionRequired(intent); } }
Example 17
Source File: MediaSessionService.java From android_9.0.0_r45 with Apache License 2.0 | 4 votes |
@Override public void setOnMediaKeyListener(IOnMediaKeyListener listener) { final int pid = Binder.getCallingPid(); final int uid = Binder.getCallingUid(); final long token = Binder.clearCallingIdentity(); try { // Enforce SET_MEDIA_KEY_LISTENER permission. if (getContext().checkPermission( android.Manifest.permission.SET_MEDIA_KEY_LISTENER, pid, uid) != PackageManager.PERMISSION_GRANTED) { throw new SecurityException("Must hold the SET_MEDIA_KEY_LISTENER" + " permission."); } synchronized (mLock) { int userId = UserHandle.getUserId(uid); FullUserRecord user = getFullUserRecordLocked(userId); if (user == null || user.mFullUserId != userId) { Log.w(TAG, "Only the full user can set the media key listener" + ", userId=" + userId); return; } if (user.mOnMediaKeyListener != null && user.mOnMediaKeyListenerUid != uid) { Log.w(TAG, "The media key listener cannot be reset by another app. " + ", mOnMediaKeyListenerUid=" + user.mOnMediaKeyListenerUid + ", uid=" + uid); return; } user.mOnMediaKeyListener = listener; user.mOnMediaKeyListenerUid = uid; Log.d(TAG, "The media key listener " + user.mOnMediaKeyListener + " is set by " + getCallingPackageName(uid)); if (user.mOnMediaKeyListener != null) { try { user.mOnMediaKeyListener.asBinder().linkToDeath( new IBinder.DeathRecipient() { @Override public void binderDied() { synchronized (mLock) { user.mOnMediaKeyListener = null; } } }, 0); } catch (RemoteException e) { Log.w(TAG, "Failed to set death recipient " + user.mOnMediaKeyListener); user.mOnMediaKeyListener = null; } } } } finally { Binder.restoreCallingIdentity(token); } }
Example 18
Source File: ContentProvider.java From AndroidComponentPlugin with Apache License 2.0 | 4 votes |
boolean checkUser(int pid, int uid, Context context) { return UserHandle.getUserId(uid) == context.getUserId() || mSingleUser || context.checkPermission(INTERACT_ACROSS_USERS, pid, uid) == PERMISSION_GRANTED; }
Example 19
Source File: ShortcutService.java From android_9.0.0_r45 with Apache License 2.0 | 4 votes |
private int getCallingUserId() { return UserHandle.getUserId(injectBinderCallingUid()); }
Example 20
Source File: MediaSessionService.java From android_9.0.0_r45 with Apache License 2.0 | 4 votes |
private boolean hasMediaControlPermission(int resolvedUserId, String packageName, int pid, int uid) throws RemoteException { // Allow API calls from the System UI if (isCurrentVolumeController(pid, uid)) { return true; } // Check if it's system server or has MEDIA_CONTENT_CONTROL. // Note that system server doesn't have MEDIA_CONTENT_CONTROL, so we need extra // check here. if (uid == Process.SYSTEM_UID || getContext().checkPermission( android.Manifest.permission.MEDIA_CONTENT_CONTROL, pid, uid) == PackageManager.PERMISSION_GRANTED) { return true; } else if (DEBUG) { Log.d(TAG, packageName + " (uid=" + uid + ") hasn't granted MEDIA_CONTENT_CONTROL"); } // You may not access another user's content as an enabled listener. final int userId = UserHandle.getUserId(uid); if (resolvedUserId != userId) { return false; } // TODO(jaewan): (Post-P) Propose NotificationManager#hasEnabledNotificationListener( // String pkgName) to notification team for optimization final List<ComponentName> enabledNotificationListeners = mNotificationManager.getEnabledNotificationListeners(userId); if (enabledNotificationListeners != null) { for (int i = 0; i < enabledNotificationListeners.size(); i++) { if (TextUtils.equals(packageName, enabledNotificationListeners.get(i).getPackageName())) { return true; } } } if (DEBUG) { Log.d(TAG, packageName + " (uid=" + uid + ") doesn't have an enabled " + "notification listener"); } return false; }