android.os.UserHandle Java Examples

The following examples show how to use android.os.UserHandle. 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: TvInputManagerService.java    From android_9.0.0_r45 with Apache License 2.0 7 votes vote down vote up
@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);
    }
}
 
Example #2
Source File: StatusBarNotification.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #3
Source File: BootReceiver.java    From android-testdpc with Apache License 2.0 6 votes vote down vote up
@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()));
    }
}
 
Example #4
Source File: BroadcastQueue.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
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");
    }
}
 
Example #5
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: DeviceIdleController.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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;
        }
    }
}
 
Example #7
Source File: PermissionMonitor.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #8
Source File: ActivityManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #9
Source File: RemoteDisplayProviderWatcher.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #10
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #11
Source File: PackageManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #12
Source File: DefaultPermissionGrantPolicy.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #13
Source File: ShortcutService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #14
Source File: LocationManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void updateProvidersLocked() {
    boolean changesMade = false;
    for (int i = mProviders.size() - 1; i >= 0; i--) {
        LocationProviderInterface p = mProviders.get(i);
        boolean isEnabled = p.isEnabled();
        String name = p.getName();
        boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
        if (isEnabled && !shouldBeEnabled) {
            updateProviderListenersLocked(name, false);
            // If any provider has been disabled, clear all last locations for all providers.
            // This is to be on the safe side in case a provider has location derived from
            // this disabled provider.
            mLastLocation.clear();
            mLastLocationCoarseInterval.clear();
            changesMade = true;
        } else if (!isEnabled && shouldBeEnabled) {
            updateProviderListenersLocked(name, true);
            changesMade = true;
        }
    }
    if (changesMade) {
        mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
                UserHandle.ALL);
        mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
                UserHandle.ALL);
    }
}
 
Example #15
Source File: UserRestrictionsUtils.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * @return true if a restriction is settable by profile owner.  Note it takes a user ID because
 * some restrictions can be changed by PO only when it's running on the system user.
 */
public static boolean canProfileOwnerChange(String restriction, int userId) {
    return !IMMUTABLE_BY_OWNERS.contains(restriction)
            && !DEVICE_OWNER_ONLY_RESTRICTIONS.contains(restriction)
            && !(userId != UserHandle.USER_SYSTEM
                && PRIMARY_USER_ONLY_RESTRICTIONS.contains(restriction));
}
 
Example #16
Source File: AppOpsService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private boolean isPackageSuspendedForUser(String pkg, int uid) {
    try {
        return AppGlobals.getPackageManager().isPackageSuspendedForUser(
                pkg, UserHandle.getUserId(uid));
    } catch (RemoteException re) {
        throw new SecurityException("Could not talk to package manager service");
    }
}
 
Example #17
Source File: UserHandleCompat.java    From DroidPlugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static int getCallingUserId() {
    try {
        return (int) MethodUtils.invokeStaticMethod(UserHandle.class, "getCallingUserId");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return 0;
}
 
Example #18
Source File: Workspace.java    From LaunchEnr with GNU General Public License v3.0 5 votes vote down vote up
public void removeAbandonedPromise(String packageName, UserHandle user) {
    HashSet<String> packages = new HashSet<>(1);
    packages.add(packageName);
    ItemInfoMatcher matcher = ItemInfoMatcher.ofPackages(packages, user);
    mLauncher.getModelWriter().deleteItemsFromDatabase(matcher);
    removeItemsByMatcher(matcher);
}
 
Example #19
Source File: ActivityManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
int runToUri(PrintWriter pw, int flags) throws RemoteException {
    Intent intent;
    try {
        intent = makeIntent(UserHandle.USER_CURRENT);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    pw.println(intent.toUri(flags));
    return 0;
}
 
Example #20
Source File: ContextImpl.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user,
        IntentFilter filter, String broadcastPermission, Handler scheduler) {
    if (receiver == null) {
        // Allow retrieving current sticky broadcast; this is safe since we
        // aren't actually registering a receiver.
        return super.registerReceiverAsUser(null, user, filter, broadcastPermission, scheduler);
    } else {
        throw new ReceiverCallNotAllowedException(
                "BroadcastReceiver components are not allowed to register to receive intents");
    }
}
 
Example #21
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example #22
Source File: ApplicationPackageManager.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/**
 * @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()));
}
 
Example #23
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@Override
public void sendBroadcastAsUser(Intent intent, UserHandle user) {
    String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
    try {
        intent.prepareToLeaveProcess();
        ActivityManagerNative.getDefault().broadcastIntent(mMainThread.getApplicationThread(),
                intent, resolvedType, null, Activity.RESULT_OK, null, null, null,
                AppOpsManager.OP_NONE, false, false, user.getIdentifier());
    } catch (RemoteException e) {
    }
}
 
Example #24
Source File: ActivityManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
int runSetStandbyBucket(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();
    String value = getNextArgRequired();
    int bucket = bucketNameToBucketValue(value);
    if (bucket < 0) return -1;
    boolean multiple = peekNextArg() != null;


    IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService(
            Context.USAGE_STATS_SERVICE));
    if (!multiple) {
        usm.setAppStandbyBucket(packageName, bucketNameToBucketValue(value), userId);
    } else {
        ArrayList<AppStandbyInfo> bucketInfoList = new ArrayList<>();
        bucketInfoList.add(new AppStandbyInfo(packageName, bucket));
        while ((packageName = getNextArg()) != null) {
            value = getNextArgRequired();
            bucket = bucketNameToBucketValue(value);
            if (bucket < 0) continue;
            bucketInfoList.add(new AppStandbyInfo(packageName, bucket));
        }
        ParceledListSlice<AppStandbyInfo> slice = new ParceledListSlice<>(bucketInfoList);
        usm.setAppStandbyBuckets(slice, userId);
    }
    return 0;
}
 
Example #25
Source File: LauncherApps.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the settings activity to show the application details for a
 * package in the specified profile.
 *
 * @param component The ComponentName of the package to launch settings for.
 * @param user The UserHandle of the profile
 * @param sourceBounds The Rect containing the source bounds of the clicked icon
 * @param opts Options to pass to startActivity
 */
public void startAppDetailsActivity(ComponentName component, UserHandle user,
        Rect sourceBounds, Bundle opts) {
    logErrorForInvalidProfileAccess(user);
    try {
        mService.showAppDetailsAsUser(mContext.getIApplicationThread(),
                mContext.getPackageName(),
                component, sourceBounds, opts, user);
    } catch (RemoteException re) {
        throw re.rethrowFromSystemServer();
    }
}
 
Example #26
Source File: FingerprintManager.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * 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 */));
        }
    }
}
 
Example #27
Source File: SdCardAvailableReceiver.java    From LaunchEnr with GNU General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example #28
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/** @hide */
@Override
public void startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle) {
    if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
        throw new AndroidRuntimeException(
                "Calling startActivities() from outside of an Activity "
                + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent."
                + " Is this really what you want?");
    }
    mMainThread.getInstrumentation().execStartActivitiesAsUser(
            getOuterContext(), mMainThread.getApplicationThread(), null,
            (Activity) null, intents, options, userHandle.getIdentifier());
}
 
Example #29
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/** @hide */
@Override
public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
    try {
        ActivityManager.getService().startActivityAsUser(
            mMainThread.getApplicationThread(), getBasePackageName(), intent,
            intent.resolveTypeIfNeeded(getContentResolver()),
            null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options,
            user.getIdentifier());
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
 
Example #30
Source File: PluginBaseContextWrapper.java    From PluginLoader with Apache License 2.0 5 votes vote down vote up
@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);
}