android.annotation.Nullable Java Examples
The following examples show how to use
android.annotation.Nullable.
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: ShortcutInfo.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
/** * Return the resource ID for a given resource ID. * * Basically its' a wrapper over {@link Resources#getIdentifier(String, String, String)}, except * if {@code resourceName} is an integer then it'll just return its value. (Which also the * aforementioned method would do internally, but not documented, so doing here explicitly.) * * @param res {@link Resources} for the publisher. Must have been loaded with * {@link PackageManager#getResourcesForApplicationAsUser}. * * @hide */ @VisibleForTesting public static int lookUpResourceId(@NonNull Resources res, @Nullable String resourceName, @Nullable String resourceType, String packageName) { if (resourceName == null) { return 0; } try { try { // It the name can be parsed as an integer, just use it. return Integer.parseInt(resourceName); } catch (NumberFormatException ignore) { } return res.getIdentifier(resourceName, resourceType, packageName); } catch (NotFoundException e) { Log.e(TAG, "Resource ID for name=" + resourceName + " not found in package " + packageName); return 0; } }
Example #2
Source File: WindowTracing.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
void stopTrace(@Nullable PrintWriter pw) { if (IS_USER){ logAndPrintln(pw, "Error: Tracing is not supported on user builds."); return; } synchronized (mLock) { logAndPrintln(pw, "Stop tracing to " + mTraceFile + ". Waiting for traces to flush."); mEnabled = mEnabledLockFree = false; while (!mWriteQueue.isEmpty()) { if (mEnabled) { logAndPrintln(pw, "ERROR: tracing was re-enabled while waiting for flush."); throw new IllegalStateException("tracing enabled while waiting for flush."); } try { mLock.wait(); mLock.notify(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } logAndPrintln(pw, "Trace written to " + mTraceFile + "."); } }
Example #3
Source File: ColorStateList.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
/** * Creates a ColorStateList from an XML document using given a set of * {@link Resources} and a {@link Theme}. * * @param r Resources against which the ColorStateList should be inflated. * @param parser Parser for the XML document defining the ColorStateList. * @param theme Optional theme to apply to the color state list, may be * {@code null}. * @return A new color state list. */ @NonNull public static ColorStateList createFromXml(@NonNull Resources r, @NonNull XmlPullParser parser, @Nullable Theme theme) throws XmlPullParserException, IOException { final AttributeSet attrs = Xml.asAttributeSet(parser); int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Seek parser to start tag. } if (type != XmlPullParser.START_TAG) { throw new XmlPullParserException("No start tag found"); } return createFromXmlInner(r, parser, attrs, theme); }
Example #4
Source File: TunerAdapter.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
@Override public @NonNull List<RadioManager.ProgramInfo> getProgramList(@Nullable Map<String, String> vendorFilter) { synchronized (mTuner) { if (mLegacyListProxy == null || !Objects.equals(mLegacyListFilter, vendorFilter)) { Log.i(TAG, "Program list filter has changed, requesting new list"); mLegacyListProxy = new ProgramList(); mLegacyListFilter = vendorFilter; mCallback.clearLastCompleteList(); mCallback.setProgramListObserver(mLegacyListProxy, () -> { }); try { mTuner.startProgramListUpdates(new ProgramList.Filter(vendorFilter)); } catch (RemoteException ex) { throw new RuntimeException("service died", ex); } } List<RadioManager.ProgramInfo> list = mCallback.getLastCompleteList(); if (list == null) throw new IllegalStateException("Program list is not ready yet"); return list; } }
Example #5
Source File: VibrationEffect.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
/** * Get a predefined vibration effect associated with a given URI. * * Predefined effects are a set of common vibration effects that should be identical, regardless * of the app they come from, in order to provide a cohesive experience for users across * the entire device. They also may be custom tailored to the device hardware in order to * provide a better experience than you could otherwise build using the generic building * blocks. * * @param uri The URI associated with the haptic effect. * @param context The context used to get the URI to haptic effect association. * * @return The desired effect, or {@code null} if there's no associated effect. * * @hide */ @Nullable public static VibrationEffect get(Uri uri, Context context) { String[] uris = context.getResources().getStringArray( com.android.internal.R.array.config_ringtoneEffectUris); for (int i = 0; i < uris.length && i < RINGTONES.length; i++) { if (uris[i] == null) { continue; } ContentResolver cr = context.getContentResolver(); Uri mappedUri = cr.uncanonicalize(Uri.parse(uris[i])); if (mappedUri == null) { continue; } if (mappedUri.equals(uri)) { return get(RINGTONES[i]); } } return null; }
Example #6
Source File: ApplicationPackageManager.java From AndroidComponentPlugin with Apache License 2.0 | 6 votes |
@Nullable private Drawable getCachedIcon(@NonNull ResourceName name) { synchronized (sSync) { final WeakReference<Drawable.ConstantState> wr = sIconCache.get(name); if (DEBUG_ICONS) Log.v(TAG, "Get cached weak drawable ref for " + name + ": " + wr); if (wr != null) { // we have the activity final Drawable.ConstantState state = wr.get(); if (state != null) { if (DEBUG_ICONS) { Log.v(TAG, "Get cached drawable state for " + name + ": " + state); } // Note: It's okay here to not use the newDrawable(Resources) variant // of the API. The ConstantState comes from a drawable that was // originally created by passing the proper app Resources instance // which means the state should already contain the proper // resources specific information (like density.) See // BitmapDrawable.BitmapState for instance. return state.newDrawable(); } // our entry has been purged sIconCache.remove(name); } } return null; }
Example #7
Source File: Convert.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
static @NonNull ArrayList<VendorKeyValue> vendorInfoToHal(@Nullable Map<String, String> info) { if (info == null) return new ArrayList<>(); ArrayList<VendorKeyValue> list = new ArrayList<>(); for (Map.Entry<String, String> entry : info.entrySet()) { VendorKeyValue elem = new VendorKeyValue(); elem.key = entry.getKey(); elem.value = entry.getValue(); if (elem.key == null || elem.value == null) { Slog.w(TAG, "VendorKeyValue contains null pointers"); continue; } list.add(elem); } return list; }
Example #8
Source File: SQLiteQueryBuilder.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
private @Nullable String computeWhere(@Nullable String selection) { final boolean hasInternal = !TextUtils.isEmpty(mWhereClause); final boolean hasExternal = !TextUtils.isEmpty(selection); if (hasInternal || hasExternal) { final StringBuilder where = new StringBuilder(); if (hasInternal) { where.append('(').append(mWhereClause).append(')'); } if (hasInternal && hasExternal) { where.append(" AND "); } if (hasExternal) { where.append('(').append(selection).append(')'); } return where.toString(); } else { return null; } }
Example #9
Source File: ShortcutService.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
/** * Do not use directly; this returns uninstalled packages too. */ @Nullable @VisibleForTesting ActivityInfo injectGetActivityInfoWithMetadataWithUninstalled( ComponentName activity, @UserIdInt int userId) { final long start = getStatStartTime(); final long token = injectClearCallingIdentity(); try { return mIPackageManager.getActivityInfo(activity, (PACKAGE_MATCH_FLAGS | PackageManager.GET_META_DATA), userId); } catch (RemoteException e) { // Shouldn't happen. Slog.wtf(TAG, "RemoteException", e); return null; } finally { injectRestoreCallingIdentity(token); logDurationStat(Stats.GET_ACTIVITY_WITH_METADATA, start); } }
Example #10
Source File: SelectionActionModeHelper.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
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 #11
Source File: RadioModule.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
public static @Nullable RadioModule tryLoadingModule(int idx, @NonNull String fqName) { try { IBroadcastRadio service = IBroadcastRadio.getService(fqName); if (service == null) return null; Mutable<AmFmRegionConfig> amfmConfig = new Mutable<>(); service.getAmFmRegionConfig(false, (result, config) -> { if (result == Result.OK) amfmConfig.value = config; }); Mutable<List<DabTableEntry>> dabConfig = new Mutable<>(); service.getDabRegionConfig((result, config) -> { if (result == Result.OK) dabConfig.value = config; }); RadioManager.ModuleProperties prop = Convert.propertiesFromHal(idx, fqName, service.getProperties(), amfmConfig.value, dabConfig.value); return new RadioModule(service, prop); } catch (RemoteException ex) { Slog.e(TAG, "failed to load module " + fqName, ex); return null; } }
Example #12
Source File: ImageView.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** @hide **/ public Runnable setImageURIAsync(@Nullable Uri uri) { if (mResource != 0 || (mUri != uri && (uri == null || mUri == null || !uri.equals(mUri)))) { Drawable d = uri == null ? null : getDrawableFromUri(uri); if (d == null) { // Do not set the URI if the drawable couldn't be loaded. uri = null; } return new ImageDrawableCallback(d, uri, 0); } return null; }
Example #13
Source File: MimeTypeMap.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * If the given MIME type is {@code null}, or one of the "generic" types (text/plain * or application/octet-stream) map it to a type that Android can deal with. * If the given type is not generic, return it unchanged. * * @param mimeType MIME type provided by the server. * @param url URL of the data being loaded. * @param contentDisposition Content-disposition header given by the server. * @return The MIME type that should be used for this data. */ /* package */ String remapGenericMimeType(@Nullable String mimeType, String url, String contentDisposition) { // If we have one of "generic" MIME types, try to deduce // the right MIME type from the file extension (if any): if ("text/plain".equals(mimeType) || "application/octet-stream".equals(mimeType)) { // for attachment, use the filename in the Content-Disposition // to guess the mimetype String filename = null; if (contentDisposition != null) { filename = URLUtil.parseContentDisposition(contentDisposition); } if (filename != null) { url = filename; } String extension = getFileExtensionFromUrl(url); String newMimeType = getMimeTypeFromExtension(extension); if (newMimeType != null) { mimeType = newMimeType; } } else if ("text/vnd.wap.wml".equals(mimeType)) { // As we don't support wml, render it as plain text mimeType = "text/plain"; } else { // It seems that xhtml+xml and vnd.wap.xhtml+xml mime // subtypes are used interchangeably. So treat them the same. if ("application/vnd.wap.xhtml+xml".equals(mimeType)) { mimeType = "application/xhtml+xml"; } } return mimeType; }
Example #14
Source File: RecordingCanvas.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
@Override public final void drawPatch(@NonNull NinePatch patch, @NonNull Rect dst, @Nullable Paint paint) { Bitmap bitmap = patch.getBitmap(); throwIfCannotDraw(bitmap); final long nativePaint = paint == null ? 0 : paint.getNativeInstance(); nDrawNinePatch(mNativeCanvasWrapper, bitmap.getNativeInstance(), patch.mNativeChunk, dst.left, dst.top, dst.right, dst.bottom, nativePaint, mDensity, patch.getDensity()); }
Example #15
Source File: FingerprintManager.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Per-user version, see {@link FingerprintManager#authenticate(CryptoObject, * CancellationSignal, int, AuthenticationCallback, Handler)} * @param userId the user ID that the fingerprint hardware will authenticate for. * @hide */ @RequiresPermission(anyOf = {USE_BIOMETRIC, USE_FINGERPRINT}) public void authenticate(@Nullable CryptoObject crypto, @Nullable CancellationSignal cancel, int flags, @NonNull AuthenticationCallback callback, Handler handler, int userId) { if (callback == null) { throw new IllegalArgumentException("Must supply an authentication callback"); } if (cancel != null) { if (cancel.isCanceled()) { Slog.w(TAG, "authentication already canceled"); return; } else { cancel.setOnCancelListener(new OnAuthenticationCancelListener(crypto)); } } if (mService != null) try { useHandler(handler); mAuthenticationCallback = callback; mCryptoObject = crypto; long sessionId = crypto != null ? crypto.getOpId() : 0; mService.authenticate(mToken, sessionId, userId, mServiceReceiver, flags, mContext.getOpPackageName(), null /* bundle */, null /* receiver */); } catch (RemoteException e) { Slog.w(TAG, "Remote exception while authenticating: ", e); if (callback != null) { // Though this may not be a hardware issue, it will cause apps to give up or try // again later. callback.onAuthenticationError(FINGERPRINT_ERROR_HW_UNAVAILABLE, getErrorString(FINGERPRINT_ERROR_HW_UNAVAILABLE, 0 /* vendorCode */)); } } }
Example #16
Source File: InstantAppRegistry.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
private static @Nullable InstantAppInfo parseMetadata(@NonNull XmlPullParser parser, @NonNull String packageName) throws IOException, XmlPullParserException { final int outerDepth = parser.getDepth(); while (XmlUtils.nextElementWithin(parser, outerDepth)) { if (TAG_PACKAGE.equals(parser.getName())) { return parsePackage(parser, packageName); } } return null; }
Example #17
Source File: ResourcesManager.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Find the ResourcesKey that this ResourcesImpl object is associated with. * @return the ResourcesKey or null if none was found. */ private @Nullable ResourcesKey findKeyForResourceImplLocked( @NonNull ResourcesImpl resourceImpl) { final int refCount = mResourceImpls.size(); for (int i = 0; i < refCount; i++) { WeakReference<ResourcesImpl> weakImplRef = mResourceImpls.valueAt(i); ResourcesImpl impl = weakImplRef != null ? weakImplRef.get() : null; if (impl != null && resourceImpl == impl) { return mResourceImpls.keyAt(i); } } return null; }
Example #18
Source File: SQLiteQueryBuilder.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Wrap given argument in parenthesis, unless it's {@code null} or * {@code ()}, in which case return it verbatim. */ private @Nullable String wrap(@Nullable String arg) { if (TextUtils.isEmpty(arg)) { return arg; } else { return "(" + arg + ")"; } }
Example #19
Source File: Slice.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Add an action to the slice being constructed * @param subType Optional template-specific type information * @see SliceItem#getSubType() */ public Slice.Builder addAction(@NonNull PendingIntent action, @NonNull Slice s, @Nullable @SliceSubtype String subType) { Preconditions.checkNotNull(action); Preconditions.checkNotNull(s); List<String> hints = s.getHints(); s.mSpec = null; mItems.add(new SliceItem(action, s, SliceItem.FORMAT_ACTION, subType, hints.toArray( new String[hints.size()]))); return this; }
Example #20
Source File: Dialog.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Set a listener to be invoked when the dialog is dismissed. * @param listener The {@link DialogInterface.OnDismissListener} to use. */ public void setOnDismissListener(@Nullable OnDismissListener listener) { if (mCancelAndDismissTaken != null) { throw new IllegalStateException( "OnDismissListener is already taken by " + mCancelAndDismissTaken + " and can not be replaced."); } if (listener != null) { mDismissMessage = mListenersHandler.obtainMessage(DISMISS, listener); } else { mDismissMessage = null; } }
Example #21
Source File: UserManagerService.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
@Override public boolean requestQuietModeEnabled(@NonNull String callingPackage, boolean enableQuietMode, int userHandle, @Nullable IntentSender target) { Preconditions.checkNotNull(callingPackage); if (enableQuietMode && target != null) { throw new IllegalArgumentException( "target should only be specified when we are disabling quiet mode."); } ensureCanModifyQuietMode(callingPackage, Binder.getCallingUid(), target != null); final long identity = Binder.clearCallingIdentity(); try { if (enableQuietMode) { setQuietModeEnabled(userHandle, true /* enableQuietMode */, target); return true; } else { boolean needToShowConfirmCredential = mLockPatternUtils.isSecure(userHandle) && !StorageManager.isUserKeyUnlocked(userHandle); if (needToShowConfirmCredential) { showConfirmCredentialToDisableQuietMode(userHandle, target); return false; } else { setQuietModeEnabled(userHandle, false /* enableQuietMode */, target); return true; } } } finally { Binder.restoreCallingIdentity(identity); } }
Example #22
Source File: Convert.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
private static @NonNull RadioManager.BandDescriptor[] amfmConfigToBands(@Nullable AmFmRegionConfig config) { if (config == null) return new RadioManager.BandDescriptor[0]; int len = config.ranges.size(); List<RadioManager.BandDescriptor> bands = new ArrayList<>(len); // Just a dummy value. int region = RadioManager.REGION_ITU_1; for (AmFmBandRange range : config.ranges) { FrequencyBand bandType = Utils.getBand(range.lowerBound); if (bandType == FrequencyBand.UNKNOWN) { Slog.e(TAG, "Unknown frequency band at " + range.lowerBound + "kHz"); continue; } if (bandType == FrequencyBand.FM) { bands.add(new RadioManager.FmBandDescriptor(region, RadioManager.BAND_FM, range.lowerBound, range.upperBound, range.spacing, // TODO(b/69958777): stereo, rds, ta, af, ea true, true, true, true, true )); } else { // AM bands.add(new RadioManager.AmBandDescriptor(region, RadioManager.BAND_AM, range.lowerBound, range.upperBound, range.spacing, // TODO(b/69958777): stereo true )); } } return bands.toArray(new RadioManager.BandDescriptor[bands.size()]); }
Example #23
Source File: StorageManager.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** {@hide} */ public @Nullable VolumeInfo findEmulatedForPrivate(VolumeInfo privateVol) { if (privateVol != null) { return findVolumeById(privateVol.getId().replace("private", "emulated")); } else { return null; } }
Example #24
Source File: GetDefaultDownloadableSubscriptionListResult.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Construct a new {@link GetDefaultDownloadableSubscriptionListResult}. * * @param result Result of the operation. May be one of the predefined {@code RESULT_} constants * in EuiccService or any implementation-specific code starting with * {@link EuiccService#RESULT_FIRST_USER}. * @param subscriptions The available subscriptions. Should only be provided if the result is * {@link EuiccService#RESULT_OK}. */ public GetDefaultDownloadableSubscriptionListResult(int result, @Nullable DownloadableSubscription[] subscriptions) { this.result = result; if (this.result == EuiccService.RESULT_OK) { this.mSubscriptions = subscriptions; } else { if (subscriptions != null) { throw new IllegalArgumentException( "Error result with non-null subscriptions: " + result); } this.mSubscriptions = null; } }
Example #25
Source File: Binder.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Implemented to call the more convenient version * {@link #dump(FileDescriptor, PrintWriter, String[])}. */ public void dump(@NonNull FileDescriptor fd, @Nullable String[] args) { FileOutputStream fout = new FileOutputStream(fd); PrintWriter pw = new FastPrintWriter(fout); try { doDump(fd, pw, args); } finally { pw.flush(); } }
Example #26
Source File: ApplicationPackageManager.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
@VisibleForTesting protected @Nullable VolumeInfo getPackageCurrentVolume(ApplicationInfo app, StorageManager storage) { if (app.isInternal()) { return storage.findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL); } else if (app.isExternalAsec()) { return storage.getPrimaryPhysicalVolume(); } else { return storage.findVolumeByUuid(app.volumeUuid); } }
Example #27
Source File: ProgramList.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * @hide for framework use only */ public Filter(@Nullable Map<String, String> vendorFilter) { mIdentifierTypes = Collections.emptySet(); mIdentifiers = Collections.emptySet(); mIncludeCategories = false; mExcludeModifications = false; mVendorFilter = vendorFilter; }
Example #28
Source File: FontResourcesParser.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
public FontFileResourceEntry(@NonNull String fileName, int weight, int italic, @Nullable String variationSettings, int ttcIndex) { mFileName = fileName; mWeight = weight; mItalic = italic; mVariationSettings = variationSettings; mTtcIndex = ttcIndex; }
Example #29
Source File: FragmentHostCallback.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Starts a new {@link IntentSender} from the given fragment. * See {@link Activity#startIntentSender(IntentSender, Intent, int, int, int, Bundle)}. */ public void onStartIntentSenderFromFragment(Fragment fragment, IntentSender intent, int requestCode, @Nullable Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags, Bundle options) throws IntentSender.SendIntentException { if (requestCode != -1) { throw new IllegalStateException( "Starting intent sender with a requestCode requires a FragmentActivity host"); } mContext.startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, options); }
Example #30
Source File: TextClassification.java From android_9.0.0_r45 with Apache License 2.0 | 4 votes |
/** * Sets the classified text. */ @NonNull public Builder setText(@Nullable String text) { mText = text; return this; }