android.os.UserHandle#USER_CURRENT源码实例Demo

下面列出了android.os.UserHandle#USER_CURRENT 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: android_9.0.0_r45   文件: ResolveInfo.java
public String toString() {
    final ComponentInfo ci = getComponentInfo();
    StringBuilder sb = new StringBuilder(128);
    sb.append("ResolveInfo{");
    sb.append(Integer.toHexString(System.identityHashCode(this)));
    sb.append(' ');
    ComponentName.appendShortString(sb, ci.packageName, ci.name);
    if (priority != 0) {
        sb.append(" p=");
        sb.append(priority);
    }
    if (preferredOrder != 0) {
        sb.append(" o=");
        sb.append(preferredOrder);
    }
    sb.append(" m=0x");
    sb.append(Integer.toHexString(match));
    if (targetUserId != UserHandle.USER_CURRENT) {
        sb.append(" targetUserId=");
        sb.append(targetUserId);
    }
    sb.append('}');
    return sb.toString();
}
 
private Intent parseIntentAndUser() throws URISyntaxException {
    mTargetUser = UserHandle.USER_CURRENT;
    mBrief = false;
    mComponents = false;
    Intent intent = Intent.parseCommandArgs(this, new Intent.CommandOptionHandler() {
        @Override
        public boolean handleOption(String opt, ShellCommand cmd) {
            if ("--user".equals(opt)) {
                mTargetUser = UserHandle.parseUserArg(cmd.getNextArgRequired());
                return true;
            } else if ("--brief".equals(opt)) {
                mBrief = true;
                return true;
            } else if ("--components".equals(opt)) {
                mComponents = true;
                return true;
            }
            return false;
        }
    });
    mTargetUser = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
            Binder.getCallingUid(), mTargetUser, false, false, null, null);
    return intent;
}
 
private int runSetHarmfulAppWarning() 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;
        }
    }

    userId = translateUserId(userId, false /*allowAll*/, "runSetHarmfulAppWarning");

    final String packageName = getNextArgRequired();
    final String warning = getNextArg();

    mInterface.setHarmfulAppWarning(packageName, warning, userId);

    return 0;
}
 
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;
}
 
源代码5 项目: android_9.0.0_r45   文件: AccessibilityManager.java
/**
 * Get an AccessibilityManager instance (create one if necessary).
 *
 * @param context Context in which this manager operates.
 *
 * @hide
 */
public static AccessibilityManager getInstance(Context context) {
    synchronized (sInstanceSync) {
        if (sInstance == null) {
            final int userId;
            if (Binder.getCallingUid() == Process.SYSTEM_UID
                    || context.checkCallingOrSelfPermission(
                            Manifest.permission.INTERACT_ACROSS_USERS)
                                    == PackageManager.PERMISSION_GRANTED
                    || context.checkCallingOrSelfPermission(
                            Manifest.permission.INTERACT_ACROSS_USERS_FULL)
                                    == PackageManager.PERMISSION_GRANTED) {
                userId = UserHandle.USER_CURRENT;
            } else {
                userId = context.getUserId();
            }
            sInstance = new AccessibilityManager(context, null, userId);
        }
    }
    return sInstance;
}
 
源代码6 项目: android_9.0.0_r45   文件: FingerprintManager.java
/**
 * 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 */));
        }
    }
}
 
源代码7 项目: android_9.0.0_r45   文件: ContentProvider.java
/** @hide */
public static Uri maybeAddUserId(Uri uri, int userId) {
    if (uri == null) return null;
    if (userId != UserHandle.USER_CURRENT
            && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
        if (!uriHasUserId(uri)) {
            //We don't add the user Id if there's already one
            Uri.Builder builder = uri.buildUpon();
            builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
            return builder.build();
        }
    }
    return uri;
}
 
