Class Util
- java.lang.Object
-
- com.google.android.exoplayer2.util.Util
-
@Deprecated public final class Util extends Object
Deprecated.com.google.android.exoplayer2 is deprecated. Please migrate to androidx.media3 (which contains the same ExoPlayer code). See the migration guide for more details, including a script to help with the migration.Miscellaneous utility methods.
-
-
Field Summary
Fields Modifier and Type Field Description static StringDEVICEDeprecated.LikeBuild.DEVICE, but in a place where it can be conveniently overridden for local testing.static StringDEVICE_DEBUG_INFODeprecated.A concise description of the device that it can be useful to log for debugging purposes.static byte[]EMPTY_BYTE_ARRAYDeprecated.An empty byte array.static StringMANUFACTURERDeprecated.LikeBuild.MANUFACTURER, but in a place where it can be conveniently overridden for local testing.static StringMODELDeprecated.LikeBuild.MODEL, but in a place where it can be conveniently overridden for local testing.static intSDK_INTDeprecated.LikeBuild.VERSION.SDK_INT, but in a place where it can be conveniently overridden for local testing.
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static longaddWithOverflowDefault(long x, long y, long overflowResult)Deprecated.Returns the sum of two arguments, or a third argument if the result overflows.static booleanareEqual(Object o1, Object o2)Deprecated.Tests two objects forObject.equals(Object)equality, handling the case where one or both may be null.static intbinarySearchCeil(int[] array, int value, boolean inclusive, boolean stayInBounds)Deprecated.Returns the index of the smallest element inarraythat is greater than (or optionally equal to) a specifiedvalue.static intbinarySearchCeil(long[] array, long value, boolean inclusive, boolean stayInBounds)Deprecated.Returns the index of the smallest element inarraythat is greater than (or optionally equal to) a specifiedvalue.static <T extends Comparable<? super T>>
intbinarySearchCeil(List<? extends Comparable<? super T>> list, T value, boolean inclusive, boolean stayInBounds)Deprecated.Returns the index of the smallest element inlistthat is greater than (or optionally equal to) a specified value.static intbinarySearchFloor(int[] array, int value, boolean inclusive, boolean stayInBounds)Deprecated.Returns the index of the largest element inarraythat is less than (or optionally equal to) a specifiedvalue.static intbinarySearchFloor(long[] array, long value, boolean inclusive, boolean stayInBounds)Deprecated.Returns the index of the largest element inarraythat is less than (or optionally equal to) a specifiedvalue.static intbinarySearchFloor(LongArray longArray, long value, boolean inclusive, boolean stayInBounds)Deprecated.Returns the index of the largest element inlongArraythat is less than (or optionally equal to) a specifiedvalue.static <T extends Comparable<? super T>>
intbinarySearchFloor(List<? extends Comparable<? super T>> list, T value, boolean inclusive, boolean stayInBounds)Deprecated.Returns the index of the largest element inlistthat is less than (or optionally equal to) a specifiedvalue.static <T> TcastNonNull(T value)Deprecated.Casts a nullable variable to a non-null variable without runtime null check.static <T> T[]castNonNullTypeArray(@NullableType T[] value)Deprecated.Casts a nullable type array to a non-null type array without runtime null check.static intceilDivide(int numerator, int denominator)Deprecated.Divides anumeratorby adenominator, returning the ceiled result.static longceilDivide(long numerator, long denominator)Deprecated.Divides anumeratorby adenominator, returning the ceiled result.static booleancheckCleartextTrafficPermitted(MediaItem... mediaItems)Deprecated.Returns whether it may be possible to load the URIs of the given media items based on the network security policy's cleartext traffic permissions.static voidcloseQuietly(Closeable closeable)Deprecated.Closes aCloseable, suppressing anyIOExceptionthat may occur.static intcompareLong(long left, long right)Deprecated.Compares two long values and returns the same value asLong.compare(long, long).static floatconstrainValue(float value, float min, float max)Deprecated.Constrains a value to the specified bounds.static intconstrainValue(int value, int min, int max)Deprecated.Constrains a value to the specified bounds.static longconstrainValue(long value, long min, long max)Deprecated.Constrains a value to the specified bounds.static booleancontains(@NullableType Object[] items, Object item)Deprecated.static intcrc32(byte[] bytes, int start, int end, int initialValue)Deprecated.Returns the result of updating a CRC-32 with the specified bytes in a "most significant bit first" order.static intcrc8(byte[] bytes, int start, int end, int initialValue)Deprecated.Returns the result of updating a CRC-8 with the specified bytes in a "most significant bit first" order.static HandlercreateHandler(Looper looper, @UnknownInitialization Handler.Callback callback)Deprecated.static HandlercreateHandlerForCurrentLooper()Deprecated.static HandlercreateHandlerForCurrentLooper(@UnknownInitialization Handler.Callback callback)Deprecated.static HandlercreateHandlerForCurrentOrMainLooper()Deprecated.static HandlercreateHandlerForCurrentOrMainLooper(@UnknownInitialization Handler.Callback callback)Deprecated.static FilecreateTempDirectory(Context context, String prefix)Deprecated.Creates an empty directory in the directory returned byContext.getCacheDir().static FilecreateTempFile(Context context, String prefix)Deprecated.Creates a new empty file in the directory returned byContext.getCacheDir().static longdurationUsToSampleCount(long durationUs, int sampleRate)Deprecated.Returns the number of samples required to representdurationUsof media atsampleRate, assuming all samples are equal duration except the last one which may be shorter.static StringescapeFileName(String fileName)Deprecated.Escapes a string so that it's safe for use as a file or directory name on at least FAT32 filesystems.static UrifixSmoothStreamingIsmManifestUri(Uri uri)Deprecated.If the provided URI is an ISM Presentation URI, returns the URI with "Manifest" appended to its path (i.e., the corresponding default manifest URI).static StringformatInvariant(String format, Object... args)Deprecated.Formats a string usingLocale.US.static StringfromUtf8Bytes(byte[] bytes)Deprecated.Returns a newStringconstructed by decoding UTF-8 encoded bytes.static StringfromUtf8Bytes(byte[] bytes, int offset, int length)Deprecated.Returns a newStringconstructed by decoding UTF-8 encoded bytes in a subarray.static intgenerateAudioSessionIdV21(Context context)Deprecated.Returns a newly generated audio session identifier, orAudioManager.ERRORif an error occurred in which case audio playback may fail.static StringgetAdaptiveMimeTypeForContentType(@com.google.android.exoplayer2.C.ContentType int contentType)Deprecated.Returns the MIME type corresponding to the given adaptiveC.ContentType, ornullif the content type is not adaptive.static @com.google.android.exoplayer2.C.AudioContentType intgetAudioContentTypeForStreamType(@com.google.android.exoplayer2.C.StreamType int streamType)Deprecated.Returns theC.AudioContentTypecorresponding to the specifiedC.StreamType.static intgetAudioTrackChannelConfig(int channelCount)Deprecated.Returns the audio track channel configuration for the given channel count, orAudioFormat.CHANNEL_INVALIDif output is not possible.static @com.google.android.exoplayer2.C.AudioUsage intgetAudioUsageForStreamType(@com.google.android.exoplayer2.C.StreamType int streamType)Deprecated.Returns theC.AudioUsagecorresponding to the specifiedC.StreamType.static Player.CommandsgetAvailableCommands(Player player, Player.Commands permanentAvailableCommands)Deprecated.Returns thePlayer.Commandsavailable in thePlayer.static intgetBigEndianInt(ByteBuffer buffer, int index)Deprecated.Absolute get method for reading an int value inByteOrder.BIG_ENDIANin aByteBuffer.static byte[]getBytesFromHexString(String hexString)Deprecated.Returns a byte array containing values parsed from the hex string provided.static intgetCodecCountOfType(String codecs, @com.google.android.exoplayer2.C.TrackType int trackType)Deprecated.Returns the number of codec strings incodecswhose type matchestrackType.static StringgetCodecsOfType(String codecs, @com.google.android.exoplayer2.C.TrackType int trackType)Deprecated.Returns a copy ofcodecswithout the codecs whose track type doesn't matchtrackType.static StringgetCommaDelimitedSimpleClassNames(Object[] objects)Deprecated.Returns a string with comma delimited simple names of each object's class.static StringgetCountryCode(Context context)Deprecated.Returns the upper-case ISO 3166-1 alpha-2 country code of the current registered operator's MCC (Mobile Country Code), or the country code of the default Locale if not available.static PointgetCurrentDisplayModeSize(Context context)Deprecated.Gets the size of the current mode of the default display, in pixels.static PointgetCurrentDisplayModeSize(Context context, Display display)Deprecated.Gets the size of the current mode of the specified display, in pixels.static LoopergetCurrentOrMainLooper()Deprecated.static UrigetDataUriForString(String mimeType, String data)Deprecated.Returns a data URI with the specified MIME type and data.static LocalegetDefaultDisplayLocale()Deprecated.static DrawablegetDrawable(Context context, Resources resources, int drawableRes)Deprecated.Returns aDrawablefor the given resource or throws aResources.NotFoundExceptionif not found.static UUIDgetDrmUuid(String drmScheme)Deprecated.Derives a DRMUUIDfromdrmScheme.static @com.google.android.exoplayer2.PlaybackException.ErrorCode intgetErrorCodeForMediaDrmErrorCode(int mediaDrmErrorCode)Deprecated.Returns aPlaybackException.ErrorCodevalue that corresponds to the providedMediaDrm.ErrorCodesvalue.static intgetErrorCodeFromPlatformDiagnosticsInfo(String diagnosticsInfo)Deprecated.Attempts to parse an error code from a diagnostic string found in framework media exceptions.static StringgetFormatSupportString(@com.google.android.exoplayer2.C.FormatSupport int formatSupport)Deprecated.Returns string representation of aC.FormatSupportflag.static intgetIntegerCodeForString(String string)Deprecated.Returns the integer equal to the big-endian concatenation of the characters instringas bytes.static StringgetLocaleLanguageTag(Locale locale)Deprecated.Returns the language tag for aLocale.static intgetMaxPendingFramesCountForMediaCodecDecoders(Context context, String codecName, boolean requestedHdrToneMapping)Deprecated.Returns the number of maximum pending output frames that are allowed on aMediaCodecdecoder.static longgetMediaDurationForPlayoutDuration(long playoutDuration, float speed)Deprecated.Returns the duration of media that will elapse inplayoutDuration.static longgetNowUnixTimeMs(long elapsedRealtimeEpochOffsetMs)Deprecated.Returns the current time in milliseconds since the epoch.static @com.google.android.exoplayer2.C.PcmEncoding intgetPcmEncoding(int bitDepth)Deprecated.Converts a sample bit depth to a corresponding PCM encoding constant.static FormatgetPcmFormat(@com.google.android.exoplayer2.C.PcmEncoding int pcmEncoding, int channels, int sampleRate)Deprecated.Gets a PCMFormatwith the specified parameters.static intgetPcmFrameSize(@com.google.android.exoplayer2.C.PcmEncoding int pcmEncoding, int channelCount)Deprecated.Returns the frame size for audio withchannelCountchannels in the specified encoding.static longgetPlayoutDurationForMediaDuration(long mediaDuration, float speed)Deprecated.Returns the playout duration ofmediaDurationof media.static @com.google.android.exoplayer2.C.StreamType intgetStreamTypeForAudioUsage(@com.google.android.exoplayer2.C.AudioUsage int usage)Deprecated.Returns theC.StreamTypecorresponding to the specifiedC.AudioUsage.static StringgetStringForTime(StringBuilder builder, Formatter formatter, long timeMs)Deprecated.Returns the specified millisecond time formatted as a string.static String[]getSystemLanguageCodes()Deprecated.Returns a non-empty array of normalized IETF BCP 47 language tags for the system languages ordered by preference.static StringgetTrackTypeString(@com.google.android.exoplayer2.C.TrackType int trackType)Deprecated.Returns a string representation of aC.TrackType.static StringgetUserAgent(Context context, String applicationName)Deprecated.Returns a user agent string based on the given application name and the library version.static byte[]getUtf8Bytes(String value)Deprecated.Returns a new byte array containing the code points of aStringencoded using UTF-8.static byte[]gzip(byte[] input)Deprecated.Compressesinputusing gzip and returns the result in a newly allocated byte array.static booleanhandlePauseButtonAction(Player player)Deprecated.Updates the player to handle an interaction with a pause button.static booleanhandlePlayButtonAction(Player player)Deprecated.Updates the player to handle an interaction with a play button.static booleanhandlePlayPauseButtonAction(Player player)Deprecated.Updates the player to handle an interaction with a play or pause button.static @com.google.android.exoplayer2.C.ContentType intinferContentType(Uri uri)Deprecated.Makes a best guess to infer theC.ContentTypefrom aUri.static @com.google.android.exoplayer2.C.ContentType intinferContentType(Uri uri, String overrideExtension)Deprecated.UseinferContentTypeForExtension(String)whenoverrideExtensionis non-empty, andinferContentType(Uri)otherwise.static @com.google.android.exoplayer2.C.ContentType intinferContentType(String fileName)Deprecated.UseUri.parse(String)andinferContentType(Uri)for full file paths orinferContentTypeForExtension(String)for extensions.static @com.google.android.exoplayer2.C.ContentType intinferContentTypeForExtension(String fileExtension)Deprecated.Makes a best guess to infer theC.ContentTypefrom a file extension.static @com.google.android.exoplayer2.C.ContentType intinferContentTypeForUriAndMimeType(Uri uri, String mimeType)Deprecated.Makes a best guess to infer theC.ContentTypefrom aUriand optional MIME type.static booleaninflate(ParsableByteArray input, ParsableByteArray output, Inflater inflater)Deprecated.Uncompresses the data ininput.static StringintToStringMaxRadix(int i)Deprecated.Returns a string representation of the integer using radix valueCharacter.MAX_RADIX.static booleanisAutomotive(Context context)Deprecated.Returns whether the app is running on an automotive device.static booleanisEncodingHighResolutionPcm(@com.google.android.exoplayer2.C.PcmEncoding int encoding)Deprecated.Returns whetherencodingis high resolution (> 16-bit) PCM.static booleanisEncodingLinearPcm(@com.google.android.exoplayer2.C.Encoding int encoding)Deprecated.Returns whetherencodingis one of the linear PCM encodings.static booleanisLinebreak(int c)Deprecated.Returns whether the given character is a carriage return ('\r') or a line feed ('\n').static booleanisLocalFileUri(Uri uri)Deprecated.Returns true if the URI is a path to a local file or a reference to a local file.static booleanisTv(Context context)Deprecated.Returns whether the app is running on a TV device.static intlinearSearch(int[] array, int value)Deprecated.Returns the index of the first occurrence ofvalueinarray, orC.INDEX_UNSETifvalueis not contained inarray.static intlinearSearch(long[] array, long value)Deprecated.Returns the index of the first occurrence ofvalueinarray, orC.INDEX_UNSETifvalueis not contained inarray.static longmaxValue(SparseLongArray sparseLongArray)Deprecated.Returns the maximum value in the givenSparseLongArray.static booleanmaybeRequestReadExternalStoragePermission(Activity activity, Uri... uris)Deprecated.Checks whether it's necessary to request theManifest.permission.READ_EXTERNAL_STORAGEpermission read the specifiedUris, requesting the permission if necessary.static booleanmaybeRequestReadExternalStoragePermission(Activity activity, MediaItem... mediaItems)Deprecated.Checks whether it's necessary to request theManifest.permission.READ_EXTERNAL_STORAGEpermission for the specifiedmedia items, requesting the permission if necessary.static longminValue(SparseLongArray sparseLongArray)Deprecated.Returns the minimum value in the givenSparseLongArray.static <T> voidmoveItems(List<T> items, int fromIndex, int toIndex, int newFromIndex)Deprecated.Moves the elements starting atfromIndextonewFromIndex.static longmsToUs(long timeMs)Deprecated.Converts a time in milliseconds to the corresponding time in microseconds, preservingC.TIME_UNSETvalues andC.TIME_END_OF_SOURCEvalues.static ExecutorServicenewSingleThreadExecutor(String threadName)Deprecated.Instantiates a new single threaded executor whose thread has the specified name.static ScheduledExecutorServicenewSingleThreadScheduledExecutor(String threadName)Deprecated.Instantiates a new single threaded scheduled executor whose thread has the specified name.static @PolyNull StringnormalizeLanguageCode(@PolyNull String language)Deprecated.Returns a normalized IETF BCP 47 language tag forlanguage.static <T> T[]nullSafeArrayAppend(T[] original, T newElement)Deprecated.Creates a new array containingoriginalwithnewElementappended.static <T> T[]nullSafeArrayConcatenation(T[] first, T[] second)Deprecated.Creates a new array containing the concatenation of two non-null type arrays.static <T> T[]nullSafeArrayCopy(T[] input, int length)Deprecated.Copies and optionally truncates an array.static <T> T[]nullSafeArrayCopyOfRange(T[] input, int from, int to)Deprecated.Copies a subset of an array.static <T> voidnullSafeListToArray(List<T> list, T[] array)Deprecated.Copies the contents oflistintoarray.static longparseXsDateTime(String value)Deprecated.Parses an xs:dateTime attribute value, returning the parsed timestamp in milliseconds since the epoch.static longparseXsDuration(String value)Deprecated.Parses an xs:duration attribute value, returning the parsed duration in milliseconds.static booleanpostOrRun(Handler handler, Runnable runnable)Deprecated.static <T> ListenableFuture<T>postOrRunWithCompletion(Handler handler, Runnable runnable, T successValue)Deprecated.static booleanreadBoolean(Parcel parcel)Deprecated.Reads an integer from aParceland interprets it as a boolean, with 0 mapping to false and all other values mapping to true.static voidrecursiveDelete(File fileOrDirectory)Deprecated.Recursively deletes a directory and its content.static IntentregisterReceiverNotExported(Context context, BroadcastReceiver receiver, IntentFilter filter)Deprecated.Registers aBroadcastReceiverthat's not intended to receive broadcasts from other apps.static <T> voidremoveRange(List<T> list, int fromIndex, int toIndex)Deprecated.Removes an indexed range from a List.static longsampleCountToDurationUs(long sampleCount, int sampleRate)Deprecated.Returns the total duration (in microseconds) ofsampleCountsamples of equal duration atsampleRate.static longscaleLargeTimestamp(long timestamp, long multiplier, long divisor)Deprecated.Scales a large timestamp.static long[]scaleLargeTimestamps(List<Long> timestamps, long multiplier, long divisor)Deprecated.AppliesscaleLargeTimestamp(long, long, long)to a list of unscaled timestamps.static voidscaleLargeTimestampsInPlace(long[] timestamps, long multiplier, long divisor)Deprecated.AppliesscaleLargeTimestamp(long, long, long)to an array of unscaled timestamps.static booleanshouldShowPlayButton(Player player)Deprecated.Returns whether a play button should be presented on a UI element for playback control.static voidsneakyThrow(Throwable t)Deprecated.A hacky method that always throwsteven iftis a checked exception, and is not declared to be thrown.static String[]split(String value, String regex)Deprecated.Splits a string usingvalue.split(regex, -1).static String[]splitAtFirst(String value, String regex)Deprecated.Splits the string at the first occurrence of the delimiterregex.static String[]splitCodecs(String codecs)Deprecated.Splits a codecs sequence string, as defined in RFC 6381, into individual codec strings.static ComponentNamestartForegroundService(Context context, Intent intent)Deprecated.CallsContext.startForegroundService(Intent)ifSDK_INTis 26 or higher, orContext.startService(Intent)otherwise.static longsubtractWithOverflowDefault(long x, long y, long overflowResult)Deprecated.Returns the difference between two arguments, or a third argument if the result overflows.static longsum(long... summands)Deprecated.Returns the sum of all summands of the given array.static booleantableExists(SQLiteDatabase database, String tableName)Deprecated.Returns whether the table exists in the database.static byte[]toByteArray(float value)Deprecated.Converts a float into an equivalent byte array.static byte[]toByteArray(int value)Deprecated.Converts an integer into an equivalent byte array.static byte[]toByteArray(int... values)Deprecated.Converts an array of integers into an equivalent byte array.static byte[]toByteArray(InputStream inputStream)Deprecated.Converts the entirety of anInputStreamto a byte array.static floattoFloat(byte[] bytes)Deprecated.Converts a byte array into a float.static StringtoHexString(byte[] bytes)Deprecated.Returns a string containing a lower-case hex representation of the bytes provided.static inttoInteger(byte[] bytes)Deprecated.Converts a byte array into an integer.static longtoLong(int mostSignificantBits, int leastSignificantBits)Deprecated.Returns the long that is composed of the bits of the 2 specified integers.static longtoUnsignedLong(int x)Deprecated.Converts an integer to a long by unsigned conversion.static <T,U>
ListenableFuture<T>transformFutureAsync(ListenableFuture<U> future, AsyncFunction<U,T> transformFunction)Deprecated.Asynchronously transforms the result of aListenableFuture.static StringunescapeFileName(String fileName)Deprecated.Unescapes an escaped file or directory name back to its original value.static longusToMs(long timeUs)Deprecated.Converts a time in microseconds to the corresponding time in milliseconds, preservingC.TIME_UNSETandC.TIME_END_OF_SOURCEvalues.static voidwriteBoolean(Parcel parcel, boolean value)Deprecated.Writes a boolean to aParcel.
-
-
-
Field Detail
-
SDK_INT
public static final int SDK_INT
Deprecated.LikeBuild.VERSION.SDK_INT, but in a place where it can be conveniently overridden for local testing.
-
DEVICE
public static final String DEVICE
Deprecated.LikeBuild.DEVICE, but in a place where it can be conveniently overridden for local testing.
-
MANUFACTURER
public static final String MANUFACTURER
Deprecated.LikeBuild.MANUFACTURER, but in a place where it can be conveniently overridden for local testing.
-
MODEL
public static final String MODEL
Deprecated.LikeBuild.MODEL, but in a place where it can be conveniently overridden for local testing.
-
DEVICE_DEBUG_INFO
public static final String DEVICE_DEBUG_INFO
Deprecated.A concise description of the device that it can be useful to log for debugging purposes.
-
EMPTY_BYTE_ARRAY
public static final byte[] EMPTY_BYTE_ARRAY
Deprecated.An empty byte array.
-
-
Method Detail
-
toByteArray
public static byte[] toByteArray(InputStream inputStream) throws IOException
Deprecated.Converts the entirety of anInputStreamto a byte array.- Parameters:
inputStream- theInputStreamto be read. The input stream is not closed by this method.- Returns:
- a byte array containing all of the inputStream's bytes.
- Throws:
IOException- if an error occurs reading from the stream.
-
toByteArray
public static byte[] toByteArray(int value)
Deprecated.Converts an integer into an equivalent byte array.
-
toByteArray
public static byte[] toByteArray(int... values)
Deprecated.Converts an array of integers into an equivalent byte array.Each integer is converted into 4 sequential bytes.
-
toByteArray
public static byte[] toByteArray(float value)
Deprecated.Converts a float into an equivalent byte array.
-
toFloat
public static float toFloat(byte[] bytes)
Deprecated.Converts a byte array into a float.
-
toInteger
public static int toInteger(byte[] bytes)
Deprecated.Converts a byte array into an integer.
-
registerReceiverNotExported
@Nullable public static Intent registerReceiverNotExported(Context context, @Nullable BroadcastReceiver receiver, IntentFilter filter)
Deprecated.Registers aBroadcastReceiverthat's not intended to receive broadcasts from other apps. This will be enforced by specifyingContext.RECEIVER_NOT_EXPORTEDifSDK_INTis 33 or above.Do not use this method if registering a receiver for a protected system broadcast.
- Parameters:
context- The context on whichContext.registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter)will be called.receiver- TheBroadcastReceiverto register. This value may be null.filter- Selects the Intent broadcasts to be received.- Returns:
- The first sticky intent found that matches
filter, or null if there are none.
-
startForegroundService
@Nullable public static ComponentName startForegroundService(Context context, Intent intent)
Deprecated.CallsContext.startForegroundService(Intent)ifSDK_INTis 26 or higher, orContext.startService(Intent)otherwise.- Parameters:
context- The context to call.intent- The intent to pass to the called method.- Returns:
- The result of the called method.
-
maybeRequestReadExternalStoragePermission
public static boolean maybeRequestReadExternalStoragePermission(Activity activity, Uri... uris)
Deprecated.Checks whether it's necessary to request theManifest.permission.READ_EXTERNAL_STORAGEpermission read the specifiedUris, requesting the permission if necessary.- Parameters:
activity- The host activity for checking and requesting the permission.uris-Uris that may requireManifest.permission.READ_EXTERNAL_STORAGEto read.- Returns:
- Whether a permission request was made.
-
maybeRequestReadExternalStoragePermission
public static boolean maybeRequestReadExternalStoragePermission(Activity activity, MediaItem... mediaItems)
Deprecated.Checks whether it's necessary to request theManifest.permission.READ_EXTERNAL_STORAGEpermission for the specifiedmedia items, requesting the permission if necessary.- Parameters:
activity- The host activity for checking and requesting the permission.mediaItems-Media itemss that may requireManifest.permission.READ_EXTERNAL_STORAGEto read.- Returns:
- Whether a permission request was made.
-
checkCleartextTrafficPermitted
public static boolean checkCleartextTrafficPermitted(MediaItem... mediaItems)
Deprecated.Returns whether it may be possible to load the URIs of the given media items based on the network security policy's cleartext traffic permissions.- Parameters:
mediaItems- A list ofmedia items.- Returns:
- Whether it may be possible to load the URIs of the given media items.
-
isLocalFileUri
public static boolean isLocalFileUri(Uri uri)
Deprecated.Returns true if the URI is a path to a local file or a reference to a local file.- Parameters:
uri- The uri to test.
-
areEqual
public static boolean areEqual(@Nullable Object o1, @Nullable Object o2)Deprecated.Tests two objects forObject.equals(Object)equality, handling the case where one or both may be null.- Parameters:
o1- The first object.o2- The second object.- Returns:
o1 == null ? o2 == null : o1.equals(o2).
-
contains
public static boolean contains(@NullableType Object[] items, @Nullable Object item)
Deprecated.Tests whether anitemsarray contains an object equal toitem, according toObject.equals(Object).If
itemis null then true is returned if and only ifitemscontains null.- Parameters:
items- The array of items to search.item- The item to search for.- Returns:
- True if the array contains an object equal to the item being searched for.
-
removeRange
public static <T> void removeRange(List<T> list, int fromIndex, int toIndex)
Deprecated.Removes an indexed range from a List.Does nothing if the provided range is valid and
fromIndex == toIndex.- Parameters:
list- The List to remove the range from.fromIndex- The first index to be removed (inclusive).toIndex- The last index to be removed (exclusive).- Throws:
IllegalArgumentException- IffromIndex< 0,toIndex>list.size(), orfromIndex>toIndex.
-
castNonNull
@EnsuresNonNull("#1") public static <T> T castNonNull(@Nullable T value)Deprecated.Casts a nullable variable to a non-null variable without runtime null check.Use
Assertions.checkNotNull(Object)to throw if the value is null.
-
castNonNullTypeArray
@EnsuresNonNull("#1") public static <T> T[] castNonNullTypeArray(@NullableType T[] value)Deprecated.Casts a nullable type array to a non-null type array without runtime null check.
-
nullSafeArrayCopy
public static <T> T[] nullSafeArrayCopy(T[] input, int length)Deprecated.Copies and optionally truncates an array. Prevents null array elements created byArrays.copyOf(Object[], int)by ensuring the new length does not exceed the current length.- Parameters:
input- The input array.length- The output array length. Must be less or equal to the length of the input array.- Returns:
- The copied array.
-
nullSafeArrayCopyOfRange
public static <T> T[] nullSafeArrayCopyOfRange(T[] input, int from, int to)Deprecated.Copies a subset of an array.- Parameters:
input- The input array.from- The start the range to be copied, inclusiveto- The end of the range to be copied, exclusive.- Returns:
- The copied array.
-
nullSafeArrayAppend
public static <T> T[] nullSafeArrayAppend(T[] original, T newElement)Deprecated.Creates a new array containingoriginalwithnewElementappended.- Parameters:
original- The input array.newElement- The element to append.- Returns:
- The new array.
-
nullSafeArrayConcatenation
public static <T> T[] nullSafeArrayConcatenation(T[] first, T[] second)Deprecated.Creates a new array containing the concatenation of two non-null type arrays.- Parameters:
first- The first array.second- The second array.- Returns:
- The concatenated result.
-
nullSafeListToArray
public static <T> void nullSafeListToArray(List<T> list, T[] array)
Deprecated.Copies the contents oflistintoarray.list.size()must be the same asarray.lengthto ensure the contents can be copied intoarraywithout leaving any nulls at the end.- Parameters:
list- The list to copy items from.array- The array to copy items to.
-
createHandlerForCurrentLooper
public static Handler createHandlerForCurrentLooper()
Deprecated.- Throws:
IllegalStateException- If the current thread doesn't have aLooper.
-
createHandlerForCurrentLooper
public static Handler createHandlerForCurrentLooper(@Nullable @UnknownInitialization Handler.Callback callback)
Deprecated.Creates aHandlerwith the specifiedHandler.Callbackon the currentLooperthread.The method accepts partially initialized objects as callback under the assumption that the Handler won't be used to send messages until the callback is fully initialized.
- Parameters:
callback- AHandler.Callback. May be a partially initialized class, or null if no callback is required.- Returns:
- A
Handlerwith the specified callback on the currentLooperthread. - Throws:
IllegalStateException- If the current thread doesn't have aLooper.
-
createHandlerForCurrentOrMainLooper
public static Handler createHandlerForCurrentOrMainLooper()
Deprecated.
-
createHandlerForCurrentOrMainLooper
public static Handler createHandlerForCurrentOrMainLooper(@Nullable @UnknownInitialization Handler.Callback callback)
Deprecated.Creates aHandlerwith the specifiedHandler.Callbackon the currentLooperthread.The method accepts partially initialized objects as callback under the assumption that the Handler won't be used to send messages until the callback is fully initialized.
If the current thread doesn't have a
Looper, the application's main threadLooperis used.- Parameters:
callback- AHandler.Callback. May be a partially initialized class, or null if no callback is required.- Returns:
- A
Handlerwith the specified callback on the currentLooperthread.
-
createHandler
public static Handler createHandler(Looper looper, @Nullable @UnknownInitialization Handler.Callback callback)
Deprecated.Creates aHandlerwith the specifiedHandler.Callbackon the specifiedLooperthread.The method accepts partially initialized objects as callback under the assumption that the Handler won't be used to send messages until the callback is fully initialized.
- Parameters:
looper- ALooperto run the callback on.callback- AHandler.Callback. May be a partially initialized class, or null if no callback is required.- Returns:
- A
Handlerwith the specified callback on the currentLooperthread.
-
postOrRunWithCompletion
public static <T> ListenableFuture<T> postOrRunWithCompletion(Handler handler, Runnable runnable, T successValue)
Deprecated.Posts theRunnableif the calling thread differs with theLooperof theHandler. Otherwise, runs theRunnabledirectly. Also returns aListenableFuturefor when theRunnablehas run.- Type Parameters:
T- The type ofsuccessValue.- Parameters:
handler- The handler to which theRunnablewill be posted.runnable- The runnable to either post or run.successValue- The value to set in theListenableFutureonce the runnable completes.- Returns:
- A
ListenableFuturefor when theRunnablehas run.
-
transformFutureAsync
public static <T,U> ListenableFuture<T> transformFutureAsync(ListenableFuture<U> future, AsyncFunction<U,T> transformFunction)
Deprecated.Asynchronously transforms the result of aListenableFuture.The transformation function is called using a direct executor.
The returned Future attempts to keep its cancellation state in sync with that of the input future and that of the future returned by the transform function. That is, if the returned Future is cancelled, it will attempt to cancel the other two, and if either of the other two is cancelled, the returned Future will also be cancelled. All forwarded cancellations will not attempt to interrupt.
- Type Parameters:
T- The result type of the input future.U- The result type of the transformation function.- Parameters:
future- The inputListenableFuture.transformFunction- The function transforming the result of the input future.- Returns:
- A
ListenableFuturefor the transformed result.
-
getCurrentOrMainLooper
public static Looper getCurrentOrMainLooper()
Deprecated.
-
newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor(String threadName)
Deprecated.Instantiates a new single threaded executor whose thread has the specified name.- Parameters:
threadName- The name of the thread.- Returns:
- The executor.
-
newSingleThreadScheduledExecutor
public static ScheduledExecutorService newSingleThreadScheduledExecutor(String threadName)
Deprecated.Instantiates a new single threaded scheduled executor whose thread has the specified name.- Parameters:
threadName- The name of the thread.- Returns:
- The executor.
-
closeQuietly
public static void closeQuietly(@Nullable Closeable closeable)Deprecated.Closes aCloseable, suppressing anyIOExceptionthat may occur. BothOutputStreamandInputStreamareCloseable.- Parameters:
closeable- TheCloseableto close.
-
readBoolean
public static boolean readBoolean(Parcel parcel)
Deprecated.Reads an integer from aParceland interprets it as a boolean, with 0 mapping to false and all other values mapping to true.- Parameters:
parcel- TheParcelto read from.- Returns:
- The read value.
-
writeBoolean
public static void writeBoolean(Parcel parcel, boolean value)
Deprecated.Writes a boolean to aParcel. The boolean is written as an integer with value 1 (true) or 0 (false).- Parameters:
parcel- TheParcelto write to.value- The value to write.
-
getLocaleLanguageTag
public static String getLocaleLanguageTag(Locale locale)
Deprecated.Returns the language tag for aLocale.For API levels ≥ 21, this tag is IETF BCP 47 compliant. Use
normalizeLanguageCode(String)to retrieve a normalized IETF BCP 47 language tag for all API levels if needed.- Parameters:
locale- ALocale.- Returns:
- The language tag.
-
normalizeLanguageCode
public static @PolyNull String normalizeLanguageCode(@PolyNull String language)
Deprecated.Returns a normalized IETF BCP 47 language tag forlanguage.- Parameters:
language- A case-insensitive language code supported byLocale.forLanguageTag(String).- Returns:
- The all-lowercase normalized code, or null if the input was null, or
language.toLowerCase()if the language could not be normalized.
-
fromUtf8Bytes
public static String fromUtf8Bytes(byte[] bytes)
Deprecated.Returns a newStringconstructed by decoding UTF-8 encoded bytes.- Parameters:
bytes- The UTF-8 encoded bytes to decode.- Returns:
- The string.
-
fromUtf8Bytes
public static String fromUtf8Bytes(byte[] bytes, int offset, int length)
Deprecated.Returns a newStringconstructed by decoding UTF-8 encoded bytes in a subarray.- Parameters:
bytes- The UTF-8 encoded bytes to decode.offset- The index of the first byte to decode.length- The number of bytes to decode.- Returns:
- The string.
-
getUtf8Bytes
public static byte[] getUtf8Bytes(String value)
Deprecated.Returns a new byte array containing the code points of aStringencoded using UTF-8.- Parameters:
value- TheStringwhose bytes should be obtained.- Returns:
- The code points encoding using UTF-8.
-
split
public static String[] split(String value, String regex)
Deprecated.Splits a string usingvalue.split(regex, -1). Note: this is is similar toString.split(String)but empty matches at the end of the string will not be omitted from the returned array.- Parameters:
value- The string to split.regex- A delimiting regular expression.- Returns:
- The array of strings resulting from splitting the string.
-
splitAtFirst
public static String[] splitAtFirst(String value, String regex)
Deprecated.Splits the string at the first occurrence of the delimiterregex. If the delimiter does not match, returns an array with one element which is the input string. If the delimiter does match, returns an array with the portion of the string before the delimiter and the rest of the string.- Parameters:
value- The string.regex- A delimiting regular expression.- Returns:
- The string split by the first occurrence of the delimiter.
-
isLinebreak
public static boolean isLinebreak(int c)
Deprecated.Returns whether the given character is a carriage return ('\r') or a line feed ('\n').- Parameters:
c- The character.- Returns:
- Whether the given character is a linebreak.
-
formatInvariant
public static String formatInvariant(String format, Object... args)
Deprecated.Formats a string usingLocale.US.- See Also:
String.format(String, Object...)
-
ceilDivide
public static int ceilDivide(int numerator, int denominator)Deprecated.Divides anumeratorby adenominator, returning the ceiled result.- Parameters:
numerator- The numerator to divide.denominator- The denominator to divide by.- Returns:
- The ceiled result of the division.
-
ceilDivide
public static long ceilDivide(long numerator, long denominator)Deprecated.Divides anumeratorby adenominator, returning the ceiled result.- Parameters:
numerator- The numerator to divide.denominator- The denominator to divide by.- Returns:
- The ceiled result of the division.
-
constrainValue
public static int constrainValue(int value, int min, int max)Deprecated.Constrains a value to the specified bounds.- Parameters:
value- The value to constrain.min- The lower bound.max- The upper bound.- Returns:
- The constrained value
Math.max(min, Math.min(value, max)).
-
constrainValue
public static long constrainValue(long value, long min, long max)Deprecated.Constrains a value to the specified bounds.- Parameters:
value- The value to constrain.min- The lower bound.max- The upper bound.- Returns:
- The constrained value
Math.max(min, Math.min(value, max)).
-
constrainValue
public static float constrainValue(float value, float min, float max)Deprecated.Constrains a value to the specified bounds.- Parameters:
value- The value to constrain.min- The lower bound.max- The upper bound.- Returns:
- The constrained value
Math.max(min, Math.min(value, max)).
-
addWithOverflowDefault
public static long addWithOverflowDefault(long x, long y, long overflowResult)Deprecated.Returns the sum of two arguments, or a third argument if the result overflows.- Parameters:
x- The first value.y- The second value.overflowResult- The return value ifx + yoverflows.- Returns:
x + y, oroverflowResultif the result overflows.
-
subtractWithOverflowDefault
public static long subtractWithOverflowDefault(long x, long y, long overflowResult)Deprecated.Returns the difference between two arguments, or a third argument if the result overflows.- Parameters:
x- The first value.y- The second value.overflowResult- The return value ifx - yoverflows.- Returns:
x - y, oroverflowResultif the result overflows.
-
linearSearch
public static int linearSearch(int[] array, int value)Deprecated.Returns the index of the first occurrence ofvalueinarray, orC.INDEX_UNSETifvalueis not contained inarray.- Parameters:
array- The array to search.value- The value to search for.- Returns:
- The index of the first occurrence of value in
array, orC.INDEX_UNSETifvalueis not contained inarray.
-
linearSearch
public static int linearSearch(long[] array, long value)Deprecated.Returns the index of the first occurrence ofvalueinarray, orC.INDEX_UNSETifvalueis not contained inarray.- Parameters:
array- The array to search.value- The value to search for.- Returns:
- The index of the first occurrence of value in
array, orC.INDEX_UNSETifvalueis not contained inarray.
-
binarySearchFloor
public static int binarySearchFloor(int[] array, int value, boolean inclusive, boolean stayInBounds)Deprecated.Returns the index of the largest element inarraythat is less than (or optionally equal to) a specifiedvalue.The search is performed using a binary search algorithm, so the array must be sorted. If the array contains multiple elements equal to
valueandinclusiveis true, the index of the first one will be returned.- Parameters:
array- The array to search.value- The value being searched for.inclusive- If the value is present in the array, whether to return the corresponding index. If false then the returned index corresponds to the largest element strictly less than the value.stayInBounds- If true, then 0 will be returned in the case that the value is smaller than the smallest element in the array. If false then -1 will be returned.- Returns:
- The index of the largest element in
arraythat is less than (or optionally equal to)value.
-
binarySearchFloor
public static int binarySearchFloor(long[] array, long value, boolean inclusive, boolean stayInBounds)Deprecated.Returns the index of the largest element inarraythat is less than (or optionally equal to) a specifiedvalue.The search is performed using a binary search algorithm, so the array must be sorted. If the array contains multiple elements equal to
valueandinclusiveis true, the index of the first one will be returned.- Parameters:
array- The array to search.value- The value being searched for.inclusive- If the value is present in the array, whether to return the corresponding index. If false then the returned index corresponds to the largest element strictly less than the value.stayInBounds- If true, then 0 will be returned in the case that the value is smaller than the smallest element in the array. If false then -1 will be returned.- Returns:
- The index of the largest element in
arraythat is less than (or optionally equal to)value.
-
binarySearchFloor
public static <T extends Comparable<? super T>> int binarySearchFloor(List<? extends Comparable<? super T>> list, T value, boolean inclusive, boolean stayInBounds)
Deprecated.Returns the index of the largest element inlistthat is less than (or optionally equal to) a specifiedvalue.The search is performed using a binary search algorithm, so the list must be sorted. If the list contains multiple elements equal to
valueandinclusiveis true, the index of the first one will be returned.- Type Parameters:
T- The type of values being searched.- Parameters:
list- The list to search.value- The value being searched for.inclusive- If the value is present in the list, whether to return the corresponding index. If false then the returned index corresponds to the largest element strictly less than the value.stayInBounds- If true, then 0 will be returned in the case that the value is smaller than the smallest element in the list. If false then -1 will be returned.- Returns:
- The index of the largest element in
listthat is less than (or optionally equal to)value.
-
binarySearchFloor
public static int binarySearchFloor(LongArray longArray, long value, boolean inclusive, boolean stayInBounds)
Deprecated.Returns the index of the largest element inlongArraythat is less than (or optionally equal to) a specifiedvalue.The search is performed using a binary search algorithm, so the array must be sorted. If the array contains multiple elements equal to
valueandinclusiveis true, the index of the first one will be returned.- Parameters:
longArray- The array to search.value- The value being searched for.inclusive- If the value is present in the array, whether to return the corresponding index. If false then the returned index corresponds to the largest element strictly less than the value.stayInBounds- If true, then 0 will be returned in the case that the value is smaller than the smallest element in the array. If false then -1 will be returned.- Returns:
- The index of the largest element in
arraythat is less than (or optionally equal to)value.
-
binarySearchCeil
public static int binarySearchCeil(int[] array, int value, boolean inclusive, boolean stayInBounds)Deprecated.Returns the index of the smallest element inarraythat is greater than (or optionally equal to) a specifiedvalue.The search is performed using a binary search algorithm, so the array must be sorted. If the array contains multiple elements equal to
valueandinclusiveis true, the index of the last one will be returned.- Parameters:
array- The array to search.value- The value being searched for.inclusive- If the value is present in the array, whether to return the corresponding index. If false then the returned index corresponds to the smallest element strictly greater than the value.stayInBounds- If true, then(a.length - 1)will be returned in the case that the value is greater than the largest element in the array. If false thena.lengthwill be returned.- Returns:
- The index of the smallest element in
arraythat is greater than (or optionally equal to)value.
-
binarySearchCeil
public static int binarySearchCeil(long[] array, long value, boolean inclusive, boolean stayInBounds)Deprecated.Returns the index of the smallest element inarraythat is greater than (or optionally equal to) a specifiedvalue.The search is performed using a binary search algorithm, so the array must be sorted. If the array contains multiple elements equal to
valueandinclusiveis true, the index of the last one will be returned.- Parameters:
array- The array to search.value- The value being searched for.inclusive- If the value is present in the array, whether to return the corresponding index. If false then the returned index corresponds to the smallest element strictly greater than the value.stayInBounds- If true, then(a.length - 1)will be returned in the case that the value is greater than the largest element in the array. If false thena.lengthwill be returned.- Returns:
- The index of the smallest element in
arraythat is greater than (or optionally equal to)value.
-
binarySearchCeil
public static <T extends Comparable<? super T>> int binarySearchCeil(List<? extends Comparable<? super T>> list, T value, boolean inclusive, boolean stayInBounds)
Deprecated.Returns the index of the smallest element inlistthat is greater than (or optionally equal to) a specified value.The search is performed using a binary search algorithm, so the list must be sorted. If the list contains multiple elements equal to
valueandinclusiveis true, the index of the last one will be returned.- Type Parameters:
T- The type of values being searched.- Parameters:
list- The list to search.value- The value being searched for.inclusive- If the value is present in the list, whether to return the corresponding index. If false then the returned index corresponds to the smallest element strictly greater than the value.stayInBounds- If true, then(list.size() - 1)will be returned in the case that the value is greater than the largest element in the list. If false thenlist.size()will be returned.- Returns:
- The index of the smallest element in
listthat is greater than (or optionally equal to)value.
-
compareLong
public static int compareLong(long left, long right)Deprecated.Compares two long values and returns the same value asLong.compare(long, long).- Parameters:
left- The left operand.right- The right operand.- Returns:
- 0, if left == right, a negative value if left < right, or a positive value if left > right.
-
minValue
@RequiresApi(18) public static long minValue(SparseLongArray sparseLongArray)
Deprecated.Returns the minimum value in the givenSparseLongArray.- Parameters:
sparseLongArray- TheSparseLongArray.- Returns:
- The minimum value.
- Throws:
NoSuchElementException- If the array is empty.
-
maxValue
@RequiresApi(18) public static long maxValue(SparseLongArray sparseLongArray)
Deprecated.Returns the maximum value in the givenSparseLongArray.- Parameters:
sparseLongArray- TheSparseLongArray.- Returns:
- The maximum value.
- Throws:
NoSuchElementException- If the array is empty.
-
usToMs
public static long usToMs(long timeUs)
Deprecated.Converts a time in microseconds to the corresponding time in milliseconds, preservingC.TIME_UNSETandC.TIME_END_OF_SOURCEvalues.- Parameters:
timeUs- The time in microseconds.- Returns:
- The corresponding time in milliseconds.
-
msToUs
public static long msToUs(long timeMs)
Deprecated.Converts a time in milliseconds to the corresponding time in microseconds, preservingC.TIME_UNSETvalues andC.TIME_END_OF_SOURCEvalues.- Parameters:
timeMs- The time in milliseconds.- Returns:
- The corresponding time in microseconds.
-
sampleCountToDurationUs
public static long sampleCountToDurationUs(long sampleCount, int sampleRate)Deprecated.Returns the total duration (in microseconds) ofsampleCountsamples of equal duration atsampleRate.If
sampleRateis less thanC.MICROS_PER_SECOND, the duration produced by this method can be reversed to the original sample count usingdurationUsToSampleCount(long, int).- Parameters:
sampleCount- The number of samples.sampleRate- The sample rate, in samples per second.- Returns:
- The total duration, in microseconds, of
sampleCountsamples.
-
durationUsToSampleCount
public static long durationUsToSampleCount(long durationUs, int sampleRate)Deprecated.Returns the number of samples required to representdurationUsof media atsampleRate, assuming all samples are equal duration except the last one which may be shorter.The result of this method cannot be generally reversed to the original duration with
sampleCountToDurationUs(long, int), due to information lost when rounding to a whole number of samples.- Parameters:
durationUs- The duration in microseconds.sampleRate- The sample rate in samples per second.- Returns:
- The number of samples required to represent
durationUs.
-
parseXsDuration
public static long parseXsDuration(String value)
Deprecated.Parses an xs:duration attribute value, returning the parsed duration in milliseconds.- Parameters:
value- The attribute value to decode.- Returns:
- The parsed duration in milliseconds.
-
parseXsDateTime
public static long parseXsDateTime(String value) throws ParserException
Deprecated.Parses an xs:dateTime attribute value, returning the parsed timestamp in milliseconds since the epoch.- Parameters:
value- The attribute value to decode.- Returns:
- The parsed timestamp in milliseconds since the epoch.
- Throws:
ParserException- if an error occurs parsing the dateTime attribute value.
-
scaleLargeTimestamp
public static long scaleLargeTimestamp(long timestamp, long multiplier, long divisor)Deprecated.Scales a large timestamp.Logically, scaling consists of a multiplication followed by a division. The actual operations performed are designed to minimize the probability of overflow.
- Parameters:
timestamp- The timestamp to scale.multiplier- The multiplier.divisor- The divisor.- Returns:
- The scaled timestamp.
-
scaleLargeTimestamps
public static long[] scaleLargeTimestamps(List<Long> timestamps, long multiplier, long divisor)
Deprecated.AppliesscaleLargeTimestamp(long, long, long)to a list of unscaled timestamps.- Parameters:
timestamps- The timestamps to scale.multiplier- The multiplier.divisor- The divisor.- Returns:
- The scaled timestamps.
-
scaleLargeTimestampsInPlace
public static void scaleLargeTimestampsInPlace(long[] timestamps, long multiplier, long divisor)Deprecated.AppliesscaleLargeTimestamp(long, long, long)to an array of unscaled timestamps.- Parameters:
timestamps- The timestamps to scale.multiplier- The multiplier.divisor- The divisor.
-
getMediaDurationForPlayoutDuration
public static long getMediaDurationForPlayoutDuration(long playoutDuration, float speed)Deprecated.Returns the duration of media that will elapse inplayoutDuration.- Parameters:
playoutDuration- The duration to scale.speed- The factor by which playback is sped up.- Returns:
- The scaled duration, in the same units as
playoutDuration.
-
getPlayoutDurationForMediaDuration
public static long getPlayoutDurationForMediaDuration(long mediaDuration, float speed)Deprecated.Returns the playout duration ofmediaDurationof media.- Parameters:
mediaDuration- The duration to scale.speed- The factor by which playback is sped up.- Returns:
- The scaled duration, in the same units as
mediaDuration.
-
getIntegerCodeForString
public static int getIntegerCodeForString(String string)
Deprecated.Returns the integer equal to the big-endian concatenation of the characters instringas bytes. The string must be no more than four characters long.- Parameters:
string- A string no more than four characters long.
-
toUnsignedLong
public static long toUnsignedLong(int x)
Deprecated.Converts an integer to a long by unsigned conversion.This method is equivalent to
Integer.toUnsignedLong(int)for API 26+.
-
toLong
public static long toLong(int mostSignificantBits, int leastSignificantBits)Deprecated.Returns the long that is composed of the bits of the 2 specified integers.- Parameters:
mostSignificantBits- The 32 most significant bits of the long to return.leastSignificantBits- The 32 least significant bits of the long to return.- Returns:
- a long where its 32 most significant bits are
mostSignificantBitsbits and its 32 least significant bits areleastSignificantBits.
-
getBytesFromHexString
public static byte[] getBytesFromHexString(String hexString)
Deprecated.Returns a byte array containing values parsed from the hex string provided.- Parameters:
hexString- The hex string to convert to bytes.- Returns:
- A byte array containing values parsed from the hex string provided.
-
toHexString
public static String toHexString(byte[] bytes)
Deprecated.Returns a string containing a lower-case hex representation of the bytes provided.- Parameters:
bytes- The byte data to convert to hex.- Returns:
- A String containing the hex representation of
bytes.
-
getCommaDelimitedSimpleClassNames
public static String getCommaDelimitedSimpleClassNames(Object[] objects)
Deprecated.Returns a string with comma delimited simple names of each object's class.- Parameters:
objects- The objects whose simple class names should be comma delimited and returned.- Returns:
- A string with comma delimited simple names of each object's class.
-
getUserAgent
public static String getUserAgent(Context context, String applicationName)
Deprecated.Returns a user agent string based on the given application name and the library version.- Parameters:
context- A valid context of the calling application.applicationName- String that will be prefix'ed to the generated user agent.- Returns:
- A user agent string generated using the applicationName and the library version.
-
getCodecCountOfType
public static int getCodecCountOfType(@Nullable String codecs, @com.google.android.exoplayer2.C.TrackType int trackType)Deprecated.Returns the number of codec strings incodecswhose type matchestrackType.
-
getCodecsOfType
@Nullable public static String getCodecsOfType(@Nullable String codecs, @com.google.android.exoplayer2.C.TrackType int trackType)
Deprecated.Returns a copy ofcodecswithout the codecs whose track type doesn't matchtrackType.- Parameters:
codecs- A codec sequence string, as defined in RFC 6381.trackType- Thetrack type.- Returns:
- A copy of
codecswithout the codecs whose track type doesn't matchtrackType. If this ends up empty, orcodecsis null, returns null.
-
splitCodecs
public static String[] splitCodecs(@Nullable String codecs)
Deprecated.Splits a codecs sequence string, as defined in RFC 6381, into individual codec strings.- Parameters:
codecs- A codec sequence string, as defined in RFC 6381.- Returns:
- The split codecs, or an array of length zero if the input was empty or null.
-
getPcmFormat
public static Format getPcmFormat(@com.google.android.exoplayer2.C.PcmEncoding int pcmEncoding, int channels, int sampleRate)
Deprecated.Gets a PCMFormatwith the specified parameters.- Parameters:
pcmEncoding- TheC.PcmEncoding.channels- The number of channels, orFormat.NO_VALUEif unknown.sampleRate- The sample rate in Hz, orFormat.NO_VALUEif unknown.- Returns:
- The PCM format.
-
getPcmEncoding
public static @com.google.android.exoplayer2.C.PcmEncoding int getPcmEncoding(int bitDepth)
Deprecated.Converts a sample bit depth to a corresponding PCM encoding constant.- Parameters:
bitDepth- The bit depth. Supported values are 8, 16, 24 and 32.- Returns:
- The corresponding encoding. One of
C.ENCODING_PCM_8BIT,C.ENCODING_PCM_16BIT,C.ENCODING_PCM_24BITandC.ENCODING_PCM_32BIT. If the bit depth is unsupported thenC.ENCODING_INVALIDis returned.
-
isEncodingLinearPcm
public static boolean isEncodingLinearPcm(@com.google.android.exoplayer2.C.Encoding int encoding)
Deprecated.Returns whetherencodingis one of the linear PCM encodings.- Parameters:
encoding- The encoding of the audio data.- Returns:
- Whether the encoding is one of the PCM encodings.
-
isEncodingHighResolutionPcm
public static boolean isEncodingHighResolutionPcm(@com.google.android.exoplayer2.C.PcmEncoding int encoding)
Deprecated.Returns whetherencodingis high resolution (> 16-bit) PCM.- Parameters:
encoding- The encoding of the audio data.- Returns:
- Whether the encoding is high resolution PCM.
-
getAudioTrackChannelConfig
public static int getAudioTrackChannelConfig(int channelCount)
Deprecated.Returns the audio track channel configuration for the given channel count, orAudioFormat.CHANNEL_INVALIDif output is not possible.- Parameters:
channelCount- The number of channels in the input audio.- Returns:
- The channel configuration or
AudioFormat.CHANNEL_INVALIDif output is not possible.
-
getPcmFrameSize
public static int getPcmFrameSize(@com.google.android.exoplayer2.C.PcmEncoding int pcmEncoding, int channelCount)Deprecated.Returns the frame size for audio withchannelCountchannels in the specified encoding.- Parameters:
pcmEncoding- The encoding of the audio data.channelCount- The channel count.- Returns:
- The size of one audio frame in bytes.
-
getAudioUsageForStreamType
@AudioUsage public static @com.google.android.exoplayer2.C.AudioUsage int getAudioUsageForStreamType(@StreamType @com.google.android.exoplayer2.C.StreamType int streamType)
Deprecated.Returns theC.AudioUsagecorresponding to the specifiedC.StreamType.
-
getAudioContentTypeForStreamType
@AudioContentType public static @com.google.android.exoplayer2.C.AudioContentType int getAudioContentTypeForStreamType(@StreamType @com.google.android.exoplayer2.C.StreamType int streamType)
Deprecated.Returns theC.AudioContentTypecorresponding to the specifiedC.StreamType.
-
getStreamTypeForAudioUsage
@StreamType public static @com.google.android.exoplayer2.C.StreamType int getStreamTypeForAudioUsage(@AudioUsage @com.google.android.exoplayer2.C.AudioUsage int usage)
Deprecated.Returns theC.StreamTypecorresponding to the specifiedC.AudioUsage.
-
generateAudioSessionIdV21
@RequiresApi(21) public static int generateAudioSessionIdV21(Context context)
Deprecated.Returns a newly generated audio session identifier, orAudioManager.ERRORif an error occurred in which case audio playback may fail.- See Also:
AudioManager.generateAudioSessionId()
-
getDrmUuid
@Nullable public static UUID getDrmUuid(String drmScheme)
Deprecated.Derives a DRMUUIDfromdrmScheme.- Parameters:
drmScheme- A UUID string, or"widevine","playready"or"clearkey".- Returns:
- The derived
UUID, ornullif one could not be derived.
-
getErrorCodeForMediaDrmErrorCode
@ErrorCode public static @com.google.android.exoplayer2.PlaybackException.ErrorCode int getErrorCodeForMediaDrmErrorCode(int mediaDrmErrorCode)
Deprecated.Returns aPlaybackException.ErrorCodevalue that corresponds to the providedMediaDrm.ErrorCodesvalue. ReturnsPlaybackException.ERROR_CODE_DRM_SYSTEM_ERRORif the provided error code isn't recognised.
-
inferContentType
@Deprecated @ContentType public static @com.google.android.exoplayer2.C.ContentType int inferContentType(Uri uri, @Nullable String overrideExtension)
Deprecated.UseinferContentTypeForExtension(String)whenoverrideExtensionis non-empty, andinferContentType(Uri)otherwise.
-
inferContentType
@ContentType public static @com.google.android.exoplayer2.C.ContentType int inferContentType(Uri uri)
Deprecated.Makes a best guess to infer theC.ContentTypefrom aUri.- Parameters:
uri- TheUri.- Returns:
- The content type.
-
inferContentType
@Deprecated @ContentType public static @com.google.android.exoplayer2.C.ContentType int inferContentType(String fileName)
Deprecated.UseUri.parse(String)andinferContentType(Uri)for full file paths orinferContentTypeForExtension(String)for extensions.
-
inferContentTypeForExtension
@ContentType public static @com.google.android.exoplayer2.C.ContentType int inferContentTypeForExtension(String fileExtension)
Deprecated.Makes a best guess to infer theC.ContentTypefrom a file extension.- Parameters:
fileExtension- The extension of the file (excluding the '.').- Returns:
- The content type.
-
inferContentTypeForUriAndMimeType
@ContentType public static @com.google.android.exoplayer2.C.ContentType int inferContentTypeForUriAndMimeType(Uri uri, @Nullable String mimeType)
Deprecated.Makes a best guess to infer theC.ContentTypefrom aUriand optional MIME type.- Parameters:
uri- TheUri.mimeType- If MIME type, ornull.- Returns:
- The content type.
-
getAdaptiveMimeTypeForContentType
@Nullable public static String getAdaptiveMimeTypeForContentType(@ContentType @com.google.android.exoplayer2.C.ContentType int contentType)
Deprecated.Returns the MIME type corresponding to the given adaptiveC.ContentType, ornullif the content type is not adaptive.
-
fixSmoothStreamingIsmManifestUri
public static Uri fixSmoothStreamingIsmManifestUri(Uri uri)
Deprecated.If the provided URI is an ISM Presentation URI, returns the URI with "Manifest" appended to its path (i.e., the corresponding default manifest URI). Else returns the provided URI without modification. See [MS-SSTR] v20180912, section 2.2.1.- Parameters:
uri- The original URI.- Returns:
- The fixed URI.
-
getStringForTime
public static String getStringForTime(StringBuilder builder, Formatter formatter, long timeMs)
Deprecated.Returns the specified millisecond time formatted as a string.- Parameters:
builder- The builder thatformatterwill write to.formatter- The formatter.timeMs- The time to format as a string, in milliseconds.- Returns:
- The time formatted as a string.
-
escapeFileName
public static String escapeFileName(String fileName)
Deprecated.Escapes a string so that it's safe for use as a file or directory name on at least FAT32 filesystems. FAT32 is the most restrictive of all filesystems still commonly used today.For simplicity, this only handles common characters known to be illegal on FAT32: <, >, :, ", /, \, |, ?, and *. % is also escaped since it is used as the escape character. Escaping is performed in a consistent way so that no collisions occur and
unescapeFileName(String)can be used to retrieve the original file name.- Parameters:
fileName- File name to be escaped.- Returns:
- An escaped file name which will be safe for use on at least FAT32 filesystems.
-
unescapeFileName
@Nullable public static String unescapeFileName(String fileName)
Deprecated.Unescapes an escaped file or directory name back to its original value.See
escapeFileName(String)for more information.- Parameters:
fileName- File name to be unescaped.- Returns:
- The original value of the file name before it was escaped, or null if the escaped fileName seems invalid.
-
getDataUriForString
public static Uri getDataUriForString(String mimeType, String data)
Deprecated.Returns a data URI with the specified MIME type and data.
-
sneakyThrow
public static void sneakyThrow(Throwable t)
Deprecated.A hacky method that always throwsteven iftis a checked exception, and is not declared to be thrown.
-
recursiveDelete
public static void recursiveDelete(File fileOrDirectory)
Deprecated.Recursively deletes a directory and its content.
-
createTempDirectory
public static File createTempDirectory(Context context, String prefix) throws IOException
Deprecated.Creates an empty directory in the directory returned byContext.getCacheDir().- Throws:
IOException
-
createTempFile
public static File createTempFile(Context context, String prefix) throws IOException
Deprecated.Creates a new empty file in the directory returned byContext.getCacheDir().- Throws:
IOException
-
crc32
public static int crc32(byte[] bytes, int start, int end, int initialValue)Deprecated.Returns the result of updating a CRC-32 with the specified bytes in a "most significant bit first" order.- Parameters:
bytes- Array containing the bytes to update the crc value with.start- The index to the first byte in the byte range to update the crc with.end- The index after the last byte in the byte range to update the crc with.initialValue- The initial value for the crc calculation.- Returns:
- The result of updating the initial value with the specified bytes.
-
crc8
public static int crc8(byte[] bytes, int start, int end, int initialValue)Deprecated.Returns the result of updating a CRC-8 with the specified bytes in a "most significant bit first" order.- Parameters:
bytes- Array containing the bytes to update the crc value with.start- The index to the first byte in the byte range to update the crc with.end- The index after the last byte in the byte range to update the crc with.initialValue- The initial value for the crc calculation.- Returns:
- The result of updating the initial value with the specified bytes.
-
gzip
public static byte[] gzip(byte[] input)
Deprecated.Compressesinputusing gzip and returns the result in a newly allocated byte array.
-
getBigEndianInt
public static int getBigEndianInt(ByteBuffer buffer, int index)
Deprecated.Absolute get method for reading an int value inByteOrder.BIG_ENDIANin aByteBuffer. Same asByteBuffer.getInt(int)except the buffer's order as returned byByteBuffer.order()is ignored andByteOrder.BIG_ENDIANis used instead.- Parameters:
buffer- The buffer from which to read an int in big endian.index- The index from which the bytes will be read.- Returns:
- The int value at the given index with the buffer bytes ordered most significant to least significant.
-
getCountryCode
public static String getCountryCode(@Nullable Context context)
Deprecated.Returns the upper-case ISO 3166-1 alpha-2 country code of the current registered operator's MCC (Mobile Country Code), or the country code of the default Locale if not available.- Parameters:
context- A context to access the telephony service. If null, only the Locale can be used.- Returns:
- The upper-case ISO 3166-1 alpha-2 country code, or an empty String if unavailable.
-
getSystemLanguageCodes
public static String[] getSystemLanguageCodes()
Deprecated.Returns a non-empty array of normalized IETF BCP 47 language tags for the system languages ordered by preference.
-
getDefaultDisplayLocale
public static Locale getDefaultDisplayLocale()
Deprecated.
-
inflate
public static boolean inflate(ParsableByteArray input, ParsableByteArray output, @Nullable Inflater inflater)
Deprecated.Uncompresses the data ininput.- Parameters:
input- Wraps the compressed input data.output- Wraps an output buffer to be used to store the uncompressed data. Ifoutput.dataisn't big enough to hold the uncompressed data, a new array is created. Iftrueis returned then the output's position will be set to 0 and its limit will be set to the length of the uncompressed data.inflater- If not null, used to uncompressed the input. Otherwise a newInflateris created.- Returns:
- Whether the input is uncompressed successfully.
-
isTv
public static boolean isTv(Context context)
Deprecated.Returns whether the app is running on a TV device.- Parameters:
context- Any context.- Returns:
- Whether the app is running on a TV device.
-
isAutomotive
public static boolean isAutomotive(Context context)
Deprecated.Returns whether the app is running on an automotive device.- Parameters:
context- Any context.- Returns:
- Whether the app is running on an automotive device.
-
getCurrentDisplayModeSize
public static Point getCurrentDisplayModeSize(Context context)
Deprecated.Gets the size of the current mode of the default display, in pixels.Note that due to application UI scaling, the number of pixels made available to applications (as reported by
Display.getSize(Point)may differ from the mode's actual resolution (as reported by this function). For example, applications running on a display configured with a 4K mode may have their UI laid out and rendered in 1080p and then scaled up. Applications can take advantage of the full mode resolution through aSurfaceViewusing full size buffers.- Parameters:
context- Any context.- Returns:
- The size of the current mode, in pixels.
-
getCurrentDisplayModeSize
public static Point getCurrentDisplayModeSize(Context context, Display display)
Deprecated.Gets the size of the current mode of the specified display, in pixels.Note that due to application UI scaling, the number of pixels made available to applications (as reported by
Display.getSize(Point)may differ from the mode's actual resolution (as reported by this function). For example, applications running on a display configured with a 4K mode may have their UI laid out and rendered in 1080p and then scaled up. Applications can take advantage of the full mode resolution through aSurfaceViewusing full size buffers.- Parameters:
context- Any context.display- The display whose size is to be returned.- Returns:
- The size of the current mode, in pixels.
-
getTrackTypeString
public static String getTrackTypeString(@com.google.android.exoplayer2.C.TrackType int trackType)
Deprecated.Returns a string representation of aC.TrackType.- Parameters:
trackType- AC.TrackTypeconstant,- Returns:
- A string representation of this constant.
-
getNowUnixTimeMs
public static long getNowUnixTimeMs(long elapsedRealtimeEpochOffsetMs)
Deprecated.Returns the current time in milliseconds since the epoch.- Parameters:
elapsedRealtimeEpochOffsetMs- The offset betweenSystemClock.elapsedRealtime()and the time since the Unix epoch, orC.TIME_UNSETif unknown.- Returns:
- The Unix time in milliseconds since the epoch.
-
moveItems
public static <T> void moveItems(List<T> items, int fromIndex, int toIndex, int newFromIndex)
Deprecated.Moves the elements starting atfromIndextonewFromIndex.- Parameters:
items- The list of which to move elements.fromIndex- The index at which the items to move start.toIndex- The index up to which elements should be moved (exclusive).newFromIndex- The new from index.
-
tableExists
public static boolean tableExists(SQLiteDatabase database, String tableName)
Deprecated.Returns whether the table exists in the database.
-
getErrorCodeFromPlatformDiagnosticsInfo
public static int getErrorCodeFromPlatformDiagnosticsInfo(@Nullable String diagnosticsInfo)Deprecated.Attempts to parse an error code from a diagnostic string found in framework media exceptions.For example: android.media.MediaCodec.error_1 or android.media.MediaDrm.error_neg_2.
- Parameters:
diagnosticsInfo- A string from which to parse the error code.- Returns:
- The parser error code, or 0 if an error code could not be parsed.
-
getMaxPendingFramesCountForMediaCodecDecoders
public static int getMaxPendingFramesCountForMediaCodecDecoders(Context context, String codecName, boolean requestedHdrToneMapping)
Deprecated.Returns the number of maximum pending output frames that are allowed on aMediaCodecdecoder.
-
getFormatSupportString
public static String getFormatSupportString(@FormatSupport @com.google.android.exoplayer2.C.FormatSupport int formatSupport)
Deprecated.Returns string representation of aC.FormatSupportflag.- Parameters:
formatSupport- AC.FormatSupportflag.- Returns:
- A string representation of the flag.
-
getAvailableCommands
public static Player.Commands getAvailableCommands(Player player, Player.Commands permanentAvailableCommands)
Deprecated.Returns thePlayer.Commandsavailable in thePlayer.- Parameters:
player- ThePlayer.permanentAvailableCommands- The commands permanently available in the player.- Returns:
- The available
Player.Commands.
-
sum
public static long sum(long... summands)
Deprecated.Returns the sum of all summands of the given array.- Parameters:
summands- The summands to calculate the sum from.- Returns:
- The sum of all summands.
-
getDrawable
public static Drawable getDrawable(Context context, Resources resources, @DrawableRes int drawableRes)
Deprecated.Returns aDrawablefor the given resource or throws aResources.NotFoundExceptionif not found.- Parameters:
context- The context to get the theme from starting with API 21.resources- The resources to load the drawable from.drawableRes- The drawable resource int.- Returns:
- The loaded
Drawable.
-
intToStringMaxRadix
public static String intToStringMaxRadix(int i)
Deprecated.Returns a string representation of the integer using radix valueCharacter.MAX_RADIX.- Parameters:
i- An integer to be converted to String.
-
shouldShowPlayButton
@EnsuresNonNullIf(result=false, expression="#1") public static boolean shouldShowPlayButton(@Nullable Player player)Deprecated.Returns whether a play button should be presented on a UI element for playback control. Iffalse, a pause button should be shown instead.Use
handlePlayPauseButtonAction(com.google.android.exoplayer2.Player),handlePlayButtonAction(com.google.android.exoplayer2.Player)orhandlePauseButtonAction(com.google.android.exoplayer2.Player)to handle the interaction with the play or pause button UI element.- Parameters:
player- ThePlayer. May be null.
-
handlePlayButtonAction
public static boolean handlePlayButtonAction(@Nullable Player player)Deprecated.Updates the player to handle an interaction with a play button.This method assumes the play button is enabled if
shouldShowPlayButton(com.google.android.exoplayer2.Player)returns true.- Parameters:
player- ThePlayer. May be null.- Returns:
- Whether a player method was triggered to handle this action.
-
handlePauseButtonAction
public static boolean handlePauseButtonAction(@Nullable Player player)Deprecated.Updates the player to handle an interaction with a pause button.This method assumes the pause button is enabled if
shouldShowPlayButton(com.google.android.exoplayer2.Player)returns false.- Parameters:
player- ThePlayer. May be null.- Returns:
- Whether a player method was triggered to handle this action.
-
handlePlayPauseButtonAction
public static boolean handlePlayPauseButtonAction(@Nullable Player player)Deprecated.Updates the player to handle an interaction with a play or pause button.This method assumes that the UI element enables a play button if
shouldShowPlayButton(com.google.android.exoplayer2.Player)returns true and a pause button otherwise.- Parameters:
player- ThePlayer. May be null.- Returns:
- Whether a player method was triggered to handle this action.
-
-