Java Code Examples for android.os.UserHandle#USER_SYSTEM

The following examples show how to use android.os.UserHandle#USER_SYSTEM . 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: DiskStatsFileLogger.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * A given package may exist for multiple users with distinct sizes. This function filters
 * the packages that do not belong to user 0 out to ensure that we get good stats for a subset.
 * @return A mapping of package name to merged package stats.
 */
private ArrayMap<String, PackageStats> filterOnlyPrimaryUser() {
    ArrayMap<String, PackageStats> packageMap = new ArrayMap<>();
    for (PackageStats stat : mPackageStats) {
        if (stat.userHandle != UserHandle.USER_SYSTEM) {
            continue;
        }

        PackageStats existingStats = packageMap.get(stat.packageName);
        if (existingStats != null) {
            existingStats.cacheSize += stat.cacheSize;
            existingStats.codeSize += stat.codeSize;
            existingStats.dataSize += stat.dataSize;
            existingStats.externalCacheSize += stat.externalCacheSize;
            existingStats.externalCodeSize += stat.externalCodeSize;
            existingStats.externalDataSize += stat.externalDataSize;
        } else {
            packageMap.put(stat.packageName, new PackageStats(stat));
        }
    }
    return packageMap;
}
 
Example 2
Source File: PackageManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public int runSetUserRestriction() throws RemoteException {
    int userId = UserHandle.USER_SYSTEM;
    String opt = getNextOption();
    if (opt != null && "--user".equals(opt)) {
        userId = UserHandle.parseUserArg(getNextArgRequired());
    }

    String restriction = getNextArg();
    String arg = getNextArg();
    boolean value;
    if ("1".equals(arg)) {
        value = true;
    } else if ("0".equals(arg)) {
        value = false;
    } else {
        getErrPrintWriter().println("Error: valid value not specified");
        return 1;
    }
    IUserManager um = IUserManager.Stub.asInterface(
            ServiceManager.getService(Context.USER_SERVICE));
    um.setUserRestriction(restriction, value, userId);
    return 0;
}
 
Example 3
Source File: OverlayManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private int runEnableDisable(final boolean enable) throws RemoteException {
    final PrintWriter err = getErrPrintWriter();

    int userId = UserHandle.USER_SYSTEM;
    String opt;
    while ((opt = getNextOption()) != null) {
        switch (opt) {
            case "--user":
                userId = UserHandle.parseUserArg(getNextArgRequired());
                break;
            default:
                err.println("Error: Unknown option: " + opt);
                return 1;
        }
    }

    final String packageName = getNextArgRequired();
    return mInterface.setEnabled(packageName, enable, userId) ? 0 : 1;
}
 
Example 4
Source File: TrustManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Temporarily suppress strong auth requirements for {@param userId} until strong auth
 * changes again. Must only be called when we know about a successful unlock already
 * before the underlying StrongAuthTracker.
 *
 * Note that this only changes whether trust agents can be started, not the actual trusted
 * value.
 */
void allowTrustFromUnlock(int userId) {
    if (userId < UserHandle.USER_SYSTEM) {
        throw new IllegalArgumentException("userId must be a valid user: " + userId);
    }
    boolean previous = canAgentsRunForUser(userId);
    mStartFromSuccessfulUnlock.put(userId, true);

    if (DEBUG) {
        Log.i(TAG, "allowTrustFromUnlock(" + userId + ") ->"
                + " trustAllowed=" + isTrustAllowedForUser(userId)
                + " agentsCanRun=" + canAgentsRunForUser(userId));
    }

    if (canAgentsRunForUser(userId) != previous) {
        refreshAgentList(userId);
    }
}
 
Example 5
Source File: UserManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a UserInfo object with the name filled in, for Owner, or the original
 * if the name is already set.
 */
private UserInfo userWithName(UserInfo orig) {
    if (orig != null && orig.name == null && orig.id == UserHandle.USER_SYSTEM) {
        UserInfo withName = new UserInfo(orig);
        withName.name = getOwnerName();
        return withName;
    } else {
        return orig;
    }
}
 