源代码8 项目: AndroidComponentPlugin   文件: ContentProvider.java
/** @hide */
public static Uri maybeAddUserId(Uri uri, int userId) {
    if (uri == null) return null;
    if (userId != UserHandle.USER_CURRENT
            && ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
        if (!uriHasUserId(uri)) {
            //We don't add the user Id if there's already one
            Uri.Builder builder = uri.buildUpon();
            builder.encodedAuthority("" + userId + "@" + uri.getEncodedAuthority());
            return builder.build();
        }
    }
    return uri;
}
 
源代码9 项目: AndroidComponentPlugin   文件: ContentService.java
private int handleIncomingUser(Uri uri, int pid, int uid, int modeFlags, boolean allowNonFull,
        int userId) {
    if (userId == UserHandle.USER_CURRENT) {
        userId = ActivityManager.getCurrentUser();
    }

    if (userId == UserHandle.USER_ALL) {
        mContext.enforceCallingOrSelfPermission(
                Manifest.permission.INTERACT_ACROSS_USERS_FULL, "No access to " + uri);
    } else if (userId < 0) {
        throw new IllegalArgumentException("Invalid user: " + userId);
    } else if (userId != UserHandle.getCallingUserId()) {
        if (checkUriPermission(uri, pid, uid, modeFlags,
                userId) != PackageManager.PERMISSION_GRANTED) {
            boolean allow = false;
            if (mContext.checkCallingOrSelfPermission(
                    Manifest.permission.INTERACT_ACROSS_USERS_FULL)
                            == PackageManager.PERMISSION_GRANTED) {
                allow = true;
            } else if (allowNonFull && mContext.checkCallingOrSelfPermission(
                    Manifest.permission.INTERACT_ACROSS_USERS)
                            == PackageManager.PERMISSION_GRANTED) {
                allow = true;
            }
            if (!allow) {
                final String permissions = allowNonFull
                        ? (Manifest.permission.INTERACT_ACROSS_USERS_FULL + " or " +
                                Manifest.permission.INTERACT_ACROSS_USERS)
                        : Manifest.permission.INTERACT_ACROSS_USERS_FULL;
                throw new SecurityException("No access to " + uri + ": neither user " + uid
                        + " nor current process has " + permissions);
            }
        }
    }

    return userId;
}
 
private int getJobState(PrintWriter pw) throws Exception {
    checkPermission("force timeout jobs");

    int userId = UserHandle.USER_SYSTEM;

    String opt;
    while ((opt = getNextOption()) != null) {
        switch (opt) {
            case "-u":
            case "--user":
                userId = UserHandle.parseUserArg(getNextArgRequired());
                break;

            default:
                pw.println("Error: unknown option '" + opt + "'");
                return -1;
        }
    }

    if (userId == UserHandle.USER_CURRENT) {
        userId = ActivityManager.getCurrentUser();
    }

    final String pkgName = getNextArgRequired();
    final String jobIdStr = getNextArgRequired();
    final int jobId = Integer.parseInt(jobIdStr);

    final long ident = Binder.clearCallingIdentity();
    try {
        int ret = mInternal.getJobState(pw, pkgName, userId, jobId);
        printError(ret, pkgName, userId, jobId);
        return ret;
    } finally {
        Binder.restoreCallingIdentity(ident);
    }
}
 
源代码11 项目: android_9.0.0_r45   文件: ContentService.java
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;
}
 
源代码12 项目: android_9.0.0_r45   文件: AppOpsService.java
int parseUserOpMode(int defMode, PrintWriter err) throws RemoteException {
    userId = UserHandle.USER_CURRENT;
    opStr = null;
    modeStr = null;
    for (String argument; (argument = getNextArg()) != null;) {
        if ("--user".equals(argument)) {
            userId = UserHandle.parseUserArg(getNextArgRequired());
        } else {
            if (opStr == null) {
                opStr = argument;
            } else if (modeStr == null) {
                modeStr = argument;
                break;
            }
        }
    }
    if (opStr == null) {
        err.println("Error: Operation not specified.");
        return -1;
    }
    op = strOpToOp(opStr, err);
    if (op < 0) {
        return -1;
    }
    if (modeStr != null) {
        if ((mode=strModeToMode(modeStr, err)) < 0) {
            return -1;
        }
    } else {
        mode = defMode;
    }
    return 0;
}
 
