com.android.internal.util.Preconditions Java Examples

The following examples show how to use com.android.internal.util.Preconditions. 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: ContentProviderClient.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/** See {@link ContentProvider#getStreamTypes ContentProvider.getStreamTypes} */
public @Nullable String[] getStreamTypes(@NonNull Uri url, @NonNull String mimeTypeFilter)
        throws RemoteException {
    Preconditions.checkNotNull(url, "url");
    Preconditions.checkNotNull(mimeTypeFilter, "mimeTypeFilter");

    beforeRemote();
    try {
        return mContentProvider.getStreamTypes(url, mimeTypeFilter);
    } catch (DeadObjectException e) {
        if (!mStable) {
            mContentResolver.unstableProviderDied(mContentProvider);
        }
        throw e;
    } finally {
        afterRemote();
    }
}
 
Example #2
Source File: PrintManager.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the list of print services, but does not register for updates. The user has to register
 * for updates by itself, or use {@link PrintServicesLoader}.
 *
 * @param selectionFlags flags selecting which services to get. Either
 *                       {@link #ENABLED_SERVICES},{@link #DISABLED_SERVICES}, or both.
 *
 * @return The print service list or an empty list.
 *
 * @see #addPrintServicesChangeListener(PrintServicesChangeListener, Handler)
 * @see #removePrintServicesChangeListener(PrintServicesChangeListener)
 *
 * @hide
 */
@SystemApi
@RequiresPermission(android.Manifest.permission.READ_PRINT_SERVICES)
public @NonNull List<PrintServiceInfo> getPrintServices(int selectionFlags) {
    Preconditions.checkFlagsArgument(selectionFlags, ALL_SERVICES);

    try {
        List<PrintServiceInfo> services = mService.getPrintServices(selectionFlags, mUserId);
        if (services != null) {
            return services;
        }
    } catch (RemoteException re) {
        throw re.rethrowFromSystemServer();
    }
    return Collections.emptyList();
}
 
Example #3
Source File: ContentProviderClient.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * See {@link ContentProvider#openFile ContentProvider.openFile}.  Note that
 * this <em>does not</em>
 * take care of non-content: URIs such as file:.  It is strongly recommended
 * you use the {@link ContentResolver#openFileDescriptor
 * ContentResolver.openFileDescriptor} API instead.
 */
public @Nullable ParcelFileDescriptor openFile(@NonNull Uri url, @NonNull String mode,
        @Nullable CancellationSignal signal) throws RemoteException, FileNotFoundException {
    Preconditions.checkNotNull(url, "url");
    Preconditions.checkNotNull(mode, "mode");

    beforeRemote();
    try {
        ICancellationSignal remoteSignal = null;
        if (signal != null) {
            signal.throwIfCanceled();
            remoteSignal = mContentProvider.createCancellationSignal();
            signal.setRemote(remoteSignal);
        }
        return mContentProvider.openFile(mPackageName, url, mode, remoteSignal, null);
    } catch (DeadObjectException e) {
        if (!mStable) {
            mContentResolver.unstableProviderDied(mContentProvider);
        }
        throw e;
    } finally {
        afterRemote();
    }
}
 
Example #4
Source File: AssetManager.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Populates {@code outValue} with the data associated with a particular
 * resource identifier for the current configuration. Resolves theme
 * attributes against the specified theme.
 *
 * @param theme the native pointer of the theme
 * @param resId the resource identifier to load
 * @param outValue the typed value in which to put the data
 * @param resolveRefs {@code true} to resolve references, {@code false}
 *                    to leave them unresolved
 * @return {@code true} if the data was loaded into {@code outValue},
 *         {@code false} otherwise
 */
boolean getThemeValue(long theme, @AnyRes int resId, @NonNull TypedValue outValue,
        boolean resolveRefs) {
    Preconditions.checkNotNull(outValue, "outValue");
    synchronized (this) {
        ensureValidLocked();
        final int cookie = nativeThemeGetAttributeValue(mObject, theme, resId, outValue,
                resolveRefs);
        if (cookie <= 0) {
            return false;
        }

        // Convert the changing configurations flags populated by native code.
        outValue.changingConfigurations = ActivityInfo.activityInfoConfigNativeToJava(
                outValue.changingConfigurations);

        if (outValue.type == TypedValue.TYPE_STRING) {
            outValue.string = mApkAssets[cookie - 1].getStringFromPool(outValue.data);
        }
        return true;
    }
}
 
Example #5
Source File: ContentResolver.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Update row(s) in a content URI.
 *
 * If the content provider supports transactions the update will be atomic.
 *
 * @param uri The URI to modify.
 * @param values The new field values. The key is the column name for the field.
                 A null value will remove an existing field value.
 * @param where A filter to apply to rows before updating, formatted as an SQL WHERE clause
                (excluding the WHERE itself).
 * @return the number of rows updated.
 * @throws NullPointerException if uri or values are null
 */
public final int update(@RequiresPermission.Write @NonNull Uri uri,
        @Nullable ContentValues values, @Nullable String where,
        @Nullable String[] selectionArgs) {
    Preconditions.checkNotNull(uri, "uri");
    IContentProvider provider = acquireProvider(uri);
    if (provider == null) {
        throw new IllegalArgumentException("Unknown URI " + uri);
    }
    try {
        long startTime = SystemClock.uptimeMillis();
        int rowsUpdated = provider.update(mPackageName, uri, values, where, selectionArgs);
        long durationMillis = SystemClock.uptimeMillis() - startTime;
        maybeLogUpdateToEventLog(durationMillis, uri, "update", where);
        return rowsUpdated;
    } catch (RemoteException e) {
        // Arbitrary and not worth documenting, as Activity
        // Manager will kill this process shortly anyway.
        return -1;
    } finally {
        releaseProvider(provider);
    }
}
 
Example #6
Source File: KeySetManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public void removeAppKeySetDataLPw(String packageName) {

        /* remove refs from common keysets and public keys */
        PackageSetting pkg = mPackages.get(packageName);
        Preconditions.checkNotNull(pkg, "pkg name: " + packageName
                + "does not have a corresponding entry in mPackages.");
        long signingKeySetId = pkg.keySetData.getProperSigningKeySet();
        decrementKeySetLPw(signingKeySetId);
        ArrayMap<String, Long> definedKeySets = pkg.keySetData.getAliases();
        for (int i = 0; i < definedKeySets.size(); i++) {
            decrementKeySetLPw(definedKeySets.valueAt(i));
        }

        /* remove from package */
        clearPackageKeySetDataLPw(pkg);
        return;
    }
 
Example #7
Source File: ApplicationPackageManager.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
@Override
public int movePrimaryStorage(VolumeInfo vol) {
    try {
        final String volumeUuid;
        if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
            volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
        } else if (vol.isPrimaryPhysical()) {
            volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
        } else {
            volumeUuid = Preconditions.checkNotNull(vol.fsUuid);
        }

        return mPM.movePrimaryStorage(volumeUuid);
    } catch (RemoteException e) {
        throw e.rethrowAsRuntimeException();
    }
}
 
Example #8
Source File: SelectionActionModeHelper.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public void logSelectionModified(int start, int end,
        @Nullable TextClassification classification, @Nullable TextSelection selection) {
    try {
        if (hasActiveClassificationSession()) {
            Preconditions.checkArgumentInRange(start, 0, mText.length(), "start");
            Preconditions.checkArgumentInRange(end, start, mText.length(), "end");
            int[] wordIndices = getWordDelta(start, end);
            if (selection != null) {
                mClassificationSession.onSelectionEvent(
                        SelectionEvent.createSelectionModifiedEvent(
                                wordIndices[0], wordIndices[1], selection));
            } else if (classification != null) {
                mClassificationSession.onSelectionEvent(
                        SelectionEvent.createSelectionModifiedEvent(
                                wordIndices[0], wordIndices[1], classification));
            } else {
                mClassificationSession.onSelectionEvent(
                        SelectionEvent.createSelectionModifiedEvent(
                                wordIndices[0], wordIndices[1]));
            }
        }
    } catch (Exception e) {
        // Avoid crashes due to logging.
        Log.e(LOG_TAG, "" + e.getMessage(), e);
    }
}
 
Example #9
Source File: MacAddress.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private static long longAddrFromStringAddr(String addr) {
    Preconditions.checkNotNull(addr);
    String[] parts = addr.split(":");
    if (parts.length != ETHER_ADDR_LEN) {
        throw new IllegalArgumentException(addr + " was not a valid MAC address");
    }
    long longAddr = 0;
    for (int i = 0; i < parts.length; i++) {
        int x = Integer.valueOf(parts[i], 16);
        if (x < 0 || 0xff < x) {
            throw new IllegalArgumentException(addr + "was not a valid MAC address");
        }
        longAddr = x + (longAddr << 8);
    }
    return longAddr;
}
 
Example #10
Source File: ApplicationPackageManager.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
@Override
public int movePrimaryStorage(VolumeInfo vol) {
    try {
        final String volumeUuid;
        if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
            volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
        } else if (vol.isPrimaryPhysical()) {
            volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
        } else {
            volumeUuid = Preconditions.checkNotNull(vol.fsUuid);
        }

        return mPM.movePrimaryStorage(volumeUuid);
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
 
Example #11
Source File: LongitudinalReportingConfig.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor to create {@link LongitudinalReportingConfig} used for {@link
 * LongitudinalReportingEncoder}
 *
 * @param encoderId    Unique encoder id.
 * @param probabilityF Probability F used in Longitudinal Reporting algorithm.
 * @param probabilityP Probability P used in Longitudinal Reporting algorithm. This will be
 *                     quantized to the nearest 1/256.
 * @param probabilityQ Probability Q used in Longitudinal Reporting algorithm. This will be
 *                     quantized to the nearest 1/256.
 */
public LongitudinalReportingConfig(String encoderId, double probabilityF,
        double probabilityP, double probabilityQ) {
    Preconditions.checkArgument(probabilityF >= 0 && probabilityF <= 1,
            "probabilityF must be in range [0.0, 1.0]");
    this.mProbabilityF = probabilityF;
    Preconditions.checkArgument(probabilityP >= 0 && probabilityP <= 1,
            "probabilityP must be in range [0.0, 1.0]");
    this.mProbabilityP = probabilityP;
    Preconditions.checkArgument(probabilityQ >= 0 && probabilityQ <= 1,
            "probabilityQ must be in range [0.0, 1.0]");
    this.mProbabilityQ = probabilityQ;
    Preconditions.checkArgument(!TextUtils.isEmpty(encoderId), "encoderId cannot be empty");
    mEncoderId = encoderId;
    mIRRConfig = new RapporConfig(encoderId, 1, 0.0, probabilityF, 1 - probabilityF, 1, 1);
}
 
Example #12
Source File: ContentResolver.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Inserts multiple rows into a table at the given URL.
 *
 * This function make no guarantees about the atomicity of the insertions.
 *
 * @param url The URL of the table to insert into.
 * @param values The initial values for the newly inserted rows. The key is the column name for
 *               the field. Passing null will create an empty row.
 * @return the number of newly created rows.
 */
public final int bulkInsert(@RequiresPermission.Write @NonNull Uri url,
            @NonNull ContentValues[] values) {
    Preconditions.checkNotNull(url, "url");
    Preconditions.checkNotNull(values, "values");
    IContentProvider provider = acquireProvider(url);
    if (provider == null) {
        throw new IllegalArgumentException("Unknown URL " + url);
    }
    try {
        long startTime = SystemClock.uptimeMillis();
        int rowsCreated = provider.bulkInsert(mPackageName, url, values);
        long durationMillis = SystemClock.uptimeMillis() - startTime;
        maybeLogUpdateToEventLog(durationMillis, url, "bulkinsert", null /* where */);
        return rowsCreated;
    } catch (RemoteException e) {
        // Arbitrary and not worth documenting, as Activity
        // Manager will kill this process shortly anyway.
        return 0;
    } finally {
        releaseProvider(provider);
    }
}
 
Example #13
Source File: LockSettingsStorage.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public static byte[] toBytes(int persistentType, int userId, int qualityForUi,
        byte[] payload) {
    if (persistentType == PersistentData.TYPE_NONE) {
        Preconditions.checkArgument(payload == null,
                "TYPE_NONE must have empty payload");
        return null;
    }
    Preconditions.checkArgument(payload != null && payload.length > 0,
            "empty payload must only be used with TYPE_NONE");

    ByteArrayOutputStream os = new ByteArrayOutputStream(
            VERSION_1_HEADER_SIZE + payload.length);
    DataOutputStream dos = new DataOutputStream(os);
    try {
        dos.writeByte(PersistentData.VERSION_1);
        dos.writeByte(persistentType);
        dos.writeInt(userId);
        dos.writeInt(qualityForUi);
        dos.write(payload);
    } catch (IOException e) {
        throw new RuntimeException("ByteArrayOutputStream cannot throw IOException");
    }
    return os.toByteArray();
}
 
Example #14
Source File: ApplicationPackageManager.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
@Override
public int movePackage(String packageName, VolumeInfo vol) {
    try {
        final String volumeUuid;
        if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
            volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
        } else if (vol.isPrimaryPhysical()) {
            volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
        } else {
            volumeUuid = Preconditions.checkNotNull(vol.fsUuid);
        }

        return mPM.movePackage(packageName, volumeUuid);
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
 
Example #15
Source File: PrecomputedText.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Returns text width for the given range.
 * Both {@code start} and {@code end} offset need to be in the same paragraph, otherwise
 * IllegalArgumentException will be thrown.
 *
 * @param start the inclusive start offset in the text
 * @param end the exclusive end offset in the text
 * @return the text width
 * @throws IllegalArgumentException if start and end offset are in the different paragraph.
 */
public @FloatRange(from = 0) float getWidth(@IntRange(from = 0) int start,
        @IntRange(from = 0) int end) {
    Preconditions.checkArgument(0 <= start && start <= mText.length(), "invalid start offset");
    Preconditions.checkArgument(0 <= end && end <= mText.length(), "invalid end offset");
    Preconditions.checkArgument(start <= end, "start offset can not be larger than end offset");

    if (start == end) {
        return 0;
    }
    final int paraIndex = findParaIndex(start);
    final int paraStart = getParagraphStart(paraIndex);
    final int paraEnd = getParagraphEnd(paraIndex);
    if (start < paraStart || paraEnd < end) {
        throw new IllegalArgumentException("Cannot measured across the paragraph:"
            + "para: (" + paraStart + ", " + paraEnd + "), "
            + "request: (" + start + ", " + end + ")");
    }
    return getMeasuredParagraph(paraIndex).getWidth(start - paraStart, end - paraStart);
}
 
Example #16
Source File: ContentResolver.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
/**
 * Call a provider-defined method.  This can be used to implement
 * read or write interfaces which are cheaper than using a Cursor and/or
 * do not fit into the traditional table model.
 *
 * @param method provider-defined method name to call.  Opaque to
 *   framework, but must be non-null.
 * @param arg provider-defined String argument.  May be null.
 * @param extras provider-defined Bundle argument.  May be null.
 * @return a result Bundle, possibly null.  Will be null if the ContentProvider
 *   does not implement call.
 * @throws NullPointerException if uri or method is null
 * @throws IllegalArgumentException if uri is not known
 */
public final @Nullable Bundle call(@NonNull Uri uri, @NonNull String method,
        @Nullable String arg, @Nullable Bundle extras) {
    Preconditions.checkNotNull(uri, "uri");
    Preconditions.checkNotNull(method, "method");
    IContentProvider provider = acquireProvider(uri);
    if (provider == null) {
        throw new IllegalArgumentException("Unknown URI " + uri);
    }
    try {
        final Bundle res = provider.call(mPackageName, method, arg, extras);
        Bundle.setDefusable(res, true);
        return res;
    } catch (RemoteException e) {
        // Arbitrary and not worth documenting, as Activity
        // Manager will kill this process shortly anyway.
        return null;
    } finally {
        releaseProvider(provider);
    }
}
 
Example #17
Source File: AmbientBrightnessDayStats.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static void checkSorted(float[] values) {
    if (values.length <= 1) {
        return;
    }
    float prevValue = values[0];
    for (int i = 1; i < values.length; i++) {
        Preconditions.checkState(prevValue < values[i]);
        prevValue = values[i];
    }
    return;
}
 
Example #18
Source File: SmartSelectionEventTracker.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Logs a selection event.
 *
 * @param event the selection event
 */
public void logEvent(@NonNull SelectionEvent event) {
    Preconditions.checkNotNull(event);

    if (event.mEventType != SelectionEvent.EventType.SELECTION_STARTED && mSessionId == null
            && DEBUG_LOG_ENABLED) {
        Log.d(LOG_TAG, "Selection session not yet started. Ignoring event");
        return;
    }

    final long now = System.currentTimeMillis();
    switch (event.mEventType) {
        case SelectionEvent.EventType.SELECTION_STARTED:
            mSessionId = startNewSession();
            Preconditions.checkArgument(event.mEnd == event.mStart + 1);
            mOrigStart = event.mStart;
            mSessionStartTime = now;
            break;
        case SelectionEvent.EventType.SMART_SELECTION_SINGLE:  // fall through
        case SelectionEvent.EventType.SMART_SELECTION_MULTI:
            mSmartSelectionTriggered = true;
            mModelName = getModelName(event);
            mSmartIndices[0] = event.mStart;
            mSmartIndices[1] = event.mEnd;
            break;
        case SelectionEvent.EventType.SELECTION_MODIFIED:  // fall through
        case SelectionEvent.EventType.AUTO_SELECTION:
            if (mPrevIndices[0] == event.mStart && mPrevIndices[1] == event.mEnd) {
                // Selection did not change. Ignore event.
                return;
            }
    }
    writeEvent(event, now);

    if (event.isTerminal()) {
        endSession();
    }
}
 
Example #19
Source File: ContentResolver.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/**
 * Open a stream on to the content associated with a content URI.  If there
 * is no data associated with the URI, FileNotFoundException is thrown.
 *
 * <h5>Accepts the following URI schemes:</h5>
 * <ul>
 * <li>content ({@link #SCHEME_CONTENT})</li>
 * <li>android.resource ({@link #SCHEME_ANDROID_RESOURCE})</li>
 * <li>file ({@link #SCHEME_FILE})</li>
 * </ul>
 *
 * <p>See {@link #openAssetFileDescriptor(Uri, String)} for more information
 * on these schemes.
 *
 * @param uri The desired URI.
 * @return InputStream
 * @throws FileNotFoundException if the provided URI could not be opened.
 * @see #openAssetFileDescriptor(Uri, String)
 */
public final @Nullable InputStream openInputStream(@NonNull Uri uri)
        throws FileNotFoundException {
    Preconditions.checkNotNull(uri, "uri");
    String scheme = uri.getScheme();
    if (SCHEME_ANDROID_RESOURCE.equals(scheme)) {
        // Note: left here to avoid breaking compatibility.  May be removed
        // with sufficient testing.
        OpenResourceIdResult r = getResourceId(uri);
        try {
            InputStream stream = r.r.openRawResource(r.id);
            return stream;
        } catch (Resources.NotFoundException ex) {
            throw new FileNotFoundException("Resource does not exist: " + uri);
        }
    } else if (SCHEME_FILE.equals(scheme)) {
        // Note: left here to avoid breaking compatibility.  May be removed
        // with sufficient testing.
        return new FileInputStream(uri.getPath());
    } else {
        AssetFileDescriptor fd = openAssetFileDescriptor(uri, "r", null);
        try {
            return fd != null ? fd.createInputStream() : null;
        } catch (IOException e) {
            throw new FileNotFoundException("Unable to create stream");
        }
    }
}
 
Example #20
Source File: NetworkPolicy.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public NetworkPolicy(NetworkTemplate template, RecurrenceRule cycleRule, long warningBytes,
        long limitBytes, long lastWarningSnooze, long lastLimitSnooze, long lastRapidSnooze,
        boolean metered, boolean inferred) {
    this.template = Preconditions.checkNotNull(template, "missing NetworkTemplate");
    this.cycleRule = Preconditions.checkNotNull(cycleRule, "missing RecurrenceRule");
    this.warningBytes = warningBytes;
    this.limitBytes = limitBytes;
    this.lastWarningSnooze = lastWarningSnooze;
    this.lastLimitSnooze = lastLimitSnooze;
    this.lastRapidSnooze = lastRapidSnooze;
    this.metered = metered;
    this.inferred = inferred;
}
 
Example #21
Source File: UsbManager.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the status of the specified USB port.
 *
 * @param port The port to query.
 * @return The status of the specified USB port, or null if unknown.
 *
 * @hide
 */
public UsbPortStatus getPortStatus(UsbPort port) {
    Preconditions.checkNotNull(port, "port must not be null");

    try {
        return mService.getPortStatus(port.getId());
    } 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 */
@Override
public KeySet getKeySetByAlias(String packageName, String alias) {
    Preconditions.checkNotNull(packageName);
    Preconditions.checkNotNull(alias);
    try {
        return mPM.getKeySetByAlias(packageName, alias);
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
 
Example #23
Source File: ShortcutService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public ParcelFileDescriptor getShortcutIconFd(int launcherUserId,
        @NonNull String callingPackage, @NonNull String packageName,
        @NonNull String shortcutId, int userId) {
    Preconditions.checkNotNull(callingPackage, "callingPackage");
    Preconditions.checkNotNull(packageName, "packageName");
    Preconditions.checkNotNull(shortcutId, "shortcutId");

    synchronized (mLock) {
        throwIfUserLockedL(userId);
        throwIfUserLockedL(launcherUserId);

        getLauncherShortcutsLocked(callingPackage, userId, launcherUserId)
                .attemptToRestoreIfNeededAndSave();

        final ShortcutPackage p = getUserShortcutsLocked(userId)
                .getPackageShortcutsIfExists(packageName);
        if (p == null) {
            return null;
        }

        final ShortcutInfo shortcutInfo = p.findShortcutById(shortcutId);
        if (shortcutInfo == null || !shortcutInfo.hasIconFile()) {
            return null;
        }
        final String path = mShortcutBitmapSaver.getBitmapPathMayWaitLocked(shortcutInfo);
        if (path == null) {
            Slog.w(TAG, "null bitmap detected in getShortcutIconFd()");
            return null;
        }
        try {
            return ParcelFileDescriptor.open(
                    new File(path),
                    ParcelFileDescriptor.MODE_READ_ONLY);
        } catch (FileNotFoundException e) {
            Slog.e(TAG, "Icon file not found: " + path);
            return null;
        }
    }
}
 
Example #24
Source File: TextClassifierService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void onCreateTextClassificationSession(
        TextClassificationContext context, TextClassificationSessionId sessionId)
        throws RemoteException {
    Preconditions.checkNotNull(context);
    Preconditions.checkNotNull(sessionId);
    TextClassifierService.this.onCreateTextClassificationSession(context, sessionId);
}
 
Example #25
Source File: ShortcutInfo.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Throws if any of the mandatory fields is not set.
 *
 * @hide
 */
public void enforceMandatoryFields(boolean forPinned) {
    Preconditions.checkStringNotEmpty(mId, "Shortcut ID must be provided");
    if (!forPinned) {
        Preconditions.checkNotNull(mActivity, "Activity must be provided");
    }
    if (mTitle == null && mTitleResId == 0) {
        throw new IllegalArgumentException("Short label must be provided");
    }
    Preconditions.checkNotNull(mIntents, "Shortcut Intent must be provided");
    Preconditions.checkArgument(mIntents.length > 0, "Shortcut Intent must be provided");
}
 
Example #26
Source File: AssetManager.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve a non-asset as a compiled XML file.  Not for use by
 * applications.
 * 
 * @param cookie Identifier of the package to be opened.
 * @param fileName Name of the asset to retrieve.
 * @hide
 */
@NonNull XmlBlock openXmlBlockAsset(int cookie, @NonNull String fileName) throws IOException {
    Preconditions.checkNotNull(fileName, "fileName");
    synchronized (this) {
        ensureOpenLocked();
        final long xmlBlock = nativeOpenXmlAsset(mObject, cookie, fileName);
        if (xmlBlock == 0) {
            throw new FileNotFoundException("Asset XML file: " + fileName);
        }
        final XmlBlock block = new XmlBlock(this, xmlBlock);
        incRefsLocked(block.hashCode());
        return block;
    }
}
 
Example #27
Source File: UsbDevice.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * UsbDevice should only be instantiated by UsbService implementation
 * @hide
 */
public UsbDevice(@NonNull String name, int vendorId, int productId, int Class, int subClass,
        int protocol, @Nullable String manufacturerName, @Nullable String productName,
        @NonNull String version, @Nullable String serialNumber) {
    mName = Preconditions.checkNotNull(name);
    mVendorId = vendorId;
    mProductId = productId;
    mClass = Class;
    mSubclass = subClass;
    mProtocol = protocol;
    mManufacturerName = manufacturerName;
    mProductName = productName;
    mVersion = Preconditions.checkStringNotEmpty(version);
    mSerialNumber = serialNumber;
}
 
Example #28
Source File: TextClassificationManager.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/** @hide */
public static TextClassificationConstants getSettings(Context context) {
    Preconditions.checkNotNull(context);
    final TextClassificationManager tcm =
            context.getSystemService(TextClassificationManager.class);
    if (tcm != null) {
        return tcm.getSettings();
    } else {
        return TextClassificationConstants.loadFromString(Settings.Global.getString(
                context.getApplicationContext().getContentResolver(),
                Settings.Global.TEXT_CLASSIFIER_CONSTANTS));
    }
}
 
Example #29
Source File: ApplicationPackageManager.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/** @hide */
@Override
public boolean isSignedByExactly(String packageName, KeySet ks) {
    Preconditions.checkNotNull(packageName);
    Preconditions.checkNotNull(ks);
    try {
        return mPM.isPackageSignedByKeySetExactly(packageName, ks);
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
 
Example #30
Source File: SelectionActionModeHelper.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private int countWordsBackward(int from) {
    Preconditions.checkArgument(from >= mStartIndex);
    int wordCount = 0;
    int offset = from;
    while (offset > mStartIndex) {
        int start = mTokenIterator.preceding(offset);
        if (!isWhitespace(start, offset)) {
            wordCount++;
        }
        offset = start;
    }
    return wordCount;
}