Example 6
Source File: ZenModeHelper.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public void writeXml(XmlSerializer out, boolean forBackup, Integer version) throws IOException {
    final int N = mConfigs.size();
    for (int i = 0; i < N; i++) {
        //TODO: http://b/22388012
        if (forBackup && mConfigs.keyAt(i) != UserHandle.USER_SYSTEM) {
            continue;
        }
        mConfigs.valueAt(i).writeXml(out, version);
    }
}
 
Example 7
Source File: PackageManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private int runGetAppLink() throws RemoteException {
    int userId = UserHandle.USER_SYSTEM;

    String opt;
    while ((opt = getNextOption()) != null) {
        if (opt.equals("--user")) {
            userId = UserHandle.parseUserArg(getNextArgRequired());
        } else {
            getErrPrintWriter().println("Error: unknown option: " + opt);
            return 1;
        }
    }

    // Package name to act on; required
    final String pkg = getNextArg();
    if (pkg == null) {
        getErrPrintWriter().println("Error: no package specified.");
        return 1;
    }

    final PackageInfo info = mInterface.getPackageInfo(pkg, 0, userId);
    if (info == null) {
        getErrPrintWriter().println("Error: package " + pkg + " not found.");
        return 1;
    }

    if ((info.applicationInfo.privateFlags
            & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) == 0) {
        getErrPrintWriter().println("Error: package " + pkg + " does not handle web links.");
        return 1;
    }

    getOutPrintWriter().println(linkStateToString(
            mInterface.getIntentVerificationStatus(pkg, userId)));

    return 0;
}
 
Example 8
Source File: SettingsProviderTest.java    From Study_Android_Demo with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetAndGetGlobalViaFrontEndApiForNonSystemUser() throws Exception {
    final int secondaryUserId = getSecondaryUserId();
    if (secondaryUserId == UserHandle.USER_SYSTEM) {
        Log.w(LOG_TAG, "No secondary user. Skipping "
                + "testSetAndGetGlobalViaFrontEndApiForNonSystemUser");
        return;
    }
    performSetAndGetSettingTestViaFrontEndApi(SETTING_TYPE_GLOBAL, secondaryUserId);
}
 
Example 9
Source File: LockSettingsStrongAuth.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public void requireStrongAuth(int strongAuthReason, int userId) {
    if (userId == UserHandle.USER_ALL || userId >= UserHandle.USER_SYSTEM) {
        mHandler.obtainMessage(MSG_REQUIRE_STRONG_AUTH, strongAuthReason,
                userId).sendToTarget();
    } else {
        throw new IllegalArgumentException(
                "userId must be an explicit user id or USER_ALL");
    }
}
 
Example 10
Source File: MediaUpdateService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void registerBroadcastReceiver() {
    BroadcastReceiver updateReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_SYSTEM)
                        != UserHandle.USER_SYSTEM) {
                    // Ignore broadcast for non system users. We don't want to update system
                    // service multiple times.
                    return;
                }
                switch (intent.getAction()) {
                    case Intent.ACTION_PACKAGE_REMOVED:
                        if (intent.getExtras().getBoolean(Intent.EXTRA_REPLACING)) {
                            // The existing package is updated. Will be handled with the
                            // following ACTION_PACKAGE_ADDED case.
                            return;
                        }
                        packageStateChanged();
                        break;
                    case Intent.ACTION_PACKAGE_CHANGED:
                        packageStateChanged();
                        break;
                    case Intent.ACTION_PACKAGE_ADDED:
                        packageStateChanged();
                        break;
                }
            }
    };
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_PACKAGE_ADDED);
    filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
    filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
    filter.addDataScheme("package");
    filter.addDataSchemeSpecificPart(MEDIA_UPDATE_PACKAGE_NAME, PatternMatcher.PATTERN_LITERAL);

    getContext().registerReceiverAsUser(updateReceiver, UserHandle.ALL, filter,
            null /* broadcast permission */, null /* handler */);
}
 