源代码13 项目: android_9.0.0_r45   文件: ResolveInfo.java
public final int compare(ResolveInfo a, ResolveInfo b) {
    // We want to put the one targeted to another user at the end of the dialog.
    if (a.targetUserId != UserHandle.USER_CURRENT) {
        return 1;
    }
    if (b.targetUserId != UserHandle.USER_CURRENT) {
        return -1;
    }
    CharSequence  sa = a.loadLabel(mPM);
    if (sa == null) sa = a.activityInfo.name;
    CharSequence  sb = b.loadLabel(mPM);
    if (sb == null) sb = b.activityInfo.name;
    
    return mCollator.compare(sa.toString(), sb.toString());
}
 
源代码14 项目: android_9.0.0_r45   文件: ContentProvider.java
/** @hide */
public Uri validateIncomingUri(Uri uri) throws SecurityException {
    String auth = uri.getAuthority();
    if (!mSingleUser) {
        int userId = getUserIdFromAuthority(auth, UserHandle.USER_CURRENT);
        if (userId != UserHandle.USER_CURRENT && userId != mContext.getUserId()) {
            throw new SecurityException("trying to query a ContentProvider in user "
                    + mContext.getUserId() + " with a uri belonging to user " + userId);
        }
    }
    if (!matchesOurAuthorities(getAuthorityWithoutUserId(auth))) {
        String message = "The authority of the uri " + uri + " does not match the one of the "
                + "contentProvider: ";
        if (mAuthority != null) {
            message += mAuthority;
        } else {
            message += Arrays.toString(mAuthorities);
        }
        throw new SecurityException(message);
    }

    // Normalize the path by removing any empty path segments, which can be
    // a source of security issues.
    final String encodedPath = uri.getEncodedPath();
    if (encodedPath != null && encodedPath.indexOf("//") != -1) {
        final Uri normalized = uri.buildUpon()
                .encodedPath(encodedPath.replaceAll("//+", "/")).build();
        Log.w(TAG, "Normalized " + uri + " to " + normalized
                + " to avoid possible security issues");
        return normalized;
    } else {
        return uri;
    }
}
 
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;
}
 
int runGetStandbyBucket(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 = getNextArg();

    IUsageStatsManager usm = IUsageStatsManager.Stub.asInterface(ServiceManager.getService(
            Context.USAGE_STATS_SERVICE));
    if (packageName != null) {
        int bucket = usm.getAppStandbyBucket(packageName, null, userId);
        pw.println(bucket);
    } else {
        ParceledListSlice<AppStandbyInfo> buckets = usm.getAppStandbyBuckets(
                SHELL_PACKAGE_NAME, userId);
        for (AppStandbyInfo bucketInfo : buckets.getList()) {
            pw.print(bucketInfo.mPackageName); pw.print(": ");
            pw.println(bucketInfo.mStandbyBucket);
        }
    }
    return 0;
}
 
