public final class Util extends Object
| Modifier and Type | Field | Description |
|---|---|---|
static String |
DEVICE |
Like
Build.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 |
Like
Build.MANUFACTURER, but in a place where it can be conveniently overridden for
local testing. |
static String |
MODEL |
Like
Build.MODEL, but in a place where it can be conveniently overridden for local
testing. |
static int |
SDK_INT |
Like
Build.VERSION.SDK_INT, but in a place where it can be conveniently
overridden for local testing. |
| 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 for
Object.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 in
array that is greater than (or optionally
equal to) a specified value. |
static int |
binarySearchCeil(long[] array,
long value,
boolean inclusive,
boolean stayInBounds) |
Returns the index of the smallest element in
array that is greater than (or optionally
equal to) a specified value. |
static <T extends Comparable<? super T>> |
binarySearchCeil(List<? extends Comparable<? super T>> list,
T value,
boolean inclusive,
boolean stayInBounds) |
Returns the index of the smallest element in
list 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 in
array that is less than (or optionally
equal to) a specified value. |
static int |
binarySearchFloor(long[] array,
long value,
boolean inclusive,
boolean stayInBounds) |
Returns the index of the largest element in
array that is less than (or optionally
equal to) a specified value. |
static int |
binarySearchFloor(LongArray longArray,
long value,
boolean inclusive,
boolean stayInBounds) |
Returns the index of the largest element in
longArray that is less than (or optionally
equal to) a specified value. |
static <T extends Comparable<? super T>> |
binarySearchFloor(List<? extends Comparable<? super T>> list,
T value,
boolean inclusive,
boolean stayInBounds) |
Returns the index of the largest element in
list that is less than (or optionally equal
to) a specified value. |
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 a
numerator by a denominator, returning the ceiled result. |
static long |
ceilDivide(long numerator,
long denominator) |
Divides a
numerator by a denominator, 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(DataSource dataSource) |
Closes a
DataSource, suppressing any IOException that may occur. |
static void |
closeQuietly(Closeable closeable) |
Closes a
Closeable, suppressing any IOException that may occur. |
static int |
compareLong(long left,
long right) |
Compares two long values and returns the same value as
Long.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 by
Context.getCacheDir(). |
static File |
createTempFile(Context context,
String prefix) |
Creates a new empty file in the directory returned by
Context.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 using
Locale.US. |
static String |
fromUtf8Bytes(byte[] bytes) |
Returns a new
String constructed by decoding UTF-8 encoded bytes. |
static String |
fromUtf8Bytes(byte[] bytes,
int offset,
int length) |
Returns a new
String constructed by decoding UTF-8 encoded bytes in a subarray. |
static String |
getAdaptiveMimeTypeForContentType(int contentType) |
Returns the MIME type corresponding to the given adaptive
C.ContentType, or null
if the content type is C.TYPE_OTHER. |
static int |
getAudioContentTypeForStreamType(int streamType) |
Returns the
C.AudioContentType corresponding to the specified C.StreamType. |
static int |
getAudioTrackChannelConfig(int channelCount) |
Returns the audio track channel configuration for the given channel count, or
AudioFormat.CHANNEL_INVALID if output is not possible. |
static int |
getAudioUsageForStreamType(int streamType) |
Returns the
C.AudioUsage corresponding to the specified C.StreamType. |
static int |
getBigEndianInt(ByteBuffer buffer,
int index) |
Absolute get method for reading an int value in
ByteOrder.BIG_ENDIAN in a ByteBuffer. |
static byte[] |
getBytesFromHexString(String hexString) |
Returns a byte array containing values parsed from the hex string provided.
|
static int |
getCodecCountOfType(String codecs,
int trackType) |
Returns the number of codec strings in
codecs whose type matches trackType. |
static String |
getCodecsOfType(String codecs,
int trackType) |
Returns a copy of
codecs without the codecs whose track type doesn't match
trackType. |
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 UUID |
getDrmUuid(String drmScheme) |
Derives a DRM
UUID from drmScheme. |
static int |
getIntegerCodeForString(String string) |
Returns the integer equal to the big-endian concatenation of the characters in
string
as bytes. |
static String |
getLocaleLanguageTag(Locale locale) |
Returns the language tag for a
Locale. |
static long |
getMediaDurationForPlayoutDuration(long playoutDuration,
float speed) |
Returns the duration of media that will elapse in
playoutDuration. |
static int |
getNetworkType(Context context) |
Returns the
C.NetworkType of the current network connection. |
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 PCM
Format with the specified parameters. |
static int |
getPcmFrameSize(int pcmEncoding,
int channelCount) |
Returns the frame size for audio with
channelCount channels in the specified encoding. |
static long |
getPlayoutDurationForMediaDuration(long mediaDuration,
float speed) |
Returns the playout duration of
mediaDuration of media. |
static int |
getStreamTypeForAudioUsage(int usage) |
Returns the
C.StreamType corresponding to the specified C.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(int trackType) |
Returns a string representation of a
TRACK_TYPE_* constant defined in C. |
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 a
String encoded using UTF-8. |
static byte[] |
gzip(byte[] input) |
Compresses
input using gzip and returns the result in a newly allocated byte array. |
static int |
inferContentType(Uri uri) |
Makes a best guess to infer the
C.ContentType from a Uri. |
static int |
inferContentType(Uri uri,
String overrideExtension) |
Makes a best guess to infer the
C.ContentType from a Uri. |
static int |
inferContentType(String fileName) |
Makes a best guess to infer the
C.ContentType from a file name. |
static int |
inferContentTypeForUriAndMimeType(Uri uri,
String mimeType) |
Makes a best guess to infer the
C.ContentType from a Uri and optional MIME type. |
static boolean |
inflate(ParsableByteArray input,
ParsableByteArray output,
Inflater inflater) |
Uncompresses the data in
input. |
static boolean |
isEncodingHighResolutionPcm(int encoding) |
Returns whether
encoding is high resolution (> 16-bit) PCM. |
static boolean |
isEncodingLinearPcm(int encoding) |
Returns whether
encoding 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 of
value in array, or C.INDEX_UNSET if value is not contained in array. |
static int |
linearSearch(long[] array,
long value) |
Returns the index of the first occurrence of
value in array, or C.INDEX_UNSET if value is not contained in array. |
static boolean |
maybeRequestReadExternalStoragePermission(Activity activity,
Uri... uris) |
Checks whether it's necessary to request the
Manifest.permission.READ_EXTERNAL_STORAGE
permission read the specified Uris, requesting the permission if necessary. |
static boolean |
maybeRequestReadExternalStoragePermission(Activity activity,
MediaItem... mediaItems) |
Checks whether it's necessary to request the
Manifest.permission.READ_EXTERNAL_STORAGE
permission for the specified media items, requesting the permission if
necessary. |
static long |
minValue(SparseLongArray sparseLongArray) |
Returns the minimum value in the given
SparseLongArray. |
static <T> void |
moveItems(List<T> items,
int fromIndex,
int toIndex,
int newFromIndex) |
Moves the elements starting at
fromIndex to newFromIndex. |
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 for
language. |
static <T> T[] |
nullSafeArrayAppend(T[] original,
T newElement) |
Creates a new array containing
original with newElement 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 of
list into array. |
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 a
Parcel and interprets it as a boolean, with 0 mapping to false
and all other values mapping to true. |
static byte[] |
readExactly(DataSource dataSource,
int length) |
Reads
length bytes from the specified opened DataSource, and returns a byte
array containing the read data. |
static byte[] |
readToEnd(DataSource dataSource) |
Reads data from the specified opened
DataSource until it ends, and returns a byte array
containing the read data. |
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) |
Applies
scaleLargeTimestamp(long, long, long) to a list of unscaled timestamps. |
static void |
scaleLargeTimestampsInPlace(long[] timestamps,
long multiplier,
long divisor) |
Applies
scaleLargeTimestamp(long, long, long) to an array of unscaled timestamps. |
static void |
sneakyThrow(Throwable t) |
A hacky method that always throws
t even if t is a checked exception,
and is not declared to be thrown. |
static String[] |
split(String value,
String regex) |
Splits a string using
value.split(regex, -1). |
static String[] |
splitAtFirst(String value,
String regex) |
Splits the string at the first occurrence of the delimiter
regex. |
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) |
Calls
Context.startForegroundService(Intent) if SDK_INT is 26 or higher, or
Context.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 an
InputStream 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) |
Return the long that is composed of the bits of the 2 specified integers.
|
static @PolyNull String |
toLowerInvariant(@PolyNull String text) |
Converts text to lower case using
Locale.US. |
static long |
toUnsignedLong(int x) |
Converts an integer to a long by unsigned conversion.
|
static @PolyNull String |
toUpperInvariant(@PolyNull String text) |
Converts text to upper case using
Locale.US. |
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 void |
writeBoolean(Parcel parcel,
boolean value) |
Writes a boolean to a
Parcel. |
public static final int SDK_INT
Build.VERSION.SDK_INT, but in a place where it can be conveniently
overridden for local testing.public static final String DEVICE
Build.DEVICE, but in a place where it can be conveniently overridden for local
testing.public static final String MANUFACTURER
Build.MANUFACTURER, but in a place where it can be conveniently overridden for
local testing.public static final String MODEL
Build.MODEL, but in a place where it can be conveniently overridden for local
testing.public static final String DEVICE_DEBUG_INFO
public static final byte[] EMPTY_BYTE_ARRAY
public static byte[] toByteArray(InputStream inputStream) throws IOException
InputStream to a byte array.inputStream - the InputStream to be read. The input stream is not closed by this
method.IOException - if an error occurs reading from the stream.@Nullable public static ComponentName startForegroundService(Context context, Intent intent)
Context.startForegroundService(Intent) if SDK_INT is 26 or higher, or
Context.startService(Intent) otherwise.context - The context to call.intent - The intent to pass to the called method.public static boolean maybeRequestReadExternalStoragePermission(Activity activity, Uri... uris)
Manifest.permission.READ_EXTERNAL_STORAGE
permission read the specified Uris, requesting the permission if necessary.activity - The host activity for checking and requesting the permission.uris - Uris that may require Manifest.permission.READ_EXTERNAL_STORAGE to read.public static boolean maybeRequestReadExternalStoragePermission(Activity activity, MediaItem... mediaItems)
Manifest.permission.READ_EXTERNAL_STORAGE
permission for the specified media items, requesting the permission if
necessary.activity - The host activity for checking and requesting the permission.mediaItems - Media itemss that may require Manifest.permission.READ_EXTERNAL_STORAGE to read.public static boolean checkCleartextTrafficPermitted(MediaItem... mediaItems)
mediaItems - A list of media items.public static boolean isLocalFileUri(Uri uri)
uri - The uri to test.public static boolean areEqual(@Nullable
Object o1,
@Nullable
Object o2)
Object.equals(Object) equality, handling the case where one or
both may be null.o1 - The first object.o2 - The second object.o1 == null ? o2 == null : o1.equals(o2).public static boolean contains(@NullableType Object[] items, @Nullable Object item)
items array contains an object equal to item, according to
Object.equals(Object).
If item is null then true is returned if and only if items contains null.
items - The array of items to search.item - The item to search for.public static <T> void removeRange(List<T> list, int fromIndex, int toIndex)
Does nothing if the provided range is valid and fromIndex == toIndex.
list - The List to remove the range from.fromIndex - The first index to be removed (inclusive).toIndex - The last index to be removed (exclusive).IllegalArgumentException - If fromIndex < 0, toIndex >
list.size(), or fromIndex > toIndex.@EnsuresNonNull("#1")
public static <T> T castNonNull(@Nullable
T value)
Use Assertions.checkNotNull(Object) to throw if the value is null.
@EnsuresNonNull("#1")
public static <T> T[] castNonNullTypeArray(@NullableType T[] value)
public static <T> T[] nullSafeArrayCopy(T[] input,
int length)
Arrays.copyOf(Object[], int) by ensuring the new length does not exceed the current length.input - The input array.length - The output array length. Must be less or equal to the length of the input array.public static <T> T[] nullSafeArrayCopyOfRange(T[] input,
int from,
int to)
input - The input array.from - The start the range to be copied, inclusiveto - The end of the range to be copied, exclusive.public static <T> T[] nullSafeArrayAppend(T[] original,
T newElement)
original with newElement appended.original - The input array.newElement - The element to append.public static <T> T[] nullSafeArrayConcatenation(T[] first,
T[] second)
first - The first array.second - The second array.public static <T> void nullSafeListToArray(List<T> list, T[] array)
list into array.
list.size() must be the same as array.length to ensure the contents can be
copied into array without leaving any nulls at the end.
list - The list to copy items from.array - The array to copy items to.public static Handler createHandlerForCurrentLooper()
IllegalStateException - If the current thread doesn't have a Looper.public static Handler createHandlerForCurrentLooper(@Nullable @UnknownInitialization Handler.Callback callback)
Handler with the specified Handler.Callback on the current Looper 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.
callback - A Handler.Callback. May be a partially initialized class, or null if no
callback is required.Handler with the specified callback on the current Looper thread.IllegalStateException - If the current thread doesn't have a Looper.public static Handler createHandlerForCurrentOrMainLooper()
public static Handler createHandlerForCurrentOrMainLooper(@Nullable @UnknownInitialization Handler.Callback callback)
Handler with the specified Handler.Callback on the current Looper 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 thread Looper is used.
callback - A Handler.Callback. May be a partially initialized class, or null if no
callback is required.Handler with the specified callback on the current Looper thread.public static Handler createHandler(Looper looper, @Nullable @UnknownInitialization Handler.Callback callback)
Handler with the specified Handler.Callback on the specified Looper 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.
looper - A Looper to run the callback on.callback - A Handler.Callback. May be a partially initialized class, or null if no
callback is required.Handler with the specified callback on the current Looper thread.public static Looper getCurrentOrMainLooper()
public static ExecutorService newSingleThreadExecutor(String threadName)
threadName - The name of the thread.public static byte[] readToEnd(DataSource dataSource) throws IOException
DataSource until it ends, and returns a byte array
containing the read data.dataSource - The source from which to read.IOException - If an error occurs reading from the source.public static byte[] readExactly(DataSource dataSource, int length) throws IOException
length bytes from the specified opened DataSource, and returns a byte
array containing the read data.dataSource - The source from which to read.IOException - If an error occurs reading from the source.IllegalStateException - If the end of the source was reached before length bytes
could be read.public static void closeQuietly(@Nullable
DataSource dataSource)
DataSource, suppressing any IOException that may occur.dataSource - The DataSource to close.public static void closeQuietly(@Nullable
Closeable closeable)
Closeable, suppressing any IOException that may occur. Both OutputStream and InputStream are Closeable.closeable - The Closeable to close.public static boolean readBoolean(Parcel parcel)
Parcel and interprets it as a boolean, with 0 mapping to false
and all other values mapping to true.parcel - The Parcel to read from.public static void writeBoolean(Parcel parcel, boolean value)
Parcel. The boolean is written as an integer with value 1 (true)
or 0 (false).parcel - The Parcel to write to.value - The value to write.public static String getLocaleLanguageTag(Locale locale)
Locale.
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.
locale - A Locale.public static @PolyNull String normalizeLanguageCode(@PolyNull String language)
language.language - A case-insensitive language code supported by Locale.forLanguageTag(String).
language.toLowerCase() if the language could not be normalized.public static String fromUtf8Bytes(byte[] bytes)
String constructed by decoding UTF-8 encoded bytes.bytes - The UTF-8 encoded bytes to decode.public static String fromUtf8Bytes(byte[] bytes, int offset, int length)
String constructed by decoding UTF-8 encoded bytes in a subarray.bytes - The UTF-8 encoded bytes to decode.offset - The index of the first byte to decode.length - The number of bytes to decode.public static byte[] getUtf8Bytes(String value)
String encoded using UTF-8.value - The String whose bytes should be obtained.public static String[] split(String value, String regex)
value.split(regex, -1). Note: this is is similar to String.split(String) but empty matches at the end of the string will not be omitted from the
returned array.value - The string to split.regex - A delimiting regular expression.public static String[] splitAtFirst(String value, String regex)
regex. 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.value - The string.regex - A delimiting regular expression.public static boolean isLinebreak(int c)
c - The character.public static @PolyNull String toLowerInvariant(@PolyNull String text)
Locale.US.text - The text to convert.text is null.public static @PolyNull String toUpperInvariant(@PolyNull String text)
Locale.US.text - The text to convert.text is null.public static String formatInvariant(String format, Object... args)
Locale.US.String.format(String, Object...)public static int ceilDivide(int numerator,
int denominator)
numerator by a denominator, returning the ceiled result.numerator - The numerator to divide.denominator - The denominator to divide by.public static long ceilDivide(long numerator,
long denominator)
numerator by a denominator, returning the ceiled result.numerator - The numerator to divide.denominator - The denominator to divide by.public static int constrainValue(int value,
int min,
int max)
value - The value to constrain.min - The lower bound.max - The upper bound.Math.max(min, Math.min(value, max)).public static long constrainValue(long value,
long min,
long max)
value - The value to constrain.min - The lower bound.max - The upper bound.Math.max(min, Math.min(value, max)).public static float constrainValue(float value,
float min,
float max)
value - The value to constrain.min - The lower bound.max - The upper bound.Math.max(min, Math.min(value, max)).public static long addWithOverflowDefault(long x,
long y,
long overflowResult)
x - The first value.y - The second value.overflowResult - The return value if x + y overflows.x + y, or overflowResult if the result overflows.public static long subtractWithOverflowDefault(long x,
long y,
long overflowResult)
x - The first value.y - The second value.overflowResult - The return value if x - y overflows.x - y, or overflowResult if the result overflows.public static int linearSearch(int[] array,
int value)
value in array, or C.INDEX_UNSET if value is not contained in array.array - The array to search.value - The value to search for.array, or C.INDEX_UNSET
if value is not contained in array.public static int linearSearch(long[] array,
long value)
value in array, or C.INDEX_UNSET if value is not contained in array.array - The array to search.value - The value to search for.array, or C.INDEX_UNSET
if value is not contained in array.public static int binarySearchFloor(int[] array,
int value,
boolean inclusive,
boolean stayInBounds)
array that is less than (or optionally
equal to) a specified value.
The search is performed using a binary search algorithm, so the array must be sorted. If the
array contains multiple elements equal to value and inclusive is true, the
index of the first one will be returned.
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.array that is less than (or optionally
equal to) value.public static int binarySearchFloor(long[] array,
long value,
boolean inclusive,
boolean stayInBounds)
array that is less than (or optionally
equal to) a specified value.
The search is performed using a binary search algorithm, so the array must be sorted. If the
array contains multiple elements equal to value and inclusive is true, the
index of the first one will be returned.
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.array that is less than (or optionally
equal to) value.public static <T extends Comparable<? super T>> int binarySearchFloor(List<? extends Comparable<? super T>> list, T value, boolean inclusive, boolean stayInBounds)
list that is less 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 and inclusive is true, the index
of the first one will be returned.
T - The type of values being searched.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.list that is less than (or optionally equal
to) value.public static int binarySearchFloor(LongArray longArray, long value, boolean inclusive, boolean stayInBounds)
longArray that is less than (or optionally
equal to) a specified value.
The search is performed using a binary search algorithm, so the array must be sorted. If the
array contains multiple elements equal to value and inclusive is true, the
index of the first one will be returned.
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.array that is less than (or optionally
equal to) value.public static int binarySearchCeil(int[] array,
int value,
boolean inclusive,
boolean stayInBounds)
array that is greater than (or optionally
equal to) a specified value.
The search is performed using a binary search algorithm, so the array must be sorted. If the
array contains multiple elements equal to value and inclusive is true, the
index of the last one will be returned.
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 then a.length will
be returned.array that is greater than (or optionally
equal to) value.public static int binarySearchCeil(long[] array,
long value,
boolean inclusive,
boolean stayInBounds)
array that is greater than (or optionally
equal to) a specified value.
The search is performed using a binary search algorithm, so the array must be sorted. If the
array contains multiple elements equal to value and inclusive is true, the
index of the last one will be returned.
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 then a.length will
be returned.array that is greater than (or optionally
equal to) value.public static <T extends Comparable<? super T>> int binarySearchCeil(List<? extends Comparable<? super T>> list, T value, boolean inclusive, boolean stayInBounds)
list 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 and inclusive is true, the index
of the last one will be returned.
T - The type of values being searched.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 then
list.size() will be returned.list that is greater than (or optionally
equal to) value.public static int compareLong(long left,
long right)
Long.compare(long, long).left - The left operand.right - The right operand.public static long minValue(SparseLongArray sparseLongArray)
SparseLongArray.sparseLongArray - The SparseLongArray.NoSuchElementException - If the array is empty.public static long parseXsDuration(String value)
value - The attribute value to decode.public static long parseXsDateTime(String value) throws ParserException
value - The attribute value to decode.ParserException - if an error occurs parsing the dateTime attribute value.public static long scaleLargeTimestamp(long timestamp,
long multiplier,
long divisor)
Logically, scaling consists of a multiplication followed by a division. The actual operations performed are designed to minimize the probability of overflow.
timestamp - The timestamp to scale.multiplier - The multiplier.divisor - The divisor.public static long[] scaleLargeTimestamps(List<Long> timestamps, long multiplier, long divisor)
scaleLargeTimestamp(long, long, long) to a list of unscaled timestamps.timestamps - The timestamps to scale.multiplier - The multiplier.divisor - The divisor.public static void scaleLargeTimestampsInPlace(long[] timestamps,
long multiplier,
long divisor)
scaleLargeTimestamp(long, long, long) to an array of unscaled timestamps.timestamps - The timestamps to scale.multiplier - The multiplier.divisor - The divisor.public static long getMediaDurationForPlayoutDuration(long playoutDuration,
float speed)
playoutDuration.playoutDuration - The duration to scale.speed - The factor by which playback is sped up.playoutDuration.public static long getPlayoutDurationForMediaDuration(long mediaDuration,
float speed)
mediaDuration of media.mediaDuration - The duration to scale.mediaDuration.public static int getIntegerCodeForString(String string)
string
as bytes. The string must be no more than four characters long.string - A string no more than four characters long.public static long toUnsignedLong(int x)
This method is equivalent to Integer.toUnsignedLong(int) for API 26+.
public static long toLong(int mostSignificantBits,
int leastSignificantBits)
mostSignificantBits - The 32 most significant bits of the long to return.leastSignificantBits - The 32 least significant bits of the long to return.mostSignificantBits bits and its
32 least significant bits are leastSignificantBits.public static CharSequence truncateAscii(CharSequence sequence, int maxLength)
This preserves span styling in the CharSequence. If that's not important, use Ascii.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.
sequence - The character sequence to truncate.maxLength - The max length to truncate to.sequence directly if sequence.length() <= maxLength, otherwise
sequence.subsequence(0, maxLength.public static byte[] getBytesFromHexString(String hexString)
hexString - The hex string to convert to bytes.public static String toHexString(byte[] bytes)
bytes - The byte data to convert to hex.bytes.public static String getCommaDelimitedSimpleClassNames(Object[] objects)
objects - The objects whose simple class names should be comma delimited and returned.public static String getUserAgent(Context context, String applicationName)
context - A valid context of the calling application.applicationName - String that will be prefix'ed to the generated user agent.public static int getCodecCountOfType(@Nullable
String codecs,
int trackType)
codecs whose type matches trackType.@Nullable public static String getCodecsOfType(@Nullable String codecs, int trackType)
codecs without the codecs whose track type doesn't match
trackType.codecs - A codec sequence string, as defined in RFC 6381.trackType - One of C.TRACK_TYPE_*.codecs without the codecs whose track type doesn't match
trackType. If this ends up empty, or codecs is null, return null.public static String[] splitCodecs(@Nullable String codecs)
codecs - A codec sequence string, as defined in RFC 6381.public static Format getPcmFormat(@PcmEncoding int pcmEncoding, int channels, int sampleRate)
Format with the specified parameters.pcmEncoding - The C.PcmEncoding.channels - The number of channels, or Format.NO_VALUE if unknown.sampleRate - The sample rate in Hz, or Format.NO_VALUE if unknown.@PcmEncoding public static int getPcmEncoding(int bitDepth)
bitDepth - The bit depth. Supported values are 8, 16, 24 and 32.C.ENCODING_PCM_8BIT, C.ENCODING_PCM_16BIT, C.ENCODING_PCM_24BIT and C.ENCODING_PCM_32BIT. If
the bit depth is unsupported then C.ENCODING_INVALID is returned.public static boolean isEncodingLinearPcm(@Encoding int encoding)
encoding is one of the linear PCM encodings.encoding - The encoding of the audio data.public static boolean isEncodingHighResolutionPcm(@PcmEncoding int encoding)
encoding is high resolution (> 16-bit) PCM.encoding - The encoding of the audio data.public static int getAudioTrackChannelConfig(int channelCount)
AudioFormat.CHANNEL_INVALID if output is not possible.channelCount - The number of channels in the input audio.AudioFormat.CHANNEL_INVALID if output is not
possible.public static int getPcmFrameSize(@PcmEncoding int pcmEncoding, int channelCount)
channelCount channels in the specified encoding.pcmEncoding - The encoding of the audio data.channelCount - The channel count.@AudioUsage public static int getAudioUsageForStreamType(@StreamType int streamType)
C.AudioUsage corresponding to the specified C.StreamType.@AudioContentType public static int getAudioContentTypeForStreamType(@StreamType int streamType)
C.AudioContentType corresponding to the specified C.StreamType.@StreamType public static int getStreamTypeForAudioUsage(@AudioUsage int usage)
C.StreamType corresponding to the specified C.AudioUsage.@Nullable public static UUID getDrmUuid(String drmScheme)
UUID from drmScheme.drmScheme - A UUID string, or "widevine", "playready" or
"clearkey".UUID, or null if one could not be derived.@ContentType public static int inferContentType(Uri uri, @Nullable String overrideExtension)
C.ContentType from a Uri.uri - The Uri.overrideExtension - If not null, used to infer the type.@ContentType public static int inferContentType(Uri uri)
C.ContentType from a Uri.uri - The Uri.@ContentType public static int inferContentType(String fileName)
C.ContentType from a file name.fileName - Name of the file. It can include the path of the file.@ContentType public static int inferContentTypeForUriAndMimeType(Uri uri, @Nullable String mimeType)
C.ContentType from a Uri and optional MIME type.uri - The Uri.mimeType - If MIME type, or null.@Nullable public static String getAdaptiveMimeTypeForContentType(int contentType)
C.ContentType, or null
if the content type is C.TYPE_OTHER.public static Uri fixSmoothStreamingIsmManifestUri(Uri uri)
uri - The original URI.public static String getStringForTime(StringBuilder builder, Formatter formatter, long timeMs)
builder - The builder that formatter will write to.formatter - The formatter.timeMs - The time to format as a string, in milliseconds.public static String escapeFileName(String fileName)
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.
fileName - File name to be escaped.@Nullable public static String unescapeFileName(String fileName)
See escapeFileName(String) for more information.
fileName - File name to be unescaped.public static Uri getDataUriForString(String mimeType, String data)
public static void sneakyThrow(Throwable t)
t even if t is a checked exception,
and is not declared to be thrown.public static void recursiveDelete(File fileOrDirectory)
public static File createTempDirectory(Context context, String prefix) throws IOException
Context.getCacheDir().IOExceptionpublic static File createTempFile(Context context, String prefix) throws IOException
Context.getCacheDir().IOExceptionpublic static int crc32(byte[] bytes,
int start,
int end,
int initialValue)
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.public static int crc8(byte[] bytes,
int start,
int end,
int initialValue)
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.public static byte[] gzip(byte[] input)
input using gzip and returns the result in a newly allocated byte array.public static int getBigEndianInt(ByteBuffer buffer, int index)
ByteOrder.BIG_ENDIAN in a ByteBuffer. Same as ByteBuffer.getInt(int) except the buffer's order as returned by
ByteBuffer.order() is ignored and ByteOrder.BIG_ENDIAN is used instead.buffer - The buffer from which to read an int in big endian.index - The index from which the bytes will be read.@NetworkType public static int getNetworkType(Context context)
C.NetworkType of the current network connection.context - A context to access the connectivity manager.C.NetworkType of the current network connection.public static String getCountryCode(@Nullable Context context)
context - A context to access the telephony service. If null, only the Locale can be used.public static String[] getSystemLanguageCodes()
public static boolean inflate(ParsableByteArray input, ParsableByteArray output, @Nullable Inflater inflater)
input.input - Wraps the compressed input data.output - Wraps an output buffer to be used to store the uncompressed data. If
output.data isn't big enough to hold the uncompressed data, a new array is created. If
true 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 new Inflater
is created.public static boolean isTv(Context context)
context - Any context.public static Point getCurrentDisplayModeSize(Context context)
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 a SurfaceView using full size buffers.
context - Any context.public static Point getCurrentDisplayModeSize(Context context, Display display)
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 a SurfaceView using full size buffers.
context - Any context.display - The display whose size is to be returned.public static String getTrackTypeString(int trackType)
TRACK_TYPE_* constant defined in C.trackType - A TRACK_TYPE_* constant,public static long getNowUnixTimeMs(long elapsedRealtimeEpochOffsetMs)
elapsedRealtimeEpochOffsetMs - The offset between SystemClock.elapsedRealtime()
and the time since the Unix epoch, or C.TIME_UNSET if unknown.public static <T> void moveItems(List<T> items, int fromIndex, int toIndex, int newFromIndex)
fromIndex to newFromIndex.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.public static boolean tableExists(SQLiteDatabase database, String tableName)