Example 11
Source File: UserSwitchingDialog.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
void inflateContent() {
    // Set up the dialog contents
    setCancelable(false);
    Resources res = getContext().getResources();
    // Custom view due to alignment and font size requirements
    View view = LayoutInflater.from(getContext()).inflate(R.layout.user_switching_dialog,
        null);

    String viewMessage = null;
    if (UserManager.isSplitSystemUser() && mNewUser.id == UserHandle.USER_SYSTEM) {
        viewMessage = res.getString(R.string.user_logging_out_message, mOldUser.name);
    } else if (UserManager.isDeviceInDemoMode(mContext)) {
        if (mOldUser.isDemo()) {
            viewMessage = res.getString(R.string.demo_restarting_message);
        } else {
            viewMessage = res.getString(R.string.demo_starting_message);
        }
    } else {
        if (mOldUser.id == UserHandle.USER_SYSTEM) {
            viewMessage = mSwitchingFromSystemUserMessage;
        } else if (mNewUser.id == UserHandle.USER_SYSTEM) {
            viewMessage = mSwitchingToSystemUserMessage;
        }

        // If switchingFromSystemUserMessage or switchingToSystemUserMessage is null, fallback
        // to system message.
        if (viewMessage == null) {
            viewMessage = res.getString(R.string.user_switching_message, mNewUser.name);
        }
    }
    ((TextView) view.findViewById(R.id.message)).setText(viewMessage);
    setView(view);
}
 
Example 12
Source File: SettingsProviderTest.java    From Study_Android_Demo with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetAndGetSecureViaFrontEndApiForNonSystemUser() throws Exception {
    final int secondaryUserId = getSecondaryUserId();
    if (secondaryUserId == UserHandle.USER_SYSTEM) {
        Log.w(LOG_TAG, "No secondary user. Skipping "
                + "testSetAndGetSecureViaFrontEndApiForNonSystemUser");
        return;
    }
    performSetAndGetSettingTestViaFrontEndApi(SETTING_TYPE_SECURE, secondaryUserId);
}
 
Example 13
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 14
Source File: SettingsProviderTest.java    From Study_Android_Demo with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetAndGetSystemViaFrontEndApiForNonSystemUser() throws Exception {
    final int secondaryUserId = getSecondaryUserId();
    if (secondaryUserId == UserHandle.USER_SYSTEM) {
        Log.w(LOG_TAG, "No secondary user. Skipping "
                + "testSetAndGetSystemViaFrontEndApiForNonSystemUser");
        return;
    }
    performSetAndGetSettingTestViaFrontEndApi(SETTING_TYPE_SYSTEM, secondaryUserId);
}
 
Example 15
Source File: ZenModeHelper.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void loadConfigForUser(int user, String reason) {
    if (mUser == user || user < UserHandle.USER_SYSTEM) return;
    mUser = user;
    if (DEBUG) Log.d(TAG, reason + " u=" + user);
    ZenModeConfig config = mConfigs.get(user);
    if (config == null) {
        if (DEBUG) Log.d(TAG, reason + " generating default config for user " + user);
        config = mDefaultConfig.copy();
        config.user = user;
    }
    synchronized (mConfig) {
        setConfigLocked(config, null, reason);
    }
    cleanUpZenRules();
}
 
Example 16
Source File: ZenModeHelper.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public void onUserRemoved(int user) {
    if (user < UserHandle.USER_SYSTEM) return;
    if (DEBUG) Log.d(TAG, "onUserRemoved u=" + user);
    mConfigs.remove(user);
}
 