源代码17 项目: android_9.0.0_r45   文件: ContentProvider.java
@Override
public ContentProviderResult[] applyBatch(String callingPkg,
        ArrayList<ContentProviderOperation> operations)
        throws OperationApplicationException {
    int numOperations = operations.size();
    final int[] userIds = new int[numOperations];
    for (int i = 0; i < numOperations; i++) {
        ContentProviderOperation operation = operations.get(i);
        Uri uri = operation.getUri();
        userIds[i] = getUserIdFromUri(uri);
        uri = validateIncomingUri(uri);
        uri = maybeGetUriWithoutUserId(uri);
        // Rebuild operation if we changed the Uri above
        if (!Objects.equals(operation.getUri(), uri)) {
            operation = new ContentProviderOperation(operation, uri);
            operations.set(i, operation);
        }
        if (operation.isReadOperation()) {
            if (enforceReadPermission(callingPkg, uri, null)
                    != AppOpsManager.MODE_ALLOWED) {
                throw new OperationApplicationException("App op not allowed", 0);
            }
        }
        if (operation.isWriteOperation()) {
            if (enforceWritePermission(callingPkg, uri, null)
                    != AppOpsManager.MODE_ALLOWED) {
                throw new OperationApplicationException("App op not allowed", 0);
            }
        }
    }
    final String original = setCallingPackage(callingPkg);
    try {
        ContentProviderResult[] results = ContentProvider.this.applyBatch(operations);
        if (results != null) {
            for (int i = 0; i < results.length ; i++) {
                if (userIds[i] != UserHandle.USER_CURRENT) {
                    // Adding the userId to the uri.
                    results[i] = new ContentProviderResult(results[i], userIds[i]);
                }
            }
        }
        return results;
    } finally {
        setCallingPackage(original);
    }
}
 
源代码18 项目: android_9.0.0_r45   文件: ResolveInfo.java
public ResolveInfo() {
    targetUserId = UserHandle.USER_CURRENT;
}
 
int runDumpHeap(PrintWriter pw) throws RemoteException {
    final PrintWriter err = getErrPrintWriter();
    boolean managed = true;
    boolean mallocInfo = false;
    int userId = UserHandle.USER_CURRENT;
    boolean runGc = false;

    String opt;
    while ((opt=getNextOption()) != null) {
        if (opt.equals("--user")) {
            userId = UserHandle.parseUserArg(getNextArgRequired());
            if (userId == UserHandle.USER_ALL) {
                err.println("Error: Can't dump heap with user 'all'");
                return -1;
            }
        } else if (opt.equals("-n")) {
            managed = false;
        } else if (opt.equals("-g")) {
            runGc = true;
        } else if (opt.equals("-m")) {
            managed = false;
            mallocInfo = true;
        } else {
            err.println("Error: Unknown option: " + opt);
            return -1;
        }
    }
    String process = getNextArgRequired();
    String heapFile = getNextArgRequired();

    File file = new File(heapFile);
    file.delete();
    ParcelFileDescriptor fd = openFileForSystem(heapFile, "w");
    if (fd == null) {
        return -1;
    }

    if (!mInterface.dumpHeap(process, userId, managed, mallocInfo, runGc, heapFile, fd)) {
        err.println("HEAP DUMP FAILED on process " + process);
        return -1;
    }
    return 0;
}
 
int runSendTrimMemory(PrintWriter pw) throws RemoteException {
    int userId = UserHandle.USER_CURRENT;
    String opt;
    while ((opt = getNextOption()) != null) {
        if (opt.equals("--user")) {
            userId = UserHandle.parseUserArg(getNextArgRequired());
            if (userId == UserHandle.USER_ALL) {
                getErrPrintWriter().println("Error: Can't use user 'all'");
                return -1;
            }
        } else {
            getErrPrintWriter().println("Error: Unknown option: " + opt);
            return -1;
        }
    }

    String proc = getNextArgRequired();
    String levelArg = getNextArgRequired();
    int level;
    switch (levelArg) {
        case "HIDDEN":
            level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
            break;
        case "RUNNING_MODERATE":
            level = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
            break;
        case "BACKGROUND":
            level = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
            break;
        case "RUNNING_LOW":
            level = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
            break;
        case "MODERATE":
            level = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
            break;
        case "RUNNING_CRITICAL":
            level = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
            break;
        case "COMPLETE":
            level = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
            break;
        default:
            try {
                level = Integer.parseInt(levelArg);
            } catch (NumberFormatException e) {
                getErrPrintWriter().println("Error: Unknown level option: " + levelArg);
                return -1;
            }
    }
    if (!mInterface.setProcessMemoryTrimLevel(proc, userId, level)) {
        getErrPrintWriter().println("Unknown error: failed to set trim level");
        return -1;
    }
    return 0;
}