Util
public final class Util
Miscellaneous utility methods.
Summary
Constants |
|
|---|---|
static final String |
This field is deprecated. Use |
static final String |
A concise description of the device that it can be useful to log for debugging purposes. |
static final byte[] |
An empty byte array. |
static final long[] |
An empty long array. |
static final String |
This field is deprecated. Use |
static final String |
This field is deprecated. Use |
static final int |
This field is deprecated. Use |
Public methods |
|
|---|---|
static long |
@UnstableApiReturns the sum of two arguments, or a third argument if the result overflows. |
static boolean |
@UnstableApiThis method is deprecated. Use |
static int |
@UnstableApiReturns the index of the smallest element in |
static int |
@UnstableApiReturns the index of the smallest element in |
static int |
@UnstableApiReturns the index of the smallest element in |
static int |
@UnstableApiReturns the index of the largest element in |
static int |
@UnstableApiReturns the index of the largest element in |
static int |
@UnstableApiReturns the index of the largest element in |
static int |
@UnstableApiReturns the index of the largest element in |
static T |
@UnstableApiCasts a nullable variable to a non-null variable without runtime null check. |
static T[] |
@UnstableApiCasts a nullable type array to a non-null type array without runtime null check. |
static int |
@UnstableApiDivides a |
static long |
@UnstableApiDivides a |
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 |
@UnstableApiCloses a |
static int |
@UnstableApiThis method is deprecated. Use |
static float |
@UnstableApiConstrains a value to the specified bounds. |
static int |
@UnstableApiConstrains a value to the specified bounds. |
static long |
@UnstableApiConstrains a value to the specified bounds. |
static boolean |
@UnstableApiTests whether an |
static boolean |
@UnstableApiTests whether a |
static boolean |
@UnstableApiTests two |
static int |
@UnstableApiReturns a hash code value for the contents of this |
static int |
@UnstableApiReturns the result of updating a CRC-16 with the specified bytes in a "most significant bit first" order. |
static int |
@UnstableApiReturns the result of updating a CRC-32 with the specified bytes in a "most significant bit first" order. |
static int |
@UnstableApiReturns the result of updating a CRC-8 with the specified bytes in a "most significant bit first" order. |
static Handler |
@UnstableApiCreates a |
static Handler |
|
static Handler |
@UnstableApiCreates a |
static Handler |
|
static Handler |
@UnstableApiCreates a |
static ByteBuffer |
@UnstableApiReturns a read-only view of the given |
static File |
@UnstableApiCreates an empty directory in the directory returned by |
static File |
@UnstableApiCreates a new empty file in the directory returned by |
static long |
@UnstableApiReturns the number of samples required to represent |
static String |
@UnstableApiEscapes a string so that it's safe for use as a file or directory name on at least FAT32 filesystems. |
static 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 |
@UnstableApiFormats a string using |
static String |
@UnstableApiReturns a new |
static String |
@UnstableApiReturns a new |
static int |
@UnstableApiReturns a newly generated audio session identifier, or |
static @Nullable String |
getAdaptiveMimeTypeForContentType(@C.ContentType int contentType)Returns the MIME type corresponding to the given adaptive |
static int |
@UnstableApiRetrieves the API Level that |
static int |
@UnstableApiThis method is deprecated. This method is no longer used by the media3 library, it does not work well and should be avoided. |
static AudioFormat |
@UnstableApiCreates |
static int |
@UnstableApiReturns the audio track channel configuration for the given channel count, or |
static int |
@UnstableApiReturns the |
static String |
@UnstableApiReturns a string representation of the |
static Player.Commands |
@UnstableApi |
static int |
@UnstableApiAbsolute get method for reading an int value in |
static int |
@UnstableApiReturns |
static int |
@UnstableApiReturns the byte depth for audio with the specified encoding. |
static byte[] |
@UnstableApiReturns a byte array containing values parsed from the hex string provided. |
static int |
@UnstableApiReturns the number of codec strings in |
static @Nullable String |
@UnstableApiReturns a copy of |
static @Nullable String |
@UnstableApiReturns a copy of |
static String |
@UnstableApiReturns 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 |
@UnstableApiGets the size of the current mode of the default display, in pixels. |
static Point |
@UnstableApiGets the size of the current mode of the specified display, in pixels. |
static Looper |
Returns the |
static Uri |
@UnstableApiReturns a data URI with the specified MIME type and data. |
static Locale |
|
static Drawable |
@UnstableApiReturns a |
static @Nullable UUID |
getDrmUuid(String drmScheme)Derives a DRM |
static int |
@UnstableApiReturns a |
static int |
@UnstableApiAttempts to parse an error code from a diagnostic string found in framework media exceptions. |
static String |
@UnstableApiReturns string representation of a |
static int |
@UnstableApiReturns the sign-extended 24-bit integer value at |
static int |
@UnstableApiReturns the integer equal to the big-endian concatenation of the characters in |
static String |
@UnstableApiReturns the language tag for a |
static int |
Returns the number of maximum pending output frames that are allowed on a |
static long |
@UnstableApiReturns the duration of media that will elapse in |
static long |
@UnstableApiReturns the current time in milliseconds since the epoch. |
static int |
@UnstableApiConverts a sample bit depth to a corresponding little-endian integer PCM encoding constant. |
static int |
@UnstableApiConverts a sample bit depth and byte order to a corresponding integer PCM encoding constant. |
static Format |
@UnstableApiGets a PCM |
static Format |
@UnstableApiGets a PCM |
static int |
@UnstableApiReturns the frame size for audio with |
static long |
@UnstableApiReturns the playout duration of |
static List<String> |
@UnstableApiReturns a list of strings representing the |
static List<String> |
@UnstableApiReturns a list of strings representing the |
static int |
This method is deprecated. Use |
static String |
@UnstableApiReturns the specified millisecond time formatted as a string. |
static String |
@UnstableApiReturns the specified millisecond time formatted as a string. |
static String[] |
Returns a non-empty array of normalized IETF BCP 47 language tags for the system languages ordered by preference. |
static String |
@UnstableApiReturns a string representation of a |
static String |
getUserAgent(Context context, String applicationName)Returns a user agent string based on the given application name and the library version. |
static byte[] |
@UnstableApiReturns a new byte array containing the code points of a |
static byte[] |
@UnstableApiCompresses |
static boolean |
handlePauseButtonAction(@Nullable Player player)Updates the player to handle an interaction with a pause button. |
static boolean |
handlePlayButtonAction(@Nullable Player player)Updates the player to handle an interaction with a play button. |
static boolean |
handlePlayPauseButtonAction(@Nullable Player player)Updates the player to handle an interaction with a play or pause button. |
static boolean |
@UnstableApiUpdates the player to handle an interaction with a play or pause button. |
static int |
@UnstableApiThis method is deprecated. Use |
static int |
Makes a best guess to infer the |
static int |
@UnstableApiThis method is deprecated. Use |
static int |
@C.ContentTypeMakes a best guess to infer the |
static int |
@C.ContentTypeMakes a best guess to infer the |
static boolean |
@UnstableApiUncompresses the data in |
static String |
@UnstableApiReturns a string representation of the integer using radix value |
static boolean |
@UnstableApiReturns whether the app is running on an automotive device. |
static boolean |
Returns the image MIME types that can be decoded and loaded by |
static boolean |
@UnstableApiReturns whether |
static boolean |
@UnstableApiReturns whether |
static boolean |
|
static boolean |
@UnstableApiReturns whether the given character is a carriage return ('\r') or a line feed ('\n'). |
static boolean |
@UnstableApiReturns true if the URI is a path to a local file or a reference to a local file. |
static boolean |
Returns true if the code path is currently running on an emulator. |
static boolean |
@UnstableApiReturns whether |
static boolean |
@UnstableApiReturns whether the app is running on a TV device. |
static boolean |
@UnstableApiReturns whether the app is running on a Wear OS device. |
static int |
@UnstableApiReturns the index of the first occurrence of |
static int |
@UnstableApiReturns the index of the first occurrence of |
static String |
@UnstableApiLoads a file from the assets folder. |
static long |
@UnstableApiReturns the maximum value in the given |
static boolean |
@UnstableApiUncompresses the data in |
static boolean |
This method is deprecated. Use |
static boolean |
This method is deprecated. Use |
static boolean |
maybeRequestReadStoragePermission(Checks whether it's necessary to request storage reading permissions for the specified |
static long |
@UnstableApiReturns the minimum value in the given |
static void |
@UnstableApiMoves the elements starting at |
static long |
@UnstableApiConverts a time in milliseconds to the corresponding time in microseconds, preserving |
static ExecutorService |
@UnstableApiInstantiates a new single threaded executor whose thread has the specified name. |
static ScheduledExecutorService |
@UnstableApiInstantiates a new single threaded scheduled executor whose thread has the specified name. |
static @PolyNull String |
@UnstableApiReturns a normalized IETF BCP 47 language tag for |
static T[] |
@UnstableApiCreates a new array containing |
static T[] |
@UnstableApiCreates a new array containing the concatenation of two non-null type arrays. |
static T[] |
@UnstableApiCopies and optionally truncates an array. |
static T[] |
@UnstableApiCopies a subset of an array. |
static void |
@UnstableApiCopies the contents of |
static long |
@UnstableApiParses an xs:dateTime attribute value, returning the parsed timestamp in milliseconds since the epoch. |
static long |
@UnstableApiParses an xs:duration attribute value, returning the parsed duration in milliseconds. |
static float |
@UnstableApiReturns the floating point percentage of |
static int |
@UnstableApiReturns the integer percentage of |
static boolean |
@UnstableApiPosts the |
static boolean |
@UnstableApiPosts the |
static ListenableFuture<T> |
@UnstableApiPosts the |
static void |
@UnstableApiWrites a 24-bit integer value to a buffer at its current |
static boolean |
@UnstableApiReads an integer from a |
static void |
@UnstableApiRecursively deletes a directory and its content. |
static @Nullable Intent |
@UnstableApiRegisters a |
static void |
@UnstableApiRemoves an indexed range from a List. |
static long |
@UnstableApiReturns the total duration (in microseconds) of |
static long |
@UnstableApiScales a large timestamp. |
static long[] |
@UnstableApiApplies |
static void |
@UnstableApiApplies |
static long |
@UnstableApiScales a large value by a multiplier and a divisor. |
static long[] |
@UnstableApiApplies |
static void |
@UnstableApiApplies |
static void |
@UnstableApiSets the notification required for a foreground service. |
static boolean |
@EnsuresNonNullIf(result = true, expression = "#1")Returns whether a play-pause button should be enabled or not. |
static boolean |
@EnsuresNonNullIf(result = false, expression = "#1")Returns whether a play button should be presented on a UI element for playback control. |
static boolean |
@UnstableApiReturns whether a play button should be presented on a UI element for playback control. |
static void |
A hacky method that always throws |
static String[] |
@UnstableApiSplits a string using |
static String[] |
@UnstableApiSplits the string at the first occurrence of the delimiter |
static String[] |
@UnstableApiSplits a codecs sequence string, as defined in RFC 6381, into individual codec strings. |
static @Nullable ComponentName |
@UnstableApiCalls |
static long |
@UnstableApiReturns the difference between two arguments, or a third argument if the result overflows. |
static long |
@UnstableApiReturns the sum of all summands of the given array. |
static boolean |
@UnstableApiReturns whether the table exists in the database. |
static byte[] |
@UnstableApiThis method is deprecated. Use Guava's |
static byte[] |
@UnstableApiConverts a float into an equivalent byte array. |
static byte[] |
@UnstableApiConverts an array of integers into an equivalent byte array. |
static String |
@UnstableApi |
static String |
@UnstableApiReturns a string containing a lower-case hex representation of the bytes provided. |
static long |
@UnstableApiReturns the long that is composed of the bits of the 2 specified integers. |
static long |
@UnstableApiConverts an integer to a long by unsigned conversion. |
static ListenableFuture<T> |
@UnstableApiAsynchronously transforms the result of a |
static @Nullable String |
@UnstableApiUnescapes an escaped file or directory name back to its original value. |
static long |
@UnstableApiConverts a time in microseconds to the corresponding time in milliseconds, preserving |
static void |
@UnstableApiWrites a boolean to a |
Constants
DEVICE_DEBUG_INFO
@UnstableApi
public static final String DEVICE_DEBUG_INFO
A concise description of the device that it can be useful to log for debugging purposes.
Public methods
addWithOverflowDefault
@UnstableApi
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 | |
|---|---|
long x |
The first value. |
long y |
The second value. |
long overflowResult |
The return value if |
| Returns | |
|---|---|
long |
|
areEqual
@UnstableApi
@InlineMe(replacement = "Objects.equals(o1, o2)", imports = [""java.util.Objects""])
public static booleanareEqual(@Nullable Object o1, @Nullable Object o2)
binarySearchCeil
@UnstableApi
public 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.
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.
| Parameters | |
|---|---|
int[] array |
The array to search. |
int value |
The value being searched for. |
boolean 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. |
boolean stayInBounds |
If true, then |
| Returns | |
|---|---|
int |
The index of the smallest element in |
binarySearchCeil
@UnstableApi
public 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.
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.
| Parameters | |
|---|---|
long[] array |
The array to search. |
long value |
The value being searched for. |
boolean 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. |
boolean stayInBounds |
If true, then |
| Returns | |
|---|---|
int |
The index of the smallest element in |
binarySearchCeil
@UnstableApi
public static int <T extends Comparable<T>> binarySearchCeil(
List<Comparable<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.
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.
| Parameters | |
|---|---|
<T extends Comparable<T>> |
The type of values being searched. |
List<Comparable<T>> list |
The list to search. |
T value |
The value being searched for. |
boolean 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. |
boolean stayInBounds |
If true, then |
| Returns | |
|---|---|
int |
The index of the smallest element in |
binarySearchFloor
@UnstableApi
public 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.
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.
| Parameters | |
|---|---|
int[] array |
The array to search. |
int value |
The value being searched for. |
boolean 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. |
boolean 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 | |
|---|---|
int |
The index of the largest element in |
binarySearchFloor
@UnstableApi
public 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.
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.
| Parameters | |
|---|---|
long[] array |
The array to search. |
long value |
The value being searched for. |
boolean 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. |
boolean 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 | |
|---|---|
int |
The index of the largest element in |
binarySearchFloor
@UnstableApi
public static int <T extends Comparable<T>> binarySearchFloor(
List<Comparable<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.
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.
| Parameters | |
|---|---|
<T extends Comparable<T>> |
The type of values being searched. |
List<Comparable<T>> list |
The list to search. |
T value |
The value being searched for. |
boolean 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. |
boolean 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 | |
|---|---|
int |
The index of the largest element in |
binarySearchFloor
@UnstableApi
public 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.
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.
| Parameters | |
|---|---|
LongArray longArray |
The array to search. |
long value |
The value being searched for. |
boolean 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. |
boolean 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 | |
|---|---|
int |
The index of the largest element in |
castNonNull
@UnstableApi
@EnsuresNonNull(value = "#1")
public static T <T> castNonNull(@Nullable T value)
Casts a nullable variable to a non-null variable without runtime null check.
Use checkNotNull to throw if the value is null.
castNonNullTypeArray
@UnstableApi
@EnsuresNonNull(value = "#1")
public static T[] <T> castNonNullTypeArray(@NullableType T[] value)
Casts a nullable type array to a non-null type array without runtime null check.
ceilDivide
@UnstableApi
public static int ceilDivide(int numerator, int denominator)
Divides a numerator by a denominator, returning the ceiled result.
| Parameters | |
|---|---|
int numerator |
The numerator to divide. |
int denominator |
The denominator to divide by. |
| Returns | |
|---|---|
int |
The ceiled result of the division. |
ceilDivide
@UnstableApi
public static long ceilDivide(long numerator, long denominator)
Divides a numerator by a denominator, returning the ceiled result.
| Parameters | |
|---|---|
long numerator |
The numerator to divide. |
long denominator |
The denominator to divide by. |
| Returns | |
|---|---|
long |
The ceiled result of the division. |
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 | |
|---|---|
MediaItem[] mediaItems |
A list of |
| Returns | |
|---|---|
boolean |
Whether it may be possible to load the URIs of the given media items. |
closeQuietly
@UnstableApi
public static void closeQuietly(@Nullable Closeable closeable)
Closes a Closeable, suppressing any IOException that may occur. Both java.io.OutputStream and InputStream are Closeable.
compareLong
@UnstableApi
@InlineMe(replacement = "Long.compare(left, right)")
public static intcompareLong(long left, long right)
constrainValue
@UnstableApi
public static float constrainValue(float value, float min, float max)
Constrains a value to the specified bounds.
| Parameters | |
|---|---|
float value |
The value to constrain. |
float min |
The lower bound. |
float max |
The upper bound. |
| Returns | |
|---|---|
float |
The constrained value |
constrainValue
@UnstableApi
public static int constrainValue(int value, int min, int max)
Constrains a value to the specified bounds.
| Parameters | |
|---|---|
int value |
The value to constrain. |
int min |
The lower bound. |
int max |
The upper bound. |
| Returns | |
|---|---|
int |
The constrained value |
constrainValue
@UnstableApi
public static long constrainValue(long value, long min, long max)
Constrains a value to the specified bounds.
| Parameters | |
|---|---|
long value |
The value to constrain. |
long min |
The lower bound. |
long max |
The upper bound. |
| Returns | |
|---|---|
long |
The constrained value |
contains
@UnstableApi
public static boolean contains(@NullableType Object[] items, @Nullable Object item)
Tests whether an items array contains an object equal to item, according to equals.
If item is null then true is returned if and only if items contains null.
| Parameters | |
|---|---|
@NullableType Object[] items |
The array of items to search. |
@Nullable Object item |
The item to search for. |
| Returns | |
|---|---|
boolean |
True if the array contains an object equal to the item being searched for. |
contains
@UnstableApi
public static boolean <T> contains(SparseArray<T> sparseArray, int key)
Tests whether a SparseArray contains a given key.
This implements SparseArray#contains for lower API versions.
contentEquals
@UnstableApi
public static boolean <T> contentEquals(
@Nullable SparseArray<T> sparseArray1,
@Nullable SparseArray<T> sparseArray2
)
Tests two SparseArray instances for content equality, handling the case where one or both may be null.
| Parameters | |
|---|---|
@Nullable SparseArray<T> sparseArray1 |
The first |
@Nullable SparseArray<T> sparseArray2 |
The second |
| Returns | |
|---|---|
boolean |
True if the two |
| See also | |
|---|---|
contentEquals |
contentHashCode
@UnstableApi
public static int <T> contentHashCode(SparseArray<T> sparseArray)
Returns a hash code value for the contents of this SparseArray, combining the hashCode result of all its keys and values.
| Parameters | |
|---|---|
SparseArray<T> sparseArray |
The |
| Returns | |
|---|---|
int |
The hash code. |
| See also | |
|---|---|
contentHashCode |
crc16
@UnstableApi
public static int crc16(byte[] bytes, int start, int end, int initialValue)
Returns the result of updating a CRC-16 with the specified bytes in a "most significant bit first" order.
| Parameters | |
|---|---|
byte[] bytes |
Array containing the bytes to update the crc value with. |
int start |
The start index (inclusive) of the byte range to update the crc with. |
int end |
The end index (exclusive) of the byte range to update the crc with. |
int initialValue |
The initial value for the crc calculation. The lower 16 bits of this 32-bit integer are used for the CRC computation. |
| Returns | |
|---|---|
int |
The result of updating the initial value with the specified bytes. |
crc32
@UnstableApi
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 | |
|---|---|
byte[] bytes |
Array containing the bytes to update the crc value with. |
int start |
The index to the first byte in the byte range to update the crc with. |
int end |
The index after the last byte in the byte range to update the crc with. |
int initialValue |
The initial value for the crc calculation. |
| Returns | |
|---|---|
int |
The result of updating the initial value with the specified bytes. |
crc8
@UnstableApi
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 | |
|---|---|
byte[] bytes |
Array containing the bytes to update the crc value with. |
int start |
The index to the first byte in the byte range to update the crc with. |
int end |
The index after the last byte in the byte range to update the crc with. |
int initialValue |
The initial value for the crc calculation. |
| Returns | |
|---|---|
int |
The result of updating the initial value with the specified bytes. |
createHandler
@UnstableApi
public static Handler createHandler(
Looper looper,
@Nullable @UnknownInitialization Handler.Callback callback
)
Creates a 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.
| Parameters | |
|---|---|
Looper looper |
A |
@Nullable @UnknownInitialization Handler.Callback callback |
A |
createHandlerForCurrentLooper
@UnstableApi
public static Handler createHandlerForCurrentLooper()
Creates a Handler on the current Looper thread.
| Throws | |
|---|---|
java.lang.IllegalStateException |
If the current thread doesn't have a |
createHandlerForCurrentLooper
@UnstableApi
public static Handler createHandlerForCurrentLooper(
@Nullable @UnknownInitialization Handler.Callback callback
)
Creates a 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.
| Parameters | |
|---|---|
@Nullable @UnknownInitialization Handler.Callback callback |
A |
| Throws | |
|---|---|
java.lang.IllegalStateException |
If the current thread doesn't have a |
createHandlerForCurrentOrMainLooper
@UnstableApi
public static Handler createHandlerForCurrentOrMainLooper()
Creates a Handler on the current Looper thread.
If the current thread doesn't have a Looper, the application's main thread Looper is used.
createHandlerForCurrentOrMainLooper
@UnstableApi
public static Handler createHandlerForCurrentOrMainLooper(
@Nullable @UnknownInitialization Handler.Callback callback
)
Creates a 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.
| Parameters | |
|---|---|
@Nullable @UnknownInitialization Handler.Callback callback |
A |
createReadOnlyByteBuffer
@UnstableApi
public static ByteBuffer createReadOnlyByteBuffer(ByteBuffer byteBuffer)
Returns a read-only view of the given ByteBuffer.
This behaves the same as asReadOnlyBuffer whilst preserving the ByteOrder of the original buffer.
createTempDirectory
@UnstableApi
public static File createTempDirectory(Context context, String prefix)
Creates an empty directory in the directory returned by getCacheDir.
| Throws | |
|---|---|
java.io.IOException |
createTempFile
@UnstableApi
public static File createTempFile(Context context, String prefix)
Creates a new empty file in the directory returned by getCacheDir.
| Throws | |
|---|---|
java.io.IOException |
durationUsToSampleCount
@UnstableApi
public static long durationUsToSampleCount(long durationUs, int sampleRate)
Returns the number of samples required to represent durationUs of media at
sampleRate, assuming all samples are equal duration except the last one which may be shorter.
The result of this method cannot be generally reversed to the original duration with sampleCountToDurationUs, due to information lost when rounding to a whole number of samples.
| Parameters | |
|---|---|
long durationUs |
The duration in microseconds. |
int sampleRate |
The sample rate in samples per second. |
| Returns | |
|---|---|
long |
The number of samples required to represent |
escapeFileName
@UnstableApi
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 can be used to retrieve the original file name.
| Parameters | |
|---|---|
String fileName |
File name to be escaped. |
| Returns | |
|---|---|
String |
An escaped file name which will be safe for use on at least FAT32 filesystems. |
fixSmoothStreamingIsmManifestUri
@UnstableApi
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 uri |
The original URI. |
| Returns | |
|---|---|
Uri |
The fixed URI. |
formatInvariant
@UnstableApi
public static String formatInvariant(String format, Object[] args)
Formats a string using US.
| See also | |
|---|---|
format |
fromUtf8Bytes
@UnstableApi
public static String fromUtf8Bytes(byte[] bytes)
Returns a new String constructed by decoding UTF-8 encoded bytes.
| Parameters | |
|---|---|
byte[] bytes |
The UTF-8 encoded bytes to decode. |
| Returns | |
|---|---|
String |
The string. |
fromUtf8Bytes
@UnstableApi
public static String fromUtf8Bytes(byte[] bytes, int offset, int length)
Returns a new String constructed by decoding UTF-8 encoded bytes in a subarray.
| Parameters | |
|---|---|
byte[] bytes |
The UTF-8 encoded bytes to decode. |
int offset |
The index of the first byte to decode. |
int length |
The number of bytes to decode. |
| Returns | |
|---|---|
String |
The string. |
generateAudioSessionIdV21
@UnstableApi
public static int generateAudioSessionIdV21(Context context)
Returns a newly generated audio session identifier, or AUDIO_SESSION_ID_UNSET if failed to generate an identifier and in which case audio playback may fail.
| See also | |
|---|---|
generateAudioSessionId |
getAdaptiveMimeTypeForContentType
public static @Nullable String getAdaptiveMimeTypeForContentType(@C.ContentType int contentType)
Returns the MIME type corresponding to the given adaptive ContentType, or null if the content type is not adaptive.
getApiLevelThatAudioFormatIntroducedAudioEncoding
@UnstableApi
public static int getApiLevelThatAudioFormatIntroducedAudioEncoding(int encoding)
Retrieves the API Level that AudioFormat introduced an encoding.
Method returns MAX_VALUE if the encoding is unknown.
| Parameters | |
|---|---|
int encoding |
for which to get the API level. |
getAudioContentTypeForStreamType
@UnstableApi
@C.AudioContentType
public static intgetAudioContentTypeForStreamType(@C.StreamType int streamType)
getAudioFormat
@UnstableApi
public static AudioFormat getAudioFormat(int sampleRate, int channelConfig, int encoding)
Creates AudioFormat with given sampleRate, channelConfig, and encoding.
getAudioTrackChannelConfig
@UnstableApi
public static int getAudioTrackChannelConfig(int channelCount)
Returns the audio track channel configuration for the given channel count, or CHANNEL_INVALID if output is not possible.
| Parameters | |
|---|---|
int channelCount |
The number of channels in the input audio. |
| Returns | |
|---|---|
int |
The channel configuration or |
getAudioUsageForStreamType
@UnstableApi
@C.AudioUsage
public static int getAudioUsageForStreamType(@C.StreamType int streamType)
Returns the C.AudioUsage corresponding to the specified C.StreamType.
getAuxiliaryTrackTypeString
@UnstableApi
public static String getAuxiliaryTrackTypeString(
@C.AuxiliaryTrackType int auxiliaryTrackType
)
Returns a string representation of the C.AuxiliaryTrackType.
getAvailableCommands
@UnstableApi
public static Player.Commands getAvailableCommands(
Player player,
Player.Commands permanentAvailableCommands
)
Returns the Commands available in the Player.
| Parameters | |
|---|---|
Player player |
The |
Player.Commands permanentAvailableCommands |
The commands permanently available in the player. |
| Returns | |
|---|---|
Player.Commands |
The available |
getBigEndianInt
@UnstableApi
public static int getBigEndianInt(ByteBuffer buffer, int index)
Absolute get method for reading an int value in BIG_ENDIAN in a ByteBuffer. Same as getInt except the buffer's order as returned by order is ignored and BIG_ENDIAN is used instead.
| Parameters | |
|---|---|
ByteBuffer buffer |
The buffer from which to read an int in big endian. |
int index |
The index from which the bytes will be read. |
| Returns | |
|---|---|
int |
The int value at the given index with the buffer bytes ordered most significant to least significant. |
getBufferFlagsFromMediaCodecFlags
@UnstableApi
@C.BufferFlags
public static int getBufferFlagsFromMediaCodecFlags(int mediaCodecFlags)
Returns C.BufferFlags corresponding to MediaCodec flags.
getByteDepth
@UnstableApi
public static int getByteDepth(@C.PcmEncoding int pcmEncoding)
Returns the byte depth for audio with the specified encoding.
| Parameters | |
|---|---|
@C.PcmEncoding int pcmEncoding |
The encoding of the audio data. |
| Returns | |
|---|---|
int |
The byte depth of the audio. |
getBytesFromHexString
@UnstableApi
public static byte[] getBytesFromHexString(String hexString)
Returns a byte array containing values parsed from the hex string provided.
| Parameters | |
|---|---|
String hexString |
The hex string to convert to bytes. |
| Returns | |
|---|---|
byte[] |
A byte array containing values parsed from the hex string provided. |
getCodecCountOfType
@UnstableApi
public static int getCodecCountOfType(@Nullable String codecs, @C.TrackType int trackType)
Returns the number of codec strings in codecs whose type matches trackType.
getCodecsOfType
@UnstableApi
public static @Nullable String getCodecsOfType(@Nullable String codecs, @C.TrackType int trackType)
Returns a copy of codecs without the codecs whose track type doesn't match
trackType.
| Parameters | |
|---|---|
@Nullable String codecs |
A codec sequence string, as defined in RFC 6381. |
@C.TrackType int trackType |
The |
getCodecsWithoutType
@UnstableApi
public static @Nullable String getCodecsWithoutType(@Nullable String codecs, @C.TrackType int trackType)
Returns a copy of codecs without the codecs whose track type matches trackType.
| Parameters | |
|---|---|
@Nullable String codecs |
A codec sequence string, as defined in RFC 6381. |
@C.TrackType int trackType |
The |
getCountryCode
@UnstableApi
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 | |
|---|---|
@Nullable Context context |
A context to access the telephony service. If null, only the Locale can be used. |
| Returns | |
|---|---|
String |
The upper-case ISO 3166-1 alpha-2 country code, or an empty String if unavailable. |
getCurrentDisplayModeSize
@UnstableApi
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 getSize 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.
| Parameters | |
|---|---|
Context context |
Any context. |
| Returns | |
|---|---|
Point |
The size of the current mode, in pixels. |
getCurrentDisplayModeSize
@UnstableApi
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 getSize 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.
| Returns | |
|---|---|
Point |
The size of the current mode, in pixels. |
getCurrentOrMainLooper
@UnstableApi
public static Looper getCurrentOrMainLooper()
Returns the Looper associated with the current thread, or the Looper of the application's main thread if the current thread doesn't have a Looper.
getDataUriForString
@UnstableApi
public static Uri getDataUriForString(String mimeType, String data)
Returns a data URI with the specified MIME type and data.
getDrawable
@UnstableApi
public static Drawable getDrawable(
Context context,
Resources resources,
@DrawableRes int drawableRes
)
Returns a Drawable for the given resource or throws a Resources.NotFoundException if not found.
| Parameters | |
|---|---|
Context context |
The context to get the theme from. |
Resources resources |
The resources to load the drawable from. |
@DrawableRes int drawableRes |
The drawable resource int. |
getDrmUuid
public static @Nullable UUID getDrmUuid(String drmScheme)
Derives a DRM UUID from drmScheme.
| Parameters | |
|---|---|
String drmScheme |
A UUID string, or |
getErrorCodeForMediaDrmErrorCode
@UnstableApi
@PlaybackException.ErrorCode
public static int getErrorCodeForMediaDrmErrorCode(int mediaDrmErrorCode)
Returns a PlaybackException.ErrorCode value that corresponds to the provided MediaDrm.ErrorCodes value. Returns ERROR_CODE_DRM_SYSTEM_ERROR if the provided error code isn't recognised.
getErrorCodeFromPlatformDiagnosticsInfo
@UnstableApi
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.
| Returns | |
|---|---|
int |
The parsed error code, or 0 if an error code could not be parsed. |
getFormatSupportString
@UnstableApi
public static String getFormatSupportString(@C.FormatSupport int formatSupport)
Returns string representation of a C.FormatSupport flag.
| Parameters | |
|---|---|
@C.FormatSupport int formatSupport |
A |
| Returns | |
|---|---|
String |
A string representation of the flag. |
getInt24
@UnstableApi
public static int getInt24(ByteBuffer buffer, int index)
Returns the sign-extended 24-bit integer value at index.
| Parameters | |
|---|---|
ByteBuffer buffer |
The buffer from which to read the 24-bit integer. |
int index |
The index of the 24-bit integer. |
getIntegerCodeForString
@UnstableApi
public static int getIntegerCodeForString(String string)
Returns the integer equal to the big-endian concatenation of the characters in string as bytes. The string must be no more than four characters long.
| Parameters | |
|---|---|
String string |
A string no more than four characters long. |
getLocaleLanguageTag
@UnstableApi
public static String getLocaleLanguageTag(Locale locale)
Returns the language tag for a Locale.
This tag is IETF BCP 47 compliant.
| Returns | |
|---|---|
String |
The language tag. |
getMaxPendingFramesCountForMediaCodecDecoders
@UnstableApi
public static int getMaxPendingFramesCountForMediaCodecDecoders(Context context)
Returns the number of maximum pending output frames that are allowed on a MediaCodec decoder.
getMediaDurationForPlayoutDuration
@UnstableApi
public static long getMediaDurationForPlayoutDuration(long playoutDuration, float speed)
Returns the duration of media that will elapse in playoutDuration.
| Parameters | |
|---|---|
long playoutDuration |
The duration to scale. |
float speed |
The factor by which playback is sped up. |
| Returns | |
|---|---|
long |
The scaled duration, in the same units as |
getNowUnixTimeMs
@UnstableApi
public static long getNowUnixTimeMs(long elapsedRealtimeEpochOffsetMs)
Returns the current time in milliseconds since the epoch.
| Parameters | |
|---|---|
long elapsedRealtimeEpochOffsetMs |
The offset between |
| Returns | |
|---|---|
long |
The Unix time in milliseconds since the epoch. |
getPcmEncoding
@UnstableApi
@C.PcmEncoding
public static int getPcmEncoding(int bitDepth)
Converts a sample bit depth to a corresponding little-endian integer PCM encoding constant.
| Parameters | |
|---|---|
int bitDepth |
The bit depth. Supported values are 8, 16, 24 and 32. |
| Returns | |
|---|---|
int |
The corresponding encoding. One of |
getPcmEncoding
@UnstableApi
@C.PcmEncoding
public static int getPcmEncoding(int bitDepth, ByteOrder byteOrder)
Converts a sample bit depth and byte order to a corresponding integer PCM encoding constant.
| Parameters | |
|---|---|
int bitDepth |
The bit depth. Supported values are 8, 16, 24 and 32. |
ByteOrder byteOrder |
The byte order. |
| Returns | |
|---|---|
int |
The corresponding integer PCM encoding. If the bit depth is unsupported then |
getPcmFormat
@UnstableApi
public static Format getPcmFormat(AudioProcessor.AudioFormat audioFormat)
Gets a PCM Format based on the AudioProcessor.AudioFormat.
getPcmFormat
@UnstableApi
public static Format getPcmFormat(@C.PcmEncoding int pcmEncoding, int channels, int sampleRate)
Gets a PCM Format with the specified parameters.
| Parameters | |
|---|---|
@C.PcmEncoding int pcmEncoding |
The |
int channels |
The number of channels, or |
int sampleRate |
The sample rate in Hz, or |
| Returns | |
|---|---|
Format |
The PCM format. |
getPcmFrameSize
@UnstableApi
public static int getPcmFrameSize(@C.PcmEncoding int pcmEncoding, int channelCount)
Returns the frame size for audio with channelCount channels in the specified encoding.
| Parameters | |
|---|---|
@C.PcmEncoding int pcmEncoding |
The encoding of the audio data. |
int channelCount |
The channel count. |
| Returns | |
|---|---|
int |
The size of one audio frame in bytes. |
getPlayoutDurationForMediaDuration
@UnstableApi
public static long getPlayoutDurationForMediaDuration(long mediaDuration, float speed)
Returns the playout duration of mediaDuration of media.
| Parameters | |
|---|---|
long mediaDuration |
The duration to scale. |
float speed |
The factor by which playback is sped up. |
| Returns | |
|---|---|
long |
The scaled duration, in the same units as |
getRoleFlagStrings
@UnstableApi
public static List<String> getRoleFlagStrings(@C.RoleFlags int roleFlags)
Returns a list of strings representing the C.RoleFlags values present in
roleFlags.
getSelectionFlagStrings
@UnstableApi
public static List<String> getSelectionFlagStrings(@C.SelectionFlags int selectionFlags)
Returns a list of strings representing the C.SelectionFlags values present in
selectionFlags.
getStreamTypeForAudioUsage
@UnstableApi
@C.StreamType
public static intgetStreamTypeForAudioUsage(@C.AudioUsage int usage)
getStringForTime
@UnstableApi
public static String getStringForTime(long timeMs)
Returns the specified millisecond time formatted as a string.
| Parameters | |
|---|---|
long timeMs |
The time to format as a string, in milliseconds. |
| Returns | |
|---|---|
String |
The time formatted as a string. |
getStringForTime
@UnstableApi
public static String getStringForTime(
StringBuilder builder,
Formatter formatter,
long timeMs
)
Returns the specified millisecond time formatted as a string.
| Parameters | |
|---|---|
StringBuilder builder |
The builder that |
Formatter formatter |
The formatter. |
long timeMs |
The time to format as a string, in milliseconds. |
| Returns | |
|---|---|
String |
The time formatted as a string. |
getSystemLanguageCodes
@UnstableApi
public static String[] getSystemLanguageCodes()
Returns a non-empty array of normalized IETF BCP 47 language tags for the system languages ordered by preference.
getTrackTypeString
@UnstableApi
public static String getTrackTypeString(@C.TrackType int trackType)
Returns a string representation of a C.TrackType.
| Parameters | |
|---|---|
@C.TrackType int trackType |
A |
| Returns | |
|---|---|
String |
A string representation of this constant. |
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 context |
A valid context of the calling application. |
String applicationName |
String that will be prefix'ed to the generated user agent. |
| Returns | |
|---|---|
String |
A user agent string generated using the applicationName and the library version. |
getUtf8Bytes
@UnstableApi
public static byte[] getUtf8Bytes(String value)
Returns a new byte array containing the code points of a String encoded using UTF-8.
| Returns | |
|---|---|
byte[] |
The code points encoding using UTF-8. |
gzip
@UnstableApi
public static byte[] gzip(byte[] input)
Compresses input using gzip and returns the result in a newly allocated byte array.
handlePauseButtonAction
public static boolean handlePauseButtonAction(@Nullable Player player)
Updates the player to handle an interaction with a pause button.
This method assumes the pause button is enabled if shouldShowPlayButton returns false.
| Returns | |
|---|---|
boolean |
Whether a player method was triggered to handle this action. |
handlePlayButtonAction
public static boolean handlePlayButtonAction(@Nullable Player player)
Updates the player to handle an interaction with a play button.
This method assumes the play button is enabled if shouldShowPlayButton returns true.
| Returns | |
|---|---|
boolean |
Whether a player method was triggered to handle this action. |
handlePlayPauseButtonAction
public static boolean handlePlayPauseButtonAction(@Nullable Player player)
Updates the player to handle an interaction with a play or pause button.
This method assumes that the UI element enables a play button if shouldShowPlayButton returns true and a pause button otherwise.
| Returns | |
|---|---|
boolean |
Whether a player method was triggered to handle this action. |
handlePlayPauseButtonAction
@UnstableApi
public static boolean handlePlayPauseButtonAction(
@Nullable Player player,
boolean playIfSuppressed
)
Updates the player to handle an interaction with a play or pause button.
This method assumes that the UI element enables a play button if shouldShowPlayButton returns true and a pause button otherwise.
| Parameters | |
|---|---|
@Nullable Player player |
The |
boolean playIfSuppressed |
Whether to trigger a play action if playback is |
| Returns | |
|---|---|
boolean |
Whether a player method was triggered to handle this action. |
inferContentType
@C.ContentType
public static int inferContentType(Uri uri)
Makes a best guess to infer the ContentType from a Uri.
| Returns | |
|---|---|
int |
The content type. |
inferContentType
@UnstableApi
@C.ContentType
public static intinferContentType(Uri uri, @Nullable String overrideExtension)
inferContentTypeForExtension
@C.ContentType
public static int inferContentTypeForExtension(String fileExtension)
Makes a best guess to infer the ContentType from a file extension.
| Parameters | |
|---|---|
String fileExtension |
The extension of the file (excluding the '.'). |
| Returns | |
|---|---|
int |
The content type. |
inferContentTypeForUriAndMimeType
@C.ContentType
public static int inferContentTypeForUriAndMimeType(Uri uri, @Nullable String mimeType)
Makes a best guess to infer the ContentType from a Uri and optional MIME type.
| Returns | |
|---|---|
int |
The content type. |
inflate
@UnstableApi
public static boolean inflate(
ParsableByteArray input,
ParsableByteArray output,
@Nullable Inflater inflater
)
Uncompresses the data in input.
| Parameters | |
|---|---|
ParsableByteArray input |
Wraps the compressed input data. |
ParsableByteArray output |
Wraps an output buffer to be used to store the uncompressed data. If |
@Nullable Inflater inflater |
If not null, used to uncompressed the input. Otherwise a new |
| Returns | |
|---|---|
boolean |
Whether the input is uncompressed successfully. |
intToStringMaxRadix
@UnstableApi
public static String intToStringMaxRadix(int i)
Returns a string representation of the integer using radix value MAX_RADIX.
| Parameters | |
|---|---|
int i |
An integer to be converted to String. |
isAutomotive
@UnstableApi
public static boolean isAutomotive(Context context)
Returns whether the app is running on an automotive device.
| Parameters | |
|---|---|
Context context |
Any context. |
| Returns | |
|---|---|
boolean |
Whether the app is running on an automotive device. |
isBitmapFactorySupportedMimeType
@UnstableApi
public static boolean isBitmapFactorySupportedMimeType(String mimeType)
Returns the image MIME types that can be decoded and loaded by android.graphics.BitmapFactory that Media3 aims to support.
isEncodingHighResolutionPcm
@UnstableApi
public static boolean isEncodingHighResolutionPcm(@C.PcmEncoding int encoding)
Returns whether encoding is high resolution (> 16-bit) PCM.
| Parameters | |
|---|---|
@C.PcmEncoding int encoding |
The encoding of the audio data. |
| Returns | |
|---|---|
boolean |
Whether the encoding is high resolution PCM. |
isEncodingLinearPcm
@UnstableApi
public static boolean isEncodingLinearPcm(@C.Encoding int encoding)
Returns whether encoding is one of the linear PCM encodings.
| Parameters | |
|---|---|
@C.Encoding int encoding |
The encoding of the audio data. |
| Returns | |
|---|---|
boolean |
Whether the encoding is one of the PCM encodings. |
isFrameDropAllowedOnSurfaceInput
@UnstableApi
public static boolean isFrameDropAllowedOnSurfaceInput(Context context)
isLinebreak
@UnstableApi
public static boolean isLinebreak(int c)
Returns whether the given character is a carriage return ('\r') or a line feed ('\n').
| Parameters | |
|---|---|
int c |
The character. |
| Returns | |
|---|---|
boolean |
Whether the given character is a linebreak. |
isLocalFileUri
@UnstableApi
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 uri |
The uri to test. |
isRunningOnEmulator
@UnstableApi
public static boolean isRunningOnEmulator()
Returns true if the code path is currently running on an emulator.
isSorted
@UnstableApi
public static boolean isSorted(long[] values)
Returns whether values is sorted in ascending order.
isTv
@UnstableApi
public static boolean isTv(Context context)
Returns whether the app is running on a TV device.
| Parameters | |
|---|---|
Context context |
Any context. |
| Returns | |
|---|---|
boolean |
Whether the app is running on a TV device. |
isWear
@UnstableApi
public static boolean isWear(Context context)
Returns whether the app is running on a Wear OS device.
| Parameters | |
|---|---|
Context context |
Any context. |
| Returns | |
|---|---|
boolean |
Whether the app is running on a Wear OS device. |
linearSearch
@UnstableApi
public static int linearSearch(int[] array, int value)
Returns the index of the first occurrence of value in array, or INDEX_UNSET if value is not contained in array.
| Parameters | |
|---|---|
int[] array |
The array to search. |
int value |
The value to search for. |
| Returns | |
|---|---|
int |
The index of the first occurrence of value in |
linearSearch
@UnstableApi
public static int linearSearch(long[] array, long value)
Returns the index of the first occurrence of value in array, or INDEX_UNSET if value is not contained in array.
| Parameters | |
|---|---|
long[] array |
The array to search. |
long value |
The value to search for. |
| Returns | |
|---|---|
int |
The index of the first occurrence of value in |
loadAsset
@UnstableApi
public static String loadAsset(Context context, String assetPath)
Loads a file from the assets folder.
This should only be used for known-small files. Generally, loading assets should be done with AssetDataSource.
The file is assumed to be encoded in UTF-8.
| Parameters | |
|---|---|
Context context |
The |
String assetPath |
The path to the file to load, from the assets folder. |
| Returns | |
|---|---|
String |
The content of the file to load. |
| Throws | |
|---|---|
java.io.IOException |
If the file couldn't be read. |
maxValue
@UnstableApi
public static long maxValue(SparseLongArray sparseLongArray)
Returns the maximum value in the given SparseLongArray.
| Parameters | |
|---|---|
SparseLongArray sparseLongArray |
The |
| Returns | |
|---|---|
long |
The maximum value. |
| Throws | |
|---|---|
java.util.NoSuchElementException |
If the array is empty. |
maybeInflate
@UnstableApi
public static boolean maybeInflate(
ParsableByteArray input,
ParsableByteArray output,
@Nullable Inflater inflater
)
Uncompresses the data in input if it starts with the zlib marker 0x78.
| Parameters | |
|---|---|
ParsableByteArray input |
Wraps the compressed input data. |
ParsableByteArray output |
Wraps an output buffer to be used to store the uncompressed data. If |
@Nullable Inflater inflater |
If not null, used to uncompress the input. Otherwise a new |
| Returns | |
|---|---|
boolean |
Whether the input is uncompressed successfully. |
maybeRequestReadExternalStoragePermission
public static booleanmaybeRequestReadExternalStoragePermission(
Activity activity,
MediaItem[] mediaItems
)
maybeRequestReadExternalStoragePermission
public static booleanmaybeRequestReadExternalStoragePermission(
Activity activity,
Uri[] uris
)
maybeRequestReadStoragePermission
public static boolean maybeRequestReadStoragePermission(
Activity activity,
MediaItem[] mediaItems
)
Checks whether it's necessary to request storage reading permissions for the specified media items, requesting the permissions if necessary.
| Parameters | |
|---|---|
Activity activity |
The host activity for checking and requesting the permission. |
MediaItem[] mediaItems |
|
| Returns | |
|---|---|
boolean |
Whether a permission request was made. |
minValue
@UnstableApi
public static long minValue(SparseLongArray sparseLongArray)
Returns the minimum value in the given SparseLongArray.
| Parameters | |
|---|---|
SparseLongArray sparseLongArray |
The |
| Returns | |
|---|---|
long |
The minimum value. |
| Throws | |
|---|---|
java.util.NoSuchElementException |
If the array is empty. |
moveItems
@UnstableApi
public static void <T extends Object> moveItems(
List<T> items,
int fromIndex,
int toIndex,
int newFromIndex
)
Moves the elements starting at fromIndex to newFromIndex.
| Parameters | |
|---|---|
List<T> items |
The list of which to move elements. |
int fromIndex |
The index at which the items to move start. |
int toIndex |
The index up to which elements should be moved (exclusive). |
int newFromIndex |
The new from index. |
msToUs
@UnstableApi
public static long msToUs(long timeMs)
Converts a time in milliseconds to the corresponding time in microseconds, preserving TIME_UNSET values and TIME_END_OF_SOURCE values.
| Parameters | |
|---|---|
long timeMs |
The time in milliseconds. |
| Returns | |
|---|---|
long |
The corresponding time in microseconds. |
newSingleThreadExecutor
@UnstableApi
public static ExecutorService newSingleThreadExecutor(String threadName)
Instantiates a new single threaded executor whose thread has the specified name.
| Parameters | |
|---|---|
String threadName |
The name of the thread. |
| Returns | |
|---|---|
ExecutorService |
The executor. |
newSingleThreadScheduledExecutor
@UnstableApi
public static ScheduledExecutorService newSingleThreadScheduledExecutor(String threadName)
Instantiates a new single threaded scheduled executor whose thread has the specified name.
| Parameters | |
|---|---|
String threadName |
The name of the thread. |
| Returns | |
|---|---|
ScheduledExecutorService |
The executor. |
normalizeLanguageCode
@UnstableApi
@PolyNull
public static @PolyNull String normalizeLanguageCode(@PolyNull @PolyNull String language)
Returns a normalized IETF BCP 47 language tag for language.
| Parameters | |
|---|---|
@PolyNull @PolyNull String language |
A case-insensitive language code supported by |
nullSafeArrayAppend
@UnstableApi
public static T[] <T> nullSafeArrayAppend(T[] original, T newElement)
Creates a new array containing original with newElement appended.
| Parameters | |
|---|---|
T[] original |
The input array. |
T newElement |
The element to append. |
| Returns | |
|---|---|
T[] |
The new array. |
nullSafeArrayConcatenation
@UnstableApi
public static T[] <T> nullSafeArrayConcatenation(T[] first, T[] second)
Creates a new array containing the concatenation of two non-null type arrays.
| Parameters | |
|---|---|
T[] first |
The first array. |
T[] second |
The second array. |
| Returns | |
|---|---|
T[] |
The concatenated result. |
nullSafeArrayCopy
@UnstableApi
public static T[] <T> nullSafeArrayCopy(T[] input, int length)
Copies and optionally truncates an array. Prevents null array elements created by copyOf by ensuring the new length does not exceed the current length.
| Parameters | |
|---|---|
T[] input |
The input array. |
int length |
The output array length. Must be less or equal to the length of the input array. |
| Returns | |
|---|---|
T[] |
The copied array. |
nullSafeArrayCopyOfRange
@UnstableApi
public static T[] <T> nullSafeArrayCopyOfRange(T[] input, int from, int to)
Copies a subset of an array.
| Parameters | |
|---|---|
T[] input |
The input array. |
int from |
The start the range to be copied, inclusive |
int to |
The end of the range to be copied, exclusive. |
| Returns | |
|---|---|
T[] |
The copied array. |
nullSafeListToArray
@UnstableApi
public static void <T> nullSafeListToArray(List<T> list, T[] array)
Copies the contents of 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.
| Parameters | |
|---|---|
List<T> list |
The list to copy items from. |
T[] array |
The array to copy items to. |
parseXsDateTime
@UnstableApi
public static long parseXsDateTime(String value)
Parses an xs:dateTime attribute value, returning the parsed timestamp in milliseconds since the epoch.
| Parameters | |
|---|---|
String value |
The attribute value to decode. |
| Returns | |
|---|---|
long |
The parsed timestamp in milliseconds since the epoch. |
| Throws | |
|---|---|
androidx.media3.common.ParserException |
if an error occurs parsing the dateTime attribute value. |
parseXsDuration
@UnstableApi
public static long parseXsDuration(String value)
Parses an xs:duration attribute value, returning the parsed duration in milliseconds.
| Parameters | |
|---|---|
String value |
The attribute value to decode. |
| Returns | |
|---|---|
long |
The parsed duration in milliseconds. |
percentFloat
@UnstableApi
public static float percentFloat(long numerator, long denominator)
Returns the floating point percentage of numerator divided by denominator. Note that this may return POSITIVE_INFINITY, NEGATIVE_INFINITY or NaN if the denominator is zero.
percentInt
@UnstableApi
public static int percentInt(long numerator, long denominator)
Returns the integer percentage of numerator divided by denominator. This uses integer arithmetic (round down).
The result is cast from long to int following the rules of saturatedCast.
postOrRun
@UnstableApi
public static boolean postOrRun(Handler handler, Runnable runnable)
Posts the Runnable if the calling thread differs with the Looper of the Handler. Otherwise, runs the Runnable directly.
postOrRun
@UnstableApi
public static boolean postOrRun(HandlerWrapper handler, Runnable runnable)
Posts the Runnable if the calling thread differs with the Looper of the HandlerWrapper. Otherwise, runs the Runnable directly.
| Parameters | |
|---|---|
HandlerWrapper handler |
The |
Runnable runnable |
The runnable to either post or run. |
| Returns | |
|---|---|
boolean |
|
postOrRunWithCompletion
@UnstableApi
public static ListenableFuture<T> <T> postOrRunWithCompletion(
Handler handler,
Runnable runnable,
T successValue
)
Posts the Runnable if the calling thread differs with the Looper of the Handler. Otherwise, runs the Runnable directly. Also returns a ListenableFuture for when the Runnable has run.
| Parameters | |
|---|---|
<T> |
The type of |
Handler handler |
The handler to which the |
Runnable runnable |
The runnable to either post or run. |
T successValue |
The value to set in the |
| Returns | |
|---|---|
ListenableFuture<T> |
A |
putInt24
@UnstableApi
public static void putInt24(ByteBuffer buffer, int value)
Writes a 24-bit integer value to a buffer at its current position.
This is a relative operation that affects the buffer's position.
| Parameters | |
|---|---|
ByteBuffer buffer |
The buffer on which to write the integer. |
int value |
The integer value to write. |
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
If |
readBoolean
@UnstableApi
public 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.
| Returns | |
|---|---|
boolean |
The read value. |
recursiveDelete
@UnstableApi
public static void recursiveDelete(File fileOrDirectory)
Recursively deletes a directory and its content.
registerReceiverNotExported
@UnstableApi
public static @Nullable Intent registerReceiverNotExported(
Context context,
@Nullable BroadcastReceiver receiver,
IntentFilter filter
)
Registers a BroadcastReceiver that's not intended to receive broadcasts from other apps. This will be enforced by specifying RECEIVER_NOT_EXPORTED if SDK_INT is 33 or above.
Do not use this method if registering a receiver for a protected system broadcast.
| Parameters | |
|---|---|
@Nullable BroadcastReceiver receiver |
The |
Context context |
The context on which registerReceiver will be called. |
IntentFilter filter |
Selects the Intent broadcasts to be received. |
removeRange
@UnstableApi
public static void <T> 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<T> list |
The List to remove the range from. |
int fromIndex |
The first index to be removed (inclusive). |
int toIndex |
The last index to be removed (exclusive). |
| Throws | |
|---|---|
java.lang.IllegalArgumentException |
If |
sampleCountToDurationUs
@UnstableApi
public static long sampleCountToDurationUs(long sampleCount, int sampleRate)
Returns the total duration (in microseconds) of sampleCount samples of equal duration at sampleRate.
If sampleRate is less than MICROS_PER_SECOND, the duration produced by this method can be reversed to the original sample count using durationUsToSampleCount.
| Parameters | |
|---|---|
long sampleCount |
The number of samples. |
int sampleRate |
The sample rate, in samples per second. |
| Returns | |
|---|---|
long |
The total duration, in microseconds, of |
scaleLargeTimestamp
@UnstableApi
public static long scaleLargeTimestamp(long timestamp, long multiplier, long divisor)
Scales a large timestamp.
Equivalent to scaleLargeValue with DOWN.
| Parameters | |
|---|---|
long timestamp |
The timestamp to scale. |
long multiplier |
The multiplier. |
long divisor |
The divisor. |
| Returns | |
|---|---|
long |
The scaled timestamp. |
scaleLargeTimestamps
@UnstableApi
public static long[] scaleLargeTimestamps(
List<Long> timestamps,
long multiplier,
long divisor
)
Applies scaleLargeTimestamp to a list of unscaled timestamps.
| Parameters | |
|---|---|
List<Long> timestamps |
The timestamps to scale. |
long multiplier |
The multiplier. |
long divisor |
The divisor. |
| Returns | |
|---|---|
long[] |
The scaled timestamps. |
scaleLargeTimestampsInPlace
@UnstableApi
public static void scaleLargeTimestampsInPlace(
long[] timestamps,
long multiplier,
long divisor
)
Applies scaleLargeTimestamp to an array of unscaled timestamps.
| Parameters | |
|---|---|
long[] timestamps |
The timestamps to scale. |
long multiplier |
The multiplier. |
long divisor |
The divisor. |
scaleLargeValue
@UnstableApi
public static long scaleLargeValue(
long value,
long multiplier,
long divisor,
RoundingMode roundingMode
)
Scales a large value by a multiplier and a divisor.
The order of operations in this implementation is designed to minimize the probability of overflow. The implementation tries to stay in integer arithmetic as long as possible, but falls through to floating-point arithmetic if the values can't be combined without overflowing signed 64-bit longs.
If the mathematical result would overflow or underflow a 64-bit long, the result will be either MAX_VALUE or MIN_VALUE, respectively.
| Parameters | |
|---|---|
long value |
The value to scale. |
long multiplier |
The multiplier. |
long divisor |
The divisor. |
RoundingMode roundingMode |
The rounding mode to use if the result of the division is not an integer. |
| Returns | |
|---|---|
long |
The scaled value. |
scaleLargeValues
@UnstableApi
public static long[] scaleLargeValues(
List<Long> values,
long multiplier,
long divisor,
RoundingMode roundingMode
)
Applies scaleLargeValue to a list of unscaled values.
| Parameters | |
|---|---|
List<Long> values |
The values to scale. |
long multiplier |
The multiplier. |
long divisor |
The divisor. |
RoundingMode roundingMode |
The rounding mode to use if the result of the division is not an integer. |
| Returns | |
|---|---|
long[] |
The scaled values. |
scaleLargeValuesInPlace
@UnstableApi
public static void scaleLargeValuesInPlace(
long[] values,
long multiplier,
long divisor,
RoundingMode roundingMode
)
Applies scaleLargeValue to an array of unscaled values.
| Parameters | |
|---|---|
long[] values |
The values to scale. |
long multiplier |
The multiplier. |
long divisor |
The divisor. |
RoundingMode roundingMode |
The rounding mode to use if the result of the division is not an integer. |
setForegroundServiceNotification
@UnstableApi
public static void setForegroundServiceNotification(
Service service,
int notificationId,
Notification notification,
int foregroundServiceType,
String foregroundServiceManifestType
)
Sets the notification required for a foreground service.
| Parameters | |
|---|---|
Service service |
The foreground |
int notificationId |
The notification id. |
Notification notification |
The |
int foregroundServiceType |
The foreground service type defined in |
String foregroundServiceManifestType |
The required foreground service type string for the |
shouldEnablePlayPauseButton
@EnsuresNonNullIf(result = true, expression = "#1")
@UnstableApi
public static boolean shouldEnablePlayPauseButton(@Nullable Player player)
Returns whether a play-pause button should be enabled or not.
shouldShowPlayButton
@EnsuresNonNullIf(result = false, expression = "#1")
public static boolean shouldShowPlayButton(@Nullable Player player)
Returns whether a play button should be presented on a UI element for playback control. If false, a pause button should be shown instead.
Use handlePlayPauseButtonAction, handlePlayButtonAction or handlePauseButtonAction to handle the interaction with the play or pause button UI element.
shouldShowPlayButton
@UnstableApi
@EnsuresNonNullIf(result = false, expression = "#1")
public static boolean shouldShowPlayButton(
@Nullable Player player,
boolean shouldShowPlayIfSuppressed
)
Returns whether a play button should be presented on a UI element for playback control. If false, a pause button should be shown instead.
Use handlePlayPauseButtonAction, handlePlayButtonAction or handlePauseButtonAction to handle the interaction with the play or pause button UI element.
| Parameters | |
|---|---|
@Nullable Player player |
The |
boolean shouldShowPlayIfSuppressed |
Whether to show a play button if playback is |
sneakyThrow
@UnstableApi
public 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.
split
@UnstableApi
public static String[] split(String value, String regex)
Splits a string using value.split(regex, -1). Note: this is similar to split but empty matches at the end of the string will not be omitted from the returned array.
| Returns | |
|---|---|
String[] |
The array of strings resulting from splitting the string. |
splitAtFirst
@UnstableApi
public static String[] splitAtFirst(String value, String regex)
Splits the string at the first occurrence of the delimiter 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.
| Returns | |
|---|---|
String[] |
The string split by the first occurrence of the delimiter. |
splitCodecs
@UnstableApi
public static String[] splitCodecs(@Nullable String codecs)
Splits a codecs sequence string, as defined in RFC 6381, into individual codec strings.
| Returns | |
|---|---|
String[] |
The split codecs, or an array of length zero if the input was empty or null. |
startForegroundService
@UnstableApi
public static @Nullable ComponentName startForegroundService(Context context, Intent intent)
Calls startForegroundService if SDK_INT is 26 or higher, or startService otherwise.
| Parameters | |
|---|---|
Context context |
The context to call. |
Intent intent |
The intent to pass to the called method. |
| Returns | |
|---|---|
@Nullable ComponentName |
The result of the called method. |
subtractWithOverflowDefault
@UnstableApi
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 | |
|---|---|
long x |
The first value. |
long y |
The second value. |
long overflowResult |
The return value if |
| Returns | |
|---|---|
long |
|
sum
@UnstableApi
public static long sum(long[] summands)
Returns the sum of all summands of the given array.
| Parameters | |
|---|---|
long[] summands |
The summands to calculate the sum from. |
| Returns | |
|---|---|
long |
The sum of all summands. |
tableExists
@UnstableApi
public static boolean tableExists(SQLiteDatabase database, String tableName)
Returns whether the table exists in the database.
toByteArray
@UnstableApi
public static byte[]toByteArray(InputStream inputStream)
| Throws | |
|---|---|
java.io.IOException |
toByteArray
@UnstableApi
public static byte[] toByteArray(float value)
Converts a float into an equivalent byte array.
toByteArray
@UnstableApi
public static byte[] toByteArray(int[] values)
Converts an array of integers into an equivalent byte array.
Each integer is converted into 4 sequential bytes.
For a single integer, prefer Guava's toByteArray implementation.
toHexString
@UnstableApi
public static String toHexString(byte[] bytes)
Returns a string containing a lower-case hex representation of the bytes provided.
| Parameters | |
|---|---|
byte[] bytes |
The byte data to convert to hex. |
| Returns | |
|---|---|
String |
A String containing the hex representation of |
toLong
@UnstableApi
public static long toLong(int mostSignificantBits, int leastSignificantBits)
Returns the long that is composed of the bits of the 2 specified integers.
| Parameters | |
|---|---|
int mostSignificantBits |
The 32 most significant bits of the long to return. |
int leastSignificantBits |
The 32 least significant bits of the long to return. |
| Returns | |
|---|---|
long |
a long where its 32 most significant bits are |
toUnsignedLong
@UnstableApi
public static long toUnsignedLong(int x)
Converts an integer to a long by unsigned conversion.
This method is equivalent to toUnsignedLong for API 26+.
transformFutureAsync
@UnstableApi
public static ListenableFuture<T> <T, U> transformFutureAsync(
ListenableFuture<U> future,
AsyncFunction<U, T> transformFunction
)
Asynchronously transforms the result of a ListenableFuture.
The transformation function is called using a direct executor.
The returned Future attempts to keep its cancellation state in sync with that of the input future and that of the future returned by the transform function. That is, if the returned Future is cancelled, it will attempt to cancel the other two, and if either of the other two is cancelled, the returned Future will also be cancelled. All forwarded cancellations will not attempt to interrupt.
| Parameters | |
|---|---|
<T> |
The result type of the input future. |
<U> |
The result type of the transformation function. |
ListenableFuture<U> future |
The input |
AsyncFunction<U, T> transformFunction |
The function transforming the result of the input future. |
| Returns | |
|---|---|
ListenableFuture<T> |
A |
unescapeFileName
@UnstableApi
public static @Nullable String unescapeFileName(String fileName)
Unescapes an escaped file or directory name back to its original value.
See escapeFileName for more information.
| Parameters | |
|---|---|
String fileName |
File name to be unescaped. |
usToMs
@UnstableApi
public static long usToMs(long timeUs)
Converts a time in microseconds to the corresponding time in milliseconds, preserving TIME_UNSET and TIME_END_OF_SOURCE values.
| Parameters | |
|---|---|
long timeUs |
The time in microseconds. |
| Returns | |
|---|---|
long |
The corresponding time in milliseconds. |
writeBoolean
@UnstableApi
public static void writeBoolean(Parcel parcel, boolean value)
Writes a boolean to a Parcel. The boolean is written as an integer with value 1 (true) or 0 (false).