Example 17
Source File: UserController.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
    final int userId = uss.mHandle.getIdentifier();

    Slog.d(TAG, "Finishing user boot " + userId);
    synchronized (mLock) {
        // Bail if we ended up with a stale user
        if (mStartedUsers.get(userId) != uss) {
            return;
        }
    }

    // We always walk through all the user lifecycle states to send
    // consistent developer events. We step into RUNNING_LOCKED here,
    // but we might immediately step into RUNNING below if the user
    // storage is already unlocked.
    if (uss.setState(STATE_BOOTING, STATE_RUNNING_LOCKED)) {
        mInjector.getUserManagerInternal().setUserState(userId, uss.state);
        // Do not report secondary users, runtime restarts or first boot/upgrade
        if (userId == UserHandle.USER_SYSTEM
                && !mInjector.isRuntimeRestarted() && !mInjector.isFirstBootOrUpgrade()) {
            int uptimeSeconds = (int)(SystemClock.elapsedRealtime() / 1000);
            MetricsLogger.histogram(mInjector.getContext(),
                    "framework_locked_boot_completed", uptimeSeconds);
            final int MAX_UPTIME_SECONDS = 120;
            if (uptimeSeconds > MAX_UPTIME_SECONDS) {
                Slog.wtf("SystemServerTiming",
                        "finishUserBoot took too long. uptimeSeconds=" + uptimeSeconds);
            }
        }

        mHandler.sendMessage(mHandler.obtainMessage(REPORT_LOCKED_BOOT_COMPLETE_MSG,
                userId, 0));
        Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
        intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
        intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
                | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
        mInjector.broadcastIntent(intent, null, resultTo, 0, null, null,
                new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
                AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
    }

    // We need to delay unlocking managed profiles until the parent user
    // is also unlocked.
    if (mInjector.getUserManager().isManagedProfile(userId)) {
        final UserInfo parent = mInjector.getUserManager().getProfileParent(userId);
        if (parent != null
                && isUserRunning(parent.id, ActivityManager.FLAG_AND_UNLOCKED)) {
            Slog.d(TAG, "User " + userId + " (parent " + parent.id
                    + "): attempting unlock because parent is unlocked");
            maybeUnlockUser(userId);
        } else {
            String parentId = (parent == null) ? "<null>" : String.valueOf(parent.id);
            Slog.d(TAG, "User " + userId + " (parent " + parentId
                    + "): delaying unlock because parent is locked");
        }
    } else {
        maybeUnlockUser(userId);
    }
}
 
Example 18
Source File: PackageManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private int runSetAppLink() throws RemoteException {
    int userId = UserHandle.USER_SYSTEM;

    String opt;
    while ((opt = getNextOption()) != null) {
        if (opt.equals("--user")) {
            userId = UserHandle.parseUserArg(getNextArgRequired());
        } else {
            getErrPrintWriter().println("Error: unknown option: " + opt);
            return 1;
        }
    }

    // Package name to act on; required
    final String pkg = getNextArg();
    if (pkg == null) {
        getErrPrintWriter().println("Error: no package specified.");
        return 1;
    }

    // State to apply; {always|ask|never|undefined}, required
    final String modeString = getNextArg();
    if (modeString == null) {
        getErrPrintWriter().println("Error: no app link state specified.");
        return 1;
    }

    final int newMode;
    switch (modeString.toLowerCase()) {
        case "undefined":
            newMode = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
            break;

        case "always":
            newMode = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
            break;

        case "ask":
            newMode = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
            break;

        case "always-ask":
            newMode = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
            break;

        case "never":
            newMode = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
            break;

        default:
            getErrPrintWriter().println("Error: unknown app link state '" + modeString + "'");
            return 1;
    }

    final PackageInfo info = mInterface.getPackageInfo(pkg, 0, userId);
    if (info == null) {
        getErrPrintWriter().println("Error: package " + pkg + " not found.");
        return 1;
    }

    if ((info.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) == 0) {
        getErrPrintWriter().println("Error: package " + pkg + " does not handle web links.");
        return 1;
    }

    if (!mInterface.updateIntentVerificationStatus(pkg, newMode, userId)) {
        getErrPrintWriter().println("Error: unable to update app link status for " + pkg);
        return 1;
    }

    return 0;
}
 
Example 19
Source File: PackageManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public int runCreateUser() throws RemoteException {
    String name;
    int userId = -1;
    int flags = 0;
    String opt;
    while ((opt = getNextOption()) != null) {
        if ("--profileOf".equals(opt)) {
            userId = UserHandle.parseUserArg(getNextArgRequired());
        } else if ("--managed".equals(opt)) {
            flags |= UserInfo.FLAG_MANAGED_PROFILE;
        } else if ("--restricted".equals(opt)) {
            flags |= UserInfo.FLAG_RESTRICTED;
        } else if ("--ephemeral".equals(opt)) {
            flags |= UserInfo.FLAG_EPHEMERAL;
        } else if ("--guest".equals(opt)) {
            flags |= UserInfo.FLAG_GUEST;
        } else if ("--demo".equals(opt)) {
            flags |= UserInfo.FLAG_DEMO;
        } else {
            getErrPrintWriter().println("Error: unknown option " + opt);
            return 1;
        }
    }
    String arg = getNextArg();
    if (arg == null) {
        getErrPrintWriter().println("Error: no user name specified.");
        return 1;
    }
    name = arg;
    UserInfo info;
    IUserManager um = IUserManager.Stub.asInterface(
            ServiceManager.getService(Context.USER_SERVICE));
    IAccountManager accm = IAccountManager.Stub.asInterface(
            ServiceManager.getService(Context.ACCOUNT_SERVICE));
    if ((flags & UserInfo.FLAG_RESTRICTED) != 0) {
        // In non-split user mode, userId can only be SYSTEM
        int parentUserId = userId >= 0 ? userId : UserHandle.USER_SYSTEM;
        info = um.createRestrictedProfile(name, parentUserId);
        accm.addSharedAccountsFromParentUser(parentUserId, userId,
                (Process.myUid() == Process.ROOT_UID) ? "root" : "com.android.shell");
    } else if (userId < 0) {
        info = um.createUser(name, flags);
    } else {
        info = um.createProfileForUser(name, flags, userId, null);
    }

    if (info != null) {
        getOutPrintWriter().println("Success: created user id " + info.id);
        return 0;
    } else {
        getErrPrintWriter().println("Error: couldn't create User.");
        return 1;
    }
}
 
Example 20
Source File: ServiceWatcher.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Searches and binds to the best package, or do nothing if the best package
 * is already bound, unless force rebinding is requested.
 *
 * @param justCheckThisPackage Only consider this package, or consider all
 *            packages if it is {@code null}.
 * @param forceRebind Force a rebinding to the best package if it's already
 *            bound.
 * @returns {@code true} if a valid package was found to bind to.
 */
@GuardedBy("mLock")
private boolean bindBestPackageLocked(String justCheckThisPackage, boolean forceRebind) {
    Intent intent = new Intent(mAction);
    if (justCheckThisPackage != null) {
        intent.setPackage(justCheckThisPackage);
    }
    final List<ResolveInfo> rInfos = mPm.queryIntentServicesAsUser(intent,
            PackageManager.GET_META_DATA | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
            mCurrentUserId);
    int bestVersion = Integer.MIN_VALUE;
    ComponentName bestComponent = null;
    boolean bestIsMultiuser = false;
    if (rInfos != null) {
        for (ResolveInfo rInfo : rInfos) {
            final ComponentName component = rInfo.serviceInfo.getComponentName();
            final String packageName = component.getPackageName();

            // check signature
            try {
                PackageInfo pInfo;
                pInfo = mPm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES
                        | PackageManager.MATCH_DEBUG_TRIAGED_MISSING);
                if (!isSignatureMatch(pInfo.signatures)) {
                    Log.w(mTag, packageName + " resolves service " + mAction
                            + ", but has wrong signature, ignoring");
                    continue;
                }
            } catch (NameNotFoundException e) {
                Log.wtf(mTag, e);
                continue;
            }

            // check metadata
            int version = Integer.MIN_VALUE;
            boolean isMultiuser = false;
            if (rInfo.serviceInfo.metaData != null) {
                version = rInfo.serviceInfo.metaData.getInt(
                        EXTRA_SERVICE_VERSION, Integer.MIN_VALUE);
                isMultiuser = rInfo.serviceInfo.metaData.getBoolean(EXTRA_SERVICE_IS_MULTIUSER);
            }

            if (version > bestVersion) {
                bestVersion = version;
                bestComponent = component;
                bestIsMultiuser = isMultiuser;
            }
        }

        if (D) {
            Log.d(mTag, String.format("bindBestPackage for %s : %s found %d, %s", mAction,
                    (justCheckThisPackage == null ? ""
                            : "(" + justCheckThisPackage + ") "), rInfos.size(),
                    (bestComponent == null ? "no new best component"
                            : "new best component: " + bestComponent)));
        }
    } else {
        if (D) Log.d(mTag, "Unable to query intent services for action: " + mAction);
    }

    if (bestComponent == null) {
        Slog.w(mTag, "Odd, no component found for service " + mAction);
        unbindLocked();
        return false;
    }

    final int userId = bestIsMultiuser ? UserHandle.USER_SYSTEM : mCurrentUserId;
    final boolean alreadyBound = Objects.equals(bestComponent, mBoundComponent)
            && bestVersion == mBoundVersion && userId == mBoundUserId;
    if (forceRebind || !alreadyBound) {
        unbindLocked();
        bindToPackageLocked(bestComponent, bestVersion, userId);
    }
    return true;
}