Class Util
- java.lang.Object
-
- com.google.android.exoplayer2.util.Util
-
public final class Util extends Object
Miscellaneous utility methods.
-
-
Field Summary
Fields Modifier and Type Field Description static String
DEVICE
LikeBuild.DEVICE
, but in a place where it can be conveniently overridden for local testing.static String
DEVICE_DEBUG_INFO
A concise description of the device that it can be useful to log for debugging purposes.static byte[]
EMPTY_BYTE_ARRAY
An empty byte array.static String
MANUFACTURER
LikeBuild.MANUFACTURER
, but in a place where it can be conveniently overridden for local testing.static String
MODEL
LikeBuild.MODEL
, but in a place where it can be conveniently overridden for local testing.static int
SDK_INT
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 Modifier and Type Method Description static long
addWithOverflowDefault(long x, long y, long overflowResult)
Returns the sum of two arguments, or a third argument if the result overflows.static boolean
areEqual(Object o1, Object o2)
Tests two objects forObject.equals(Object)
equality, handling the case where one or both may be null.static int
binarySearchCeil(int[] array, int value, boolean inclusive, boolean stayInBounds)
Returns the index of the smallest element inarray
that is greater than (or optionally equal to) a specifiedvalue
.static int
binarySearchCeil(long[] array, long value, boolean inclusive, boolean stayInBounds)
Returns the index of the smallest element inarray
that 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)
Returns the index of the smallest element inlist
that is greater than (or optionally equal to) a specified value.static int
binarySearchFloor(int[] array, int value, boolean inclusive, boolean stayInBounds)
Returns the index of the largest element inarray
that is less than (or optionally equal to) a specifiedvalue
.static int
binarySearchFloor(long[] array, long value, boolean inclusive, boolean stayInBounds)
Returns the index of the largest element inarray
that is less than (or optionally equal to) a specifiedvalue
.static int
binarySearchFloor(LongArray longArray, long value, boolean inclusive, boolean stayInBounds)
Returns the index of the largest element inlongArray
that 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)
Returns the index of the largest element inlist
that is less than (or optionally equal to) a specifiedvalue
.static <T> T
castNonNull(T value)
Casts a nullable variable to a non-null variable without runtime null check.static <T> T[]
castNonNullTypeArray(@NullableType T[] value)
Casts a nullable type array to a non-null type array without runtime null check.static int
ceilDivide(int numerator, int denominator)
Divides anumerator
by adenominator
, returning the ceiled result.static long
ceilDivide(long numerator, long denominator)
Divides anumerator
by adenominator
, returning the ceiled result.static boolean
checkCleartextTrafficPermitted(MediaItem... mediaItems)
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 void
closeQuietly(Closeable closeable)
Closes aCloseable
, suppressing anyIOException
that may occur.static int
compareLong(long left, long right)
Compares two long values and returns the same value asLong.compare(long, long)
.static float
constrainValue(float value, float min, float max)
Constrains a value to the specified bounds.static int
constrainValue(int value, int min, int max)
Constrains a value to the specified bounds.static long
constrainValue(long value, long min, long max)
Constrains a value to the specified bounds.static boolean
contains(@NullableType Object[] items, Object item)
static int
crc32(byte[] bytes, int start, int end, int initialValue)
Returns the result of updating a CRC-32 with the specified bytes in a "most significant bit first" order.static int
crc8(byte[] bytes, int start, int end, int initialValue)
Returns the result of updating a CRC-8 with the specified bytes in a "most significant bit first" order.static Handler
createHandler(Looper looper, @UnknownInitialization Handler.Callback callback)
static Handler
createHandlerForCurrentLooper()
static Handler
createHandlerForCurrentLooper(@UnknownInitialization Handler.Callback callback)
static Handler
createHandlerForCurrentOrMainLooper()
static Handler
createHandlerForCurrentOrMainLooper(@UnknownInitialization Handler.Callback callback)
static File
createTempDirectory(Context context, String prefix)
Creates an empty directory in the directory returned byContext.getCacheDir()
.static File
createTempFile(Context context, String prefix)
Creates a new empty file in the directory returned byContext.getCacheDir()
.static String
escapeFileName(String fileName)
Escapes a string so that it's safe for use as a file or directory name on at least FAT32 filesystems.static Uri
fixSmoothStreamingIsmManifestUri(Uri uri)
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 String
formatInvariant(String format, Object... args)
Formats a string usingLocale.US
.static String
fromUtf8Bytes(byte[] bytes)
Returns a newString
constructed by decoding UTF-8 encoded bytes.static String
fromUtf8Bytes(byte[] bytes, int offset, int length)
Returns a newString
constructed by decoding UTF-8 encoded bytes in a subarray.static int
generateAudioSessionIdV21(Context context)
Returns a newly generated audio session identifier, orAudioManager.ERROR
if an error occurred in which case audio playback may fail.static String
getAdaptiveMimeTypeForContentType(int contentType)
Returns the MIME type corresponding to the given adaptiveC.ContentType
, ornull
if the content type isC.TYPE_OTHER
.static @com.google.android.exoplayer2.C.AudioContentType int
getAudioContentTypeForStreamType(int streamType)
Returns theC.AudioContentType
corresponding to the specifiedC.StreamType
.static int
getAudioTrackChannelConfig(int channelCount)
Returns the audio track channel configuration for the given channel count, orAudioFormat.CHANNEL_INVALID
if output is not possible.static @com.google.android.exoplayer2.C.AudioUsage int
getAudioUsageForStreamType(int streamType)
Returns theC.AudioUsage
corresponding to the specifiedC.StreamType
.static int
getBigEndianInt(ByteBuffer buffer, int index)
Absolute get method for reading an int value inByteOrder.BIG_ENDIAN
in aByteBuffer
.static byte[]
getBytesFromHexString(String hexString)
Returns a byte array containing values parsed from the hex string provided.static int
getCodecCountOfType(String codecs, @com.google.android.exoplayer2.C.TrackType int trackType)
Returns the number of codec strings incodecs
whose type matchestrackType
.static String
getCodecsOfType(String codecs, @com.google.android.exoplayer2.C.TrackType int trackType)
Returns a copy ofcodecs
without the codecs whose track type doesn't matchtrackType
.static String
getCommaDelimitedSimpleClassNames(Object[] objects)
Returns a string with comma delimited simple names of each object's class.static String
getCountryCode(Context context)
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 Point
getCurrentDisplayModeSize(Context context)
Gets the size of the current mode of the default display, in pixels.static Point
getCurrentDisplayModeSize(Context context, Display display)
Gets the size of the current mode of the specified display, in pixels.static Looper
getCurrentOrMainLooper()
static Uri
getDataUriForString(String mimeType, String data)
Returns a data URI with the specified MIME type and data.static Locale
getDefaultDisplayLocale()
static UUID
getDrmUuid(String drmScheme)
Derives a DRMUUID
fromdrmScheme
.static @com.google.android.exoplayer2.PlaybackException.ErrorCode int
getErrorCodeForMediaDrmErrorCode(int mediaDrmErrorCode)
Returns aPlaybackException.ErrorCode
value that corresponds to the providedMediaDrm.ErrorCodes
value.static int
getErrorCodeFromPlatformDiagnosticsInfo(String diagnosticsInfo)
Attempts to parse an error code from a diagnostic string found in framework media exceptions.static String
getFormatSupportString(int formatSupport)
Returns string representation of aC.FormatSupport
flag.static int
getIntegerCodeForString(String string)
Returns the integer equal to the big-endian concatenation of the characters instring
as bytes.static String
getLocaleLanguageTag(Locale locale)
Returns the language tag for aLocale
.static long
getMediaDurationForPlayoutDuration(long playoutDuration, float speed)
Returns the duration of media that will elapse inplayoutDuration
.static long
getNowUnixTimeMs(long elapsedRealtimeEpochOffsetMs)
Returns the current time in milliseconds since the epoch.static int
getPcmEncoding(int bitDepth)
Converts a sample bit depth to a corresponding PCM encoding constant.static Format
getPcmFormat(int pcmEncoding, int channels, int sampleRate)
Gets a PCMFormat
with the specified parameters.static int
getPcmFrameSize(int pcmEncoding, int channelCount)
Returns the frame size for audio withchannelCount
channels in the specified encoding.static long
getPlayoutDurationForMediaDuration(long mediaDuration, float speed)
Returns the playout duration ofmediaDuration
of media.static int
getStreamTypeForAudioUsage(@com.google.android.exoplayer2.C.AudioUsage int usage)
Returns theC.StreamType
corresponding to the specifiedC.AudioUsage
.static String
getStringForTime(StringBuilder builder, Formatter formatter, long timeMs)
Returns the specified millisecond time formatted as a string.static String[]
getSystemLanguageCodes()
Returns a non-empty array of normalized IETF BCP 47 language tags for the system languages ordered by preference.static String
getTrackTypeString(@com.google.android.exoplayer2.C.TrackType int trackType)
Returns a string representation of aC.TrackType
.static String
getUserAgent(Context context, String applicationName)
Returns a user agent string based on the given application name and the library version.static byte[]
getUtf8Bytes(String value)
Returns a new byte array containing the code points of aString
encoded using UTF-8.static byte[]
gzip(byte[] input)
Compressesinput
using gzip and returns the result in a newly allocated byte array.static int
inferContentType(Uri uri)
Makes a best guess to infer theC.ContentType
from aUri
.static int
inferContentType(Uri uri, String overrideExtension)
Makes a best guess to infer theC.ContentType
from aUri
.static int
inferContentType(String fileName)
Makes a best guess to infer theC.ContentType
from a file name.static int
inferContentTypeForUriAndMimeType(Uri uri, String mimeType)
Makes a best guess to infer theC.ContentType
from aUri
and optional MIME type.static boolean
inflate(ParsableByteArray input, ParsableByteArray output, Inflater inflater)
Uncompresses the data ininput
.static boolean
isAutomotive(Context context)
Returns whether the app is running on an automotive device.static boolean
isEncodingHighResolutionPcm(int encoding)
Returns whetherencoding
is high resolution (> 16-bit) PCM.static boolean
isEncodingLinearPcm(int encoding)
Returns whetherencoding
is one of the linear PCM encodings.static boolean
isLinebreak(int c)
Returns whether the given character is a carriage return ('\r') or a line feed ('\n').static boolean
isLocalFileUri(Uri uri)
Returns true if the URI is a path to a local file or a reference to a local file.static boolean
isTv(Context context)
Returns whether the app is running on a TV device.static int
linearSearch(int[] array, int value)
Returns the index of the first occurrence ofvalue
inarray
, orC.INDEX_UNSET
ifvalue
is not contained inarray
.static int
linearSearch(long[] array, long value)
Returns the index of the first occurrence ofvalue
inarray
, orC.INDEX_UNSET
ifvalue
is not contained inarray
.static boolean
maybeRequestReadExternalStoragePermission(Activity activity, Uri... uris)
Checks whether it's necessary to request theManifest.permission.READ_EXTERNAL_STORAGE
permission read the specifiedUri
s, requesting the permission if necessary.static boolean
maybeRequestReadExternalStoragePermission(Activity activity, MediaItem... mediaItems)
Checks whether it's necessary to request theManifest.permission.READ_EXTERNAL_STORAGE
permission for the specifiedmedia items
, requesting the permission if necessary.static long
minValue(SparseLongArray sparseLongArray)
Returns the minimum value in the givenSparseLongArray
.static <T> void
moveItems(List<T> items, int fromIndex, int toIndex, int newFromIndex)
Moves the elements starting atfromIndex
tonewFromIndex
.static long
msToUs(long timeMs)
Converts a time in milliseconds to the corresponding time in microseconds, preservingC.TIME_UNSET
values andC.TIME_END_OF_SOURCE
values.static ExecutorService
newSingleThreadExecutor(String threadName)
Instantiates a new single threaded executor whose thread has the specified name.static @PolyNull String
normalizeLanguageCode(@PolyNull String language)
Returns a normalized IETF BCP 47 language tag forlanguage
.static <T> T[]
nullSafeArrayAppend(T[] original, T newElement)
Creates a new array containingoriginal
withnewElement
appended.static <T> T[]
nullSafeArrayConcatenation(T[] first, T[] second)
Creates a new array containing the concatenation of two non-null type arrays.static <T> T[]
nullSafeArrayCopy(T[] input, int length)
Copies and optionally truncates an array.static <T> T[]
nullSafeArrayCopyOfRange(T[] input, int from, int to)
Copies a subset of an array.static <T> void
nullSafeListToArray(List<T> list, T[] array)
Copies the contents oflist
intoarray
.static long
parseXsDateTime(String value)
Parses an xs:dateTime attribute value, returning the parsed timestamp in milliseconds since the epoch.static long
parseXsDuration(String value)
Parses an xs:duration attribute value, returning the parsed duration in milliseconds.static boolean
postOrRun(Handler handler, Runnable runnable)
static boolean
readBoolean(Parcel parcel)
Reads an integer from aParcel
and interprets it as a boolean, with 0 mapping to false and all other values mapping to true.static void
recursiveDelete(File fileOrDirectory)
Recursively deletes a directory and its content.static <T> void
removeRange(List<T> list, int fromIndex, int toIndex)
Removes an indexed range from a List.static long
scaleLargeTimestamp(long timestamp, long multiplier, long divisor)
Scales a large timestamp.static long[]
scaleLargeTimestamps(List<Long> timestamps, long multiplier, long divisor)
AppliesscaleLargeTimestamp(long, long, long)
to a list of unscaled timestamps.static void
scaleLargeTimestampsInPlace(long[] timestamps, long multiplier, long divisor)
AppliesscaleLargeTimestamp(long, long, long)
to an array of unscaled timestamps.static void
sneakyThrow(Throwable t)
A hacky method that always throwst
even ift
is a checked exception, and is not declared to be thrown.static String[]
split(String value, String regex)
Splits a string usingvalue.split(regex, -1
).static String[]
splitAtFirst(String value, String regex)
Splits the string at the first occurrence of the delimiterregex
.static String[]
splitCodecs(String codecs)
Splits a codecs sequence string, as defined in RFC 6381, into individual codec strings.static ComponentName
startForegroundService(Context context, Intent intent)
CallsContext.startForegroundService(Intent)
ifSDK_INT
is 26 or higher, orContext.startService(Intent)
otherwise.static long
subtractWithOverflowDefault(long x, long y, long overflowResult)
Returns the difference between two arguments, or a third argument if the result overflows.static boolean
tableExists(SQLiteDatabase database, String tableName)
Returns whether the table exists in the database.static byte[]
toByteArray(InputStream inputStream)
Converts the entirety of anInputStream
to a byte array.static String
toHexString(byte[] bytes)
Returns a string containing a lower-case hex representation of the bytes provided.static long
toLong(int mostSignificantBits, int leastSignificantBits)
Returns the long that is composed of the bits of the 2 specified integers.static long
toUnsignedLong(int x)
Converts an integer to a long by unsigned conversion.static CharSequence
truncateAscii(CharSequence sequence, int maxLength)
Truncates a sequence of ASCII characters to a maximum length.static String
unescapeFileName(String fileName)
Unescapes an escaped file or directory name back to its original value.static long
usToMs(long timeUs)
Converts a time in microseconds to the corresponding time in milliseconds, preservingC.TIME_UNSET
andC.TIME_END_OF_SOURCE
values.static void
writeBoolean(Parcel parcel, boolean value)
Writes a boolean to aParcel
.
-
-
-
Field Detail
-
SDK_INT
public static final int SDK_INT
LikeBuild.VERSION.SDK_INT
, but in a place where it can be conveniently overridden for local testing.
-
DEVICE
public static final String DEVICE
LikeBuild.DEVICE
, but in a place where it can be conveniently overridden for local testing.
-
MANUFACTURER
public static final String MANUFACTURER
LikeBuild.MANUFACTURER
, but in a place where it can be conveniently overridden for local testing.
-
MODEL
public static final String MODEL
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
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
An empty byte array.
-
-
Method Detail
-
toByteArray
public static byte[] toByteArray(InputStream inputStream) throws IOException
Converts the entirety of anInputStream
to a byte array.- Parameters:
inputStream
- theInputStream
to 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.
-
startForegroundService
@Nullable public static ComponentName startForegroundService(Context context, Intent intent)
CallsContext.startForegroundService(Intent)
ifSDK_INT
is 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)
Checks whether it's necessary to request theManifest.permission.READ_EXTERNAL_STORAGE
permission read the specifiedUri
s, requesting the permission if necessary.- Parameters:
activity
- The host activity for checking and requesting the permission.uris
-Uri
s that may requireManifest.permission.READ_EXTERNAL_STORAGE
to read.- Returns:
- Whether a permission request was made.
-
maybeRequestReadExternalStoragePermission
public static boolean maybeRequestReadExternalStoragePermission(Activity activity, MediaItem... mediaItems)
Checks whether it's necessary to request theManifest.permission.READ_EXTERNAL_STORAGE
permission for the specifiedmedia items
, requesting the permission if necessary.- Parameters:
activity
- The host activity for checking and requesting the permission.mediaItems
-Media items
s that may requireManifest.permission.READ_EXTERNAL_STORAGE
to read.- Returns:
- Whether a permission request was made.
-
checkCleartextTrafficPermitted
public static boolean checkCleartextTrafficPermitted(MediaItem... mediaItems)
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)
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)
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)
Tests whether anitems
array contains an object equal toitem
, according toObject.equals(Object)
.If
item
is null then true is returned if and only ifitems
contains 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)
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)
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)
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)
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)
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)
Creates a new array containingoriginal
withnewElement
appended.- Parameters:
original
- The input array.newElement
- The element to append.- Returns:
- The new array.
-
nullSafeArrayConcatenation
public static <T> T[] nullSafeArrayConcatenation(T[] first, T[] second)
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)
Copies the contents oflist
intoarray
.list.size()
must be the same asarray.length
to ensure the contents can be copied intoarray
without 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()
- Throws:
IllegalStateException
- If the current thread doesn't have aLooper
.
-
createHandlerForCurrentLooper
public static Handler createHandlerForCurrentLooper(@Nullable @UnknownInitialization Handler.Callback callback)
Creates aHandler
with the specifiedHandler.Callback
on the currentLooper
thread.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
Handler
with the specified callback on the currentLooper
thread. - Throws:
IllegalStateException
- If the current thread doesn't have aLooper
.
-
createHandlerForCurrentOrMainLooper
public static Handler createHandlerForCurrentOrMainLooper()
-
createHandlerForCurrentOrMainLooper
public static Handler createHandlerForCurrentOrMainLooper(@Nullable @UnknownInitialization Handler.Callback callback)
Creates aHandler
with the specifiedHandler.Callback
on the currentLooper
thread.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 threadLooper
is used.- Parameters:
callback
- AHandler.Callback
. May be a partially initialized class, or null if no callback is required.- Returns:
- A
Handler
with the specified callback on the currentLooper
thread.
-
createHandler
public static Handler createHandler(Looper looper, @Nullable @UnknownInitialization Handler.Callback callback)
Creates aHandler
with the specifiedHandler.Callback
on the specifiedLooper
thread.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
- ALooper
to run the callback on.callback
- AHandler.Callback
. May be a partially initialized class, or null if no callback is required.- Returns:
- A
Handler
with the specified callback on the currentLooper
thread.
-
getCurrentOrMainLooper
public static Looper getCurrentOrMainLooper()
-
newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor(String threadName)
Instantiates a new single threaded 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)
Closes aCloseable
, suppressing anyIOException
that may occur. BothOutputStream
andInputStream
areCloseable
.- Parameters:
closeable
- TheCloseable
to close.
-
readBoolean
public static boolean readBoolean(Parcel parcel)
Reads an integer from aParcel
and interprets it as a boolean, with 0 mapping to false and all other values mapping to true.- Parameters:
parcel
- TheParcel
to read from.- Returns:
- The read value.
-
writeBoolean
public static void writeBoolean(Parcel parcel, boolean value)
Writes a boolean to aParcel
. The boolean is written as an integer with value 1 (true) or 0 (false).- Parameters:
parcel
- TheParcel
to write to.value
- The value to write.
-
getLocaleLanguageTag
public static String getLocaleLanguageTag(Locale locale)
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)
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)
Returns a newString
constructed 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)
Returns a newString
constructed 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)
Returns a new byte array containing the code points of aString
encoded using UTF-8.- Parameters:
value
- TheString
whose bytes should be obtained.- Returns:
- The code points encoding using UTF-8.
-
split
public static String[] split(String value, String regex)
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)
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)
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)
Formats a string usingLocale.US
.- See Also:
String.format(String, Object...)
-
ceilDivide
public static int ceilDivide(int numerator, int denominator)
Divides anumerator
by 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)
Divides anumerator
by 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)
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)
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)
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)
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 + y
overflows.- Returns:
x + y
, oroverflowResult
if the result overflows.
-
subtractWithOverflowDefault
public static long subtractWithOverflowDefault(long x, long y, long overflowResult)
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 - y
overflows.- Returns:
x - y
, oroverflowResult
if the result overflows.
-
linearSearch
public static int linearSearch(int[] array, int value)
Returns the index of the first occurrence ofvalue
inarray
, orC.INDEX_UNSET
ifvalue
is 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_UNSET
ifvalue
is not contained inarray
.
-
linearSearch
public static int linearSearch(long[] array, long value)
Returns the index of the first occurrence ofvalue
inarray
, orC.INDEX_UNSET
ifvalue
is 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_UNSET
ifvalue
is not contained inarray
.
-
binarySearchFloor
public static int binarySearchFloor(int[] array, int value, boolean inclusive, boolean stayInBounds)
Returns the index of the largest element inarray
that 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
value
andinclusive
is 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
array
that is less than (or optionally equal to)value
.
-
binarySearchFloor
public static int binarySearchFloor(long[] array, long value, boolean inclusive, boolean stayInBounds)
Returns the index of the largest element inarray
that 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
value
andinclusive
is 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
array
that 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)
Returns the index of the largest element inlist
that 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
value
andinclusive
is 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
list
that is less than (or optionally equal to)value
.
-
binarySearchFloor
public static int binarySearchFloor(LongArray longArray, long value, boolean inclusive, boolean stayInBounds)
Returns the index of the largest element inlongArray
that 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
value
andinclusive
is 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
array
that is less than (or optionally equal to)value
.
-
binarySearchCeil
public static int binarySearchCeil(int[] array, int value, boolean inclusive, boolean stayInBounds)
Returns the index of the smallest element inarray
that 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
value
andinclusive
is 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.length
will be returned.- Returns:
- The index of the smallest element in
array
that is greater than (or optionally equal to)value
.
-
binarySearchCeil
public static int binarySearchCeil(long[] array, long value, boolean inclusive, boolean stayInBounds)
Returns the index of the smallest element inarray
that 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
value
andinclusive
is 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.length
will be returned.- Returns:
- The index of the smallest element in
array
that 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)
Returns the index of the smallest element inlist
that 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
value
andinclusive
is 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
list
that is greater than (or optionally equal to)value
.
-
compareLong
public static int compareLong(long left, long right)
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)
Returns the minimum value in the givenSparseLongArray
.- Parameters:
sparseLongArray
- TheSparseLongArray
.- Returns:
- The minimum value.
- Throws:
NoSuchElementException
- If the array is empty.
-
usToMs
public static long usToMs(long timeUs)
Converts a time in microseconds to the corresponding time in milliseconds, preservingC.TIME_UNSET
andC.TIME_END_OF_SOURCE
values.- Parameters:
timeUs
- The time in microseconds.- Returns:
- The corresponding time in milliseconds.
-
msToUs
public static long msToUs(long timeMs)
Converts a time in milliseconds to the corresponding time in microseconds, preservingC.TIME_UNSET
values andC.TIME_END_OF_SOURCE
values.- Parameters:
timeMs
- The time in milliseconds.- Returns:
- The corresponding time in microseconds.
-
parseXsDuration
public static long parseXsDuration(String value)
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
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)
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)
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)
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)
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)
Returns the playout duration ofmediaDuration
of media.- Parameters:
mediaDuration
- The duration to scale.- Returns:
- The scaled duration, in the same units as
mediaDuration
.
-
getIntegerCodeForString
public static int getIntegerCodeForString(String string)
Returns the integer equal to the big-endian concatenation of the characters instring
as 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)
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)
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
mostSignificantBits
bits and its 32 least significant bits areleastSignificantBits
.
-
truncateAscii
public static CharSequence truncateAscii(CharSequence sequence, int maxLength)
Truncates a sequence of ASCII characters to a maximum length.This preserves span styling in the
CharSequence
. If that's not important, useAscii.truncate(CharSequence, int, String)
.Note: This is not safe to use in general on Unicode text because it may separate characters from combining characters or split up surrogate pairs.
- Parameters:
sequence
- The character sequence to truncate.maxLength
- The max length to truncate to.- Returns:
sequence
directly ifsequence.length() <= maxLength
, otherwisesequence.subsequence(0, maxLength
.
-
getBytesFromHexString
public static byte[] getBytesFromHexString(String hexString)
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)
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)
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)
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)
Returns the number of codec strings incodecs
whose type matchestrackType
.
-
getCodecsOfType
@Nullable public static String getCodecsOfType(@Nullable String codecs, @com.google.android.exoplayer2.C.TrackType int trackType)
Returns a copy ofcodecs
without 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
codecs
without the codecs whose track type doesn't matchtrackType
. If this ends up empty, orcodecs
is null, returns null.
-
splitCodecs
public static String[] splitCodecs(@Nullable String codecs)
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(@PcmEncoding int pcmEncoding, int channels, int sampleRate)
Gets a PCMFormat
with the specified parameters.- Parameters:
pcmEncoding
- TheC.PcmEncoding
.channels
- The number of channels, orFormat.NO_VALUE
if unknown.sampleRate
- The sample rate in Hz, orFormat.NO_VALUE
if unknown.- Returns:
- The PCM format.
-
getPcmEncoding
@PcmEncoding public static int getPcmEncoding(int bitDepth)
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_24BIT
andC.ENCODING_PCM_32BIT
. If the bit depth is unsupported thenC.ENCODING_INVALID
is returned.
-
isEncodingLinearPcm
public static boolean isEncodingLinearPcm(@Encoding int encoding)
Returns whetherencoding
is 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(@PcmEncoding int encoding)
Returns whetherencoding
is 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)
Returns the audio track channel configuration for the given channel count, orAudioFormat.CHANNEL_INVALID
if output is not possible.- Parameters:
channelCount
- The number of channels in the input audio.- Returns:
- The channel configuration or
AudioFormat.CHANNEL_INVALID
if output is not possible.
-
getPcmFrameSize
public static int getPcmFrameSize(@PcmEncoding int pcmEncoding, int channelCount)
Returns the frame size for audio withchannelCount
channels 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 int streamType)
Returns theC.AudioUsage
corresponding to the specifiedC.StreamType
.
-
getAudioContentTypeForStreamType
@AudioContentType public static @com.google.android.exoplayer2.C.AudioContentType int getAudioContentTypeForStreamType(@StreamType int streamType)
Returns theC.AudioContentType
corresponding to the specifiedC.StreamType
.
-
getStreamTypeForAudioUsage
@StreamType public static int getStreamTypeForAudioUsage(@AudioUsage @com.google.android.exoplayer2.C.AudioUsage int usage)
Returns theC.StreamType
corresponding to the specifiedC.AudioUsage
.
-
generateAudioSessionIdV21
@RequiresApi(21) public static int generateAudioSessionIdV21(Context context)
Returns a newly generated audio session identifier, orAudioManager.ERROR
if an error occurred in which case audio playback may fail.- See Also:
AudioManager.generateAudioSessionId()
-
getDrmUuid
@Nullable public static UUID getDrmUuid(String drmScheme)
Derives a DRMUUID
fromdrmScheme
.- Parameters:
drmScheme
- A UUID string, or"widevine"
,"playready"
or"clearkey"
.- Returns:
- The derived
UUID
, ornull
if one could not be derived.
-
getErrorCodeForMediaDrmErrorCode
@ErrorCode public static @com.google.android.exoplayer2.PlaybackException.ErrorCode int getErrorCodeForMediaDrmErrorCode(int mediaDrmErrorCode)
Returns aPlaybackException.ErrorCode
value that corresponds to the providedMediaDrm.ErrorCodes
value. ReturnsPlaybackException.ERROR_CODE_DRM_SYSTEM_ERROR
if the provided error code isn't recognised.
-
inferContentType
@ContentType public static int inferContentType(Uri uri, @Nullable String overrideExtension)
Makes a best guess to infer theC.ContentType
from aUri
.- Parameters:
uri
- TheUri
.overrideExtension
- If not null, used to infer the type.- Returns:
- The content type.
-
inferContentType
@ContentType public static int inferContentType(Uri uri)
Makes a best guess to infer theC.ContentType
from aUri
.- Parameters:
uri
- TheUri
.- Returns:
- The content type.
-
inferContentType
@ContentType public static int inferContentType(String fileName)
Makes a best guess to infer theC.ContentType
from a file name.- Parameters:
fileName
- Name of the file. It can include the path of the file.- Returns:
- The content type.
-
inferContentTypeForUriAndMimeType
@ContentType public static int inferContentTypeForUriAndMimeType(Uri uri, @Nullable String mimeType)
Makes a best guess to infer theC.ContentType
from aUri
and optional MIME type.- Parameters:
uri
- TheUri
.mimeType
- If MIME type, ornull
.- Returns:
- The content type.
-
getAdaptiveMimeTypeForContentType
@Nullable public static String getAdaptiveMimeTypeForContentType(int contentType)
Returns the MIME type corresponding to the given adaptiveC.ContentType
, ornull
if the content type isC.TYPE_OTHER
.
-
fixSmoothStreamingIsmManifestUri
public static Uri fixSmoothStreamingIsmManifestUri(Uri uri)
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)
Returns the specified millisecond time formatted as a string.- Parameters:
builder
- The builder thatformatter
will 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)
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)
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)
Returns a data URI with the specified MIME type and data.
-
sneakyThrow
public static void sneakyThrow(Throwable t)
A hacky method that always throwst
even ift
is a checked exception, and is not declared to be thrown.
-
recursiveDelete
public static void recursiveDelete(File fileOrDirectory)
Recursively deletes a directory and its content.
-
createTempDirectory
public static File createTempDirectory(Context context, String prefix) throws IOException
Creates an empty directory in the directory returned byContext.getCacheDir()
.- Throws:
IOException
-
createTempFile
public static File createTempFile(Context context, String prefix) throws IOException
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)
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)
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)
Compressesinput
using gzip and returns the result in a newly allocated byte array.
-
getBigEndianInt
public static int getBigEndianInt(ByteBuffer buffer, int index)
Absolute get method for reading an int value inByteOrder.BIG_ENDIAN
in aByteBuffer
. Same asByteBuffer.getInt(int)
except the buffer's order as returned byByteBuffer.order()
is ignored andByteOrder.BIG_ENDIAN
is 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)
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()
Returns a non-empty array of normalized IETF BCP 47 language tags for the system languages ordered by preference.
-
getDefaultDisplayLocale
public static Locale getDefaultDisplayLocale()
-
inflate
public static boolean inflate(ParsableByteArray input, ParsableByteArray output, @Nullable Inflater inflater)
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.data
isn't big enough to hold the uncompressed data, a new array is created. Iftrue
is 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 newInflater
is created.- Returns:
- Whether the input is uncompressed successfully.
-
isTv
public static boolean isTv(Context context)
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)
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)
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 aSurfaceView
using 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)
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 aSurfaceView
using 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)
Returns a string representation of aC.TrackType
.- Parameters:
trackType
- AC.TrackType
constant,- Returns:
- A string representation of this constant.
-
getNowUnixTimeMs
public static long getNowUnixTimeMs(long elapsedRealtimeEpochOffsetMs)
Returns the current time in milliseconds since the epoch.- Parameters:
elapsedRealtimeEpochOffsetMs
- The offset betweenSystemClock.elapsedRealtime()
and the time since the Unix epoch, orC.TIME_UNSET
if 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)
Moves the elements starting atfromIndex
tonewFromIndex
.- 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)
Returns whether the table exists in the database.
-
getErrorCodeFromPlatformDiagnosticsInfo
public static int getErrorCodeFromPlatformDiagnosticsInfo(@Nullable String diagnosticsInfo)
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.
-
getFormatSupportString
public static String getFormatSupportString(@FormatSupport int formatSupport)
Returns string representation of aC.FormatSupport
flag.- Parameters:
formatSupport
- AC.FormatSupport
flag.- Returns:
- A string representation of the flag.
-
-