下面列出了android.content.pm.PackageStats#android.os.UserHandle 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public StatusBarNotification(Parcel in) {
this.pkg = in.readString();
this.opPkg = in.readString();
this.id = in.readInt();
if (in.readInt() != 0) {
this.tag = in.readString();
} else {
this.tag = null;
}
this.uid = in.readInt();
this.initialPid = in.readInt();
this.notification = new Notification(in);
this.user = UserHandle.readFromParcel(in);
this.postTime = in.readLong();
if (in.readInt() != 0) {
this.overrideGroupKey = in.readString();
} else {
this.overrideGroupKey = null;
}
this.key = key();
this.groupKey = groupKey();
}
private int runSetHiddenSetting(boolean state) throws RemoteException {
int userId = UserHandle.USER_SYSTEM;
String option = getNextOption();
if (option != null && option.equals("--user")) {
userId = UserHandle.parseUserArg(getNextArgRequired());
}
String pkg = getNextArg();
if (pkg == null) {
getErrPrintWriter().println("Error: no package or component specified");
return 1;
}
mInterface.setApplicationHiddenSettingAsUser(pkg, state, userId);
getOutPrintWriter().println("Package " + pkg + " new hidden state: "
+ mInterface.getApplicationHiddenSettingAsUser(pkg, userId));
return 0;
}
@Override
public Context createPackageContextAsUser(String packageName, int flags, UserHandle user)
throws NameNotFoundException {
final boolean restricted = (flags & CONTEXT_RESTRICTED) == CONTEXT_RESTRICTED;
if (packageName.equals("system") || packageName.equals("android")) {
return new ContextImpl(this, mMainThread, mPackageInfo, mActivityToken,
user, restricted, mDisplay, mOverrideConfiguration);
}
LoadedApk pi = mMainThread.getPackageInfo(packageName, mResources.getCompatibilityInfo(),
flags | CONTEXT_REGISTER_PACKAGE, user.getIdentifier());
if (pi != null) {
ContextImpl c = new ContextImpl(this, mMainThread, pi, mActivityToken,
user, restricted, mDisplay, mOverrideConfiguration);
if (c.mResources != null) {
return c;
}
}
// Should be a better exception.
throw new PackageManager.NameNotFoundException(
"Application package " + packageName + " not found");
}
final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
final int logIndex = r.nextReceiver - 1;
if (logIndex >= 0 && logIndex < r.receivers.size()) {
Object curReceiver = r.receivers.get(logIndex);
if (curReceiver instanceof BroadcastFilter) {
BroadcastFilter bf = (BroadcastFilter) curReceiver;
EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
bf.owningUserId, System.identityHashCode(r),
r.intent.getAction(), logIndex, System.identityHashCode(bf));
} else {
ResolveInfo ri = (ResolveInfo) curReceiver;
EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
}
} else {
if (logIndex < 0) Slog.w(TAG,
"Discarding broadcast before first receiver is invoked: " + r);
EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
-1, System.identityHashCode(r),
r.intent.getAction(),
r.nextReceiver,
"NONE");
}
}
private boolean isSysComponentOrPersistentPlatformSignedPrivApp(PackageParser.Package pkg) {
if (UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID) {
return true;
}
if (!pkg.isPrivileged()) {
return false;
}
final PackageParser.Package disabledPkg =
mServiceInternal.getDisabledPackage(pkg.packageName);
if (disabledPkg != null) {
if ((disabledPkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) == 0) {
return false;
}
} else if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) == 0) {
return false;
}
final String systemPackageName = mServiceInternal.getKnownPackageName(
PackageManagerInternal.PACKAGE_SYSTEM, UserHandle.USER_SYSTEM);
final PackageParser.Package systemPackage = getPackage(systemPackageName);
return pkg.mSigningDetails.hasAncestorOrSelf(systemPackage.mSigningDetails)
|| systemPackage.mSigningDetails.checkCapability(pkg.mSigningDetails,
PackageParser.SigningDetails.CertCapabilities.PERMISSION);
}
int runGetInactive(PrintWriter pw) throws RemoteException {
int userId = UserHandle.USER_CURRENT;
String opt;
while ((opt=getNextOption()) != null) {
if (opt.equals("--user")) {
userId = UserHandle.parseUserArg(getNextArgRequired());
} else {
getErrPrintWriter().println("Error: Unknown option: " + opt);
return -1;
}
}
String packageName = getNextArgRequired();
IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService(
Context.USAGE_STATS_SERVICE));
boolean isIdle = usm.isAppInactive(packageName, userId);
pw.println("Idle=" + isIdle);
return 0;
}
public boolean addPowerSaveWhitelistExceptIdleInternal(String name) {
synchronized (this) {
try {
final ApplicationInfo ai = getContext().getPackageManager().getApplicationInfo(name,
PackageManager.MATCH_ANY_USER);
if (mPowerSaveWhitelistAppsExceptIdle.put(name, UserHandle.getAppId(ai.uid))
== null) {
mPowerSaveWhitelistUserAppsExceptIdle.add(name);
reportPowerSaveWhitelistChangedLocked();
mPowerSaveWhitelistExceptIdleAppIdArray = buildAppIdArray(
mPowerSaveWhitelistAppsExceptIdle, mPowerSaveWhitelistUserApps,
mPowerSaveWhitelistExceptIdleAppIds);
passWhiteListsToForceAppStandbyTrackerLocked();
}
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
}
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
if (!Util.isProfileOwner(context)
|| Util.getBindDeviceAdminTargetUsers(context).size() == 0) {
return;
}
// We are a profile owner and can bind to the device owner - let's notify the device
// owner that we are up and running (i.e. our user was just started and/or unlocked)
UserHandle targetUser = Util.getBindDeviceAdminTargetUsers(context).get(0);
BindDeviceAdminServiceHelper<IDeviceOwnerService> helper =
createBindDeviceOwnerServiceHelper(context, targetUser);
helper.crossUserCall(service -> service.notifyUserIsUnlocked(Process.myUserHandle()));
}
}
@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");
}
private void update(Set<Integer> users, Map<Integer, Boolean> apps, boolean add) {
List<Integer> network = new ArrayList<>();
List<Integer> system = new ArrayList<>();
for (Entry<Integer, Boolean> app : apps.entrySet()) {
List<Integer> list = app.getValue() ? system : network;
for (int user : users) {
list.add(UserHandle.getUid(user, app.getKey()));
}
}
try {
if (add) {
mNetd.setPermission("NETWORK", toIntArray(network));
mNetd.setPermission("SYSTEM", toIntArray(system));
} else {
mNetd.clearPermission(toIntArray(network));
mNetd.clearPermission(toIntArray(system));
}
} catch (RemoteException e) {
loge("Exception when updating permissions: " + e);
}
}
public void start() {
if (!mRunning) {
mRunning = true;
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
filter.addDataScheme("package");
mContext.registerReceiverAsUser(mScanPackagesReceiver,
new UserHandle(mUserId), filter, null, mHandler);
// Scan packages.
// Also has the side-effect of restarting providers if needed.
mHandler.post(mScanPackagesRunnable);
}
}
@Override
public void requestChannelBrowsable(Uri channelUri, int userId)
throws RemoteException {
final String callingPackageName = getCallingPackageName();
final long identity = Binder.clearCallingIdentity();
final int callingUid = Binder.getCallingUid();
final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
userId, "requestChannelBrowsable");
try {
Intent intent = new Intent(TvContract.ACTION_CHANNEL_BROWSABLE_REQUESTED);
List<ResolveInfo> list = getContext().getPackageManager()
.queryBroadcastReceivers(intent, 0);
if (list != null) {
for (ResolveInfo info : list) {
String receiverPackageName = info.activityInfo.packageName;
intent.putExtra(TvContract.EXTRA_CHANNEL_ID, ContentUris.parseId(
channelUri));
intent.putExtra(TvContract.EXTRA_PACKAGE_NAME, callingPackageName);
intent.setPackage(receiverPackageName);
getContext().sendBroadcastAsUser(intent, new UserHandle(resolvedUserId));
}
}
} finally {
Binder.restoreCallingIdentity(identity);
}
}
@Override
public boolean isForegroundDefaultLauncher(@NonNull String callingPackage, int callingUid) {
Preconditions.checkNotNull(callingPackage);
final int userId = UserHandle.getUserId(callingUid);
final ComponentName defaultLauncher = getDefaultLauncher(userId);
if (defaultLauncher == null) {
return false;
}
if (!callingPackage.equals(defaultLauncher.getPackageName())) {
return false;
}
synchronized (mLock) {
if (!isUidForegroundLocked(callingUid)) {
return false;
}
}
return true;
}
/**
* @hide
*/
public Drawable loadItemIcon(PackageItemInfo itemInfo, ApplicationInfo appInfo) {
Drawable dr = loadUnbadgedItemIcon(itemInfo, appInfo);
if (itemInfo.showUserIcon != UserHandle.USER_NULL) {
return dr;
}
return getUserBadgedIcon(dr, new UserHandle(mContext.getUserId()));
}
@Override
public void revokeRuntimePermission(String packageName, String permissionName,
UserHandle user) {
try {
mPM.revokeRuntimePermission(packageName, permissionName, user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
private void registerShowTouchesSettingObserver() {
mContext.getContentResolver().registerContentObserver(
Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
new ContentObserver(mHandler) {
@Override
public void onChange(boolean selfChange) {
updateShowTouchesFromSettings();
}
}, UserHandle.USER_ALL);
}
@Override
public void sendBroadcastAsUser(Intent intent, UserHandle user) {
String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
try {
intent.prepareToLeaveProcess(this);
ActivityManagerNative.getDefault().broadcastIntent(mMainThread.getApplicationThread(),
intent, resolvedType, null, Activity.RESULT_OK, null, null, null,
AppOpsManager.OP_NONE, null, false, false, user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* @return true if the service is bound or in the process of being bound.
* Returns false otherwise.
*/
private boolean bindLocked() {
if (isBoundLocked() || mBinding) {
return true;
}
// TODO: Handle bind timeout.
final boolean willBind;
final long identity = Binder.clearCallingIdentity();
try {
ComponentName componentName =
TextClassifierService.getServiceComponentName(mContext);
if (componentName == null) {
// Might happen if the storage is encrypted and the user is not unlocked
return false;
}
Intent serviceIntent = new Intent(TextClassifierService.SERVICE_INTERFACE)
.setComponent(componentName);
Slog.d(LOG_TAG, "Binding to " + serviceIntent.getComponent());
willBind = mContext.bindServiceAsUser(
serviceIntent, mConnection,
Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
UserHandle.of(mUserId));
mBinding = willBind;
} finally {
Binder.restoreCallingIdentity(identity);
}
return willBind;
}
@Override
public int checkPermission(String permission, int pid, int uid) {
if (permission == null) {
throw new IllegalArgumentException("permission is null");
}
final IActivityManager am = ActivityManager.getService();
if (am == null) {
// Well this is super awkward; we somehow don't have an active
// ActivityManager instance. If we're testing a root or system
// UID, then they totally have whatever permission this is.
final int appId = UserHandle.getAppId(uid);
if (appId == Process.ROOT_UID || appId == Process.SYSTEM_UID) {
Slog.w(TAG, "Missing ActivityManager; assuming " + uid + " holds " + permission);
return PackageManager.PERMISSION_GRANTED;
}
Slog.w(TAG, "Missing ActivityManager; assuming " + uid + " does not hold "
+ permission);
return PackageManager.PERMISSION_DENIED;
}
try {
return am.checkPermission(permission, pid, uid);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
private void verifyApp(String packageName) throws PackageManager.NameNotFoundException {
IPackageManager pm = IPackageManager.Stub.asInterface(
ServiceManager.getService("package"));
try {
pm.getApplicationInfo(packageName, 0, UserHandle.getCallingUserId());
} catch (RemoteException e) {
throw new IllegalStateException(e);
}
}
@Override
public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
UserHandle user) {
try {
return mPM.setApplicationHiddenSettingAsUser(packageName, hidden,
user.getIdentifier());
} catch (RemoteException re) {
// Should never happen!
}
return false;
}
@Override
public @Nullable String getSerial() throws RemoteException {
if (UserHandle.getAppId(Binder.getCallingUid()) != Process.SYSTEM_UID
&& mContext.checkCallingOrSelfPermission(
Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED
&& mContext.checkCallingOrSelfPermission(
Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
throw new SecurityException("getSerial requires READ_PHONE_STATE"
+ " or READ_PRIVILEGED_PHONE_STATE permission");
}
return SystemProperties.get("ro.serialno", Build.UNKNOWN);
}
@Override
public Drawable getUserBadgedDrawableForDensity(Drawable drawable, UserHandle user,
Rect badgeLocation, int badgeDensity) {
Drawable badgeDrawable = getUserBadgeForDensity(user, badgeDensity);
if (badgeDrawable == null) {
return drawable;
}
return getBadgedDrawable(drawable, badgeDrawable, badgeLocation, true);
}
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;
}
@VisibleForTesting
protected void clearTetheredNotification() {
NotificationManager notificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null && mLastNotificationId != 0) {
notificationManager.cancelAsUser(null, mLastNotificationId,
UserHandle.ALL);
mLastNotificationId = 0;
}
}
@RequiresApi(N) ApplicationInfo getApplicationInfo(final String pkg, final UserHandle user) {
try {
return Objects.requireNonNull(Hacks.LauncherApps_getApplicationInfo).invoke(pkg, PM_FLAGS_GET_APP_INFO, user).on(mLauncherApps.get());
} catch (final Exception e) { // NameNotFoundException will be thrown since Android O instead of retuning null on Android N.
if (e instanceof RuntimeException) throw (RuntimeException) e;
return null;
}
}
@Override
public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
String receiverPermission, int appOp, Bundle options, BroadcastReceiver resultReceiver,
Handler scheduler, int initialCode, String initialData, Bundle initialExtras) {
IIntentReceiver rd = null;
if (resultReceiver != null) {
if (mPackageInfo != null) {
if (scheduler == null) {
scheduler = mMainThread.getHandler();
}
rd = mPackageInfo.getReceiverDispatcher(
resultReceiver, getOuterContext(), scheduler,
mMainThread.getInstrumentation(), false);
} else {
if (scheduler == null) {
scheduler = mMainThread.getHandler();
}
rd = new LoadedApk.ReceiverDispatcher(resultReceiver, getOuterContext(),
scheduler, null, false).getIIntentReceiver();
}
}
String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
String[] receiverPermissions = receiverPermission == null ? null
: new String[] {receiverPermission};
try {
intent.prepareToLeaveProcess(this);
ActivityManager.getService().broadcastIntent(
mMainThread.getApplicationThread(), intent, resolvedType, rd,
initialCode, initialData, initialExtras, receiverPermissions,
appOp, options, true, false, user.getIdentifier());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Request fingerprint enrollment. This call warms up the fingerprint hardware
* and starts scanning for fingerprints. Progress will be indicated by callbacks to the
* {@link EnrollmentCallback} object. It terminates when
* {@link EnrollmentCallback#onEnrollmentError(int, CharSequence)} or
* {@link EnrollmentCallback#onEnrollmentProgress(int) is called with remaining == 0, at
* which point the object is no longer valid. The operation can be canceled by using the
* provided cancel object.
* @param token a unique token provided by a recent creation or verification of device
* credentials (e.g. pin, pattern or password).
* @param cancel an object that can be used to cancel enrollment
* @param flags optional flags
* @param userId the user to whom this fingerprint will belong to
* @param callback an object to receive enrollment events
* @hide
*/
@RequiresPermission(MANAGE_FINGERPRINT)
public void enroll(byte [] token, CancellationSignal cancel, int flags,
int userId, EnrollmentCallback callback) {
if (userId == UserHandle.USER_CURRENT) {
userId = getCurrentUserId();
}
if (callback == null) {
throw new IllegalArgumentException("Must supply an enrollment callback");
}
if (cancel != null) {
if (cancel.isCanceled()) {
Slog.w(TAG, "enrollment already canceled");
return;
} else {
cancel.setOnCancelListener(new OnEnrollCancelListener());
}
}
if (mService != null) try {
mEnrollmentCallback = callback;
mService.enroll(mToken, token, userId, mServiceReceiver, flags,
mContext.getOpPackageName());
} catch (RemoteException e) {
Slog.w(TAG, "Remote exception in enroll: ", e);
if (callback != null) {
// Though this may not be a hardware issue, it will cause apps to give up or try
// again later.
callback.onEnrollmentError(FINGERPRINT_ERROR_HW_UNAVAILABLE,
getErrorString(FINGERPRINT_ERROR_HW_UNAVAILABLE, 0 /* vendorCode */));
}
}
}
@Override
public void onReceive(Context context, Intent intent) {
final LauncherAppsCompat launcherApps = LauncherAppsCompat.getInstance(context);
final PackageManagerHelper pmHelper = new PackageManagerHelper(context);
for (Entry<UserHandle, ArrayList<String>> entry : mPackages.entrySet()) {
UserHandle user = entry.getKey();
final ArrayList<String> packagesRemoved = new ArrayList<>();
final ArrayList<String> packagesUnavailable = new ArrayList<>();
for (String pkg : new HashSet<>(entry.getValue())) {
if (!launcherApps.isPackageEnabledForProfile(pkg, user)) {
if (pmHelper.isAppOnSdcard(pkg, user)) {
packagesUnavailable.add(pkg);
} else {
packagesRemoved.add(pkg);
}
}
}
if (!packagesRemoved.isEmpty()) {
mModel.onPackagesRemoved(user,
packagesRemoved.toArray(new String[packagesRemoved.size()]));
}
if (!packagesUnavailable.isEmpty()) {
mModel.onPackagesUnavailable(
packagesUnavailable.toArray(new String[packagesUnavailable.size()]),
user, false);
}
}
// Unregister the broadcast receiver, just in case
mContext.unregisterReceiver(this);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) {
PaLog.d(intent);
intent = PluginIntentResolver.resolveReceiver(intent);
super.sendStickyBroadcastAsUser(intent, user);
}