public final class Util


Miscellaneous utility methods.

Summary

Constants

static final String

This field is deprecated.

Use DEVICE instead.

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 MANUFACTURER instead.

static final String

This field is deprecated.

Use MODEL instead.

static final int

Like SDK_INT, but in a place where it can be conveniently overridden for local testing.

Public methods

static long
@UnstableApi
addWithOverflowDefault(long x, long y, long overflowResult)

Returns the sum of two arguments, or a third argument if the result overflows.

static boolean
@UnstableApi
@InlineMe(replacement = "Objects.equals(o1, o2)", imports = [""java.util.Objects""])
areEqual(@Nullable Object o1, @Nullable Object o2)

This method is deprecated.

Use equals instead.

static int
@UnstableApi
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
@UnstableApi
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 int
@UnstableApi
<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.

static int
@UnstableApi
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
@UnstableApi
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
@UnstableApi
<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.

static int
@UnstableApi
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
@UnstableApi
@EnsuresNonNull(value = "#1")
<T> castNonNull(@Nullable T value)

Casts a nullable variable to a non-null variable without runtime null check.

static T[]

Casts a nullable type array to a non-null type array without runtime null check.

static int
@UnstableApi
ceilDivide(int numerator, int denominator)

Divides a numerator by a denominator, returning the ceiled result.

static long
@UnstableApi
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

Closes a Closeable, suppressing any IOException that may occur.

static int
@UnstableApi
compareLong(long left, long right)

Compares two long values and returns the same value as Long.compare(long, long).

static float
@UnstableApi
constrainValue(float value, float min, float max)

Constrains a value to the specified bounds.

static int
@UnstableApi
constrainValue(int value, int min, int max)

Constrains a value to the specified bounds.

static long
@UnstableApi
constrainValue(long value, long min, long max)

Constrains a value to the specified bounds.

static boolean
@UnstableApi
contains(@NullableType Object[] items, @Nullable Object item)

Tests whether an items array contains an object equal to item, according to equals.

static boolean
@UnstableApi
<T> contains(SparseArray<T> sparseArray, int key)

Tests whether a SparseArray contains a given key.

static boolean
@UnstableApi
<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.

static int

Returns a hash code value for the contents of this SparseArray, combining the hashCode result of all its keys and values.

static int
@UnstableApi
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.

static int
@UnstableApi
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
@UnstableApi
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

Creates a Handler with the specified Handler.Callback on the specified thread.

static Handler

Creates a Handler on the current Looper thread.

static Handler

Creates a Handler with the specified Handler.Callback on the current thread.

static Handler

Creates a Handler on the current Looper thread.

static Handler

Creates a Handler with the specified Handler.Callback on the current thread.

static ByteBuffer

Returns a read-only view of the given ByteBuffer.

static File

Creates an empty directory in the directory returned by getCacheDir.

static File

Creates a new empty file in the directory returned by getCacheDir.

static long
@UnstableApi
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.

static String

Escapes 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
@UnstableApi
formatInvariant(String format, Object[] args)

Formats a string using US.

static String
@UnstableApi
fromUtf8Bytes(byte[] bytes)

Returns a new String constructed by decoding UTF-8 encoded bytes.

static String
@UnstableApi
fromUtf8Bytes(byte[] bytes, int offset, int length)

Returns a new String constructed by decoding UTF-8 encoded bytes in a subarray.

static int

Returns a newly generated audio session identifier, or ERROR if an error occurred in which case audio playback may fail.

static @Nullable String

Returns the MIME type corresponding to the given adaptive ContentType, or null if the content type is not adaptive.

static int

Retrieves the API Level that AudioFormat introduced an encoding.

static int

This method is deprecated.

This method is no longer used by the media3 library, it does not work well and should be avoided.

static AudioFormat
@UnstableApi
getAudioFormat(int sampleRate, int channelConfig, int encoding)

Creates AudioFormat with given sampleRate, channelConfig, and encoding.

static int

Returns the audio track channel configuration for the given channel count, or CHANNEL_INVALID if output is not possible.

static int

Returns the C.AudioUsage corresponding to the specified C.StreamType.

static String

Returns a string representation of the C.AuxiliaryTrackType.

static Player.Commands
@UnstableApi
getAvailableCommands(
    Player player,
    Player.Commands permanentAvailableCommands
)

Returns the Commands available in the Player.

static int
@UnstableApi
getBigEndianInt(ByteBuffer buffer, int index)

Absolute get method for reading an int value in BIG_ENDIAN in a .

static int

Returns the byte depth for audio with the specified encoding.

static byte[]

Returns a byte array containing values parsed from the hex string provided.

static int

Returns the number of codec strings in codecs whose type matches trackType.

static @Nullable String

Returns a copy of codecs without the codecs whose track type doesn't match trackType.

static @Nullable String

Returns a copy of codecs without the codecs whose track type matches trackType.

static String

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

Gets the size of the current mode of the default display, in pixels.

static Point

Gets the size of the current mode of the specified display, in pixels.

static Looper

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.

static Uri

Returns a data URI with the specified MIME type and data.

static Locale

Returns the default DISPLAYLocale.

static Drawable
@UnstableApi
getDrawable(
    Context context,
    Resources resources,
    @DrawableRes int drawableRes
)

Returns a Drawable for the given resource or throws a if not found.

static @Nullable UUID
getDrmUuid(String drmScheme)

Derives a DRM UUID from drmScheme.

static int

Returns a PlaybackException.ErrorCode value that corresponds to the provided value.

static int

Attempts to parse an error code from a diagnostic string found in framework media exceptions.

static String

Returns string representation of a C.FormatSupport flag.

static int

Returns the integer equal to the big-endian concatenation of the characters in string as bytes.

static String

Returns the language tag for a Locale.

static int

Returns the number of maximum pending output frames that are allowed on a MediaCodec decoder.

static long
@UnstableApi
getMediaDurationForPlayoutDuration(long playoutDuration, float speed)

Returns the duration of media that will elapse in playoutDuration.

static long
@UnstableApi
getNowUnixTimeMs(long elapsedRealtimeEpochOffsetMs)

Returns the current time in milliseconds since the epoch.

static int

Converts a sample bit depth to a corresponding PCM encoding constant.

static Format

Gets a PCM Format based on the AudioProcessor.AudioFormat.

static Format
@UnstableApi
getPcmFormat(@C.PcmEncoding int pcmEncoding, int channels, int sampleRate)

Gets a PCM Format with the specified parameters.

static int
@UnstableApi
getPcmFrameSize(@C.PcmEncoding int pcmEncoding, int channelCount)

Returns the frame size for audio with channelCount channels in the specified encoding.

static long
@UnstableApi
getPlayoutDurationForMediaDuration(long mediaDuration, float speed)

Returns the playout duration of mediaDuration of media.

static List<String>

Returns a list of strings representing the C.RoleFlags values present in roleFlags.

static List<String>

Returns a list of strings representing the C.SelectionFlags values present in selectionFlags.

static int

This method is deprecated.

Use getStreamType instead.

static String
@UnstableApi
getStringForTime(
    StringBuilder builder,
    Formatter formatter,
    long timeMs
)

Returns 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

Returns a string representation of a C.TrackType.

static String
@UnstableApi
getUserAgent(Context context, String applicationName)

Returns a user agent string based on the given application name and the library version.

static byte[]

Returns a new byte array containing the code points of a String encoded using UTF-8.

static byte[]
@UnstableApi
gzip(byte[] input)

Compresses input using gzip and returns the result in a newly allocated byte array.

static boolean

Updates the player to handle an interaction with a pause button.

static boolean

Updates the player to handle an interaction with a play button.

static boolean

Updates the player to handle an interaction with a play or pause button.

static boolean
@UnstableApi
handlePlayPauseButtonAction(
    @Nullable Player player,
    boolean playIfSuppressed
)

Updates the player to handle an interaction with a play or pause button.

static int

This method is deprecated.

Use parse and inferContentType for full file paths or inferContentTypeForExtension for extensions.

static int

Makes a best guess to infer the ContentType from a Uri.

static int

This method is deprecated.

Use inferContentTypeForExtension when overrideExtension is non-empty, and inferContentType otherwise.

static int

Makes a best guess to infer the ContentType from a file extension.

static int

Makes a best guess to infer the ContentType from a Uri and optional MIME type.

static boolean
@UnstableApi
inflate(
    ParsableByteArray input,
    ParsableByteArray output,
    @Nullable Inflater inflater
)

Uncompresses the data in input.

static String

Returns a string representation of the integer using radix value MAX_RADIX.

static boolean

Returns whether the app is running on an automotive device.

static boolean

Returns the image MIME types that can be decoded and loaded by that Media3 aims to support.

static boolean

Returns whether encoding is high resolution (> 16-bit) PCM.

static boolean

Returns whether encoding is one of the linear PCM encodings.

static boolean
static boolean

Returns whether the given character is a carriage return ('\r') or a line feed ('\n').

static boolean

Returns 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

Returns whether the app is running on a TV device.

static boolean

Returns whether the app is running on a Wear OS device.

static int
@UnstableApi
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.

static int
@UnstableApi
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.

static String
@UnstableApi
loadAsset(Context context, String assetPath)

Loads a file from the assets folder.

static long

Returns the maximum value in the given SparseLongArray.

static boolean
@UnstableApi
maybeInflate(
    ParsableByteArray input,
    ParsableByteArray output,
    @Nullable Inflater inflater
)

Uncompresses the data in input if it starts with the zlib marker 0x78.

static boolean
maybeRequestReadExternalStoragePermission(
    Activity activity,
    MediaItem[] mediaItems
)

This method is deprecated.

Use maybeRequestReadStoragePermission instead.

static boolean
maybeRequestReadExternalStoragePermission(
    Activity activity,
    Uri[] uris
)

This method is deprecated.

Use maybeRequestReadStoragePermission instead.

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.

static long

Returns the minimum value in the given SparseLongArray.

static void
@UnstableApi
<T extends Object> moveItems(
    List<T> items,
    int fromIndex,
    int toIndex,
    int newFromIndex
)

Moves the elements starting at fromIndex to newFromIndex.

static long
@UnstableApi
msToUs(long timeMs)

Converts a time in milliseconds to the corresponding time in microseconds, preserving TIME_UNSET values and TIME_END_OF_SOURCE values.

static ExecutorService

Instantiates a new single threaded executor whose thread has the specified name.

static ScheduledExecutorService

Instantiates a new single threaded scheduled executor whose thread has the specified name.

static @PolyNull String

Returns a normalized IETF BCP 47 language tag for language.

static T[]
@UnstableApi
<T> nullSafeArrayAppend(T[] original, T newElement)

Creates a new array containing original with newElement appended.

static T[]
@UnstableApi
<T> nullSafeArrayConcatenation(T[] first, T[] second)

Creates a new array containing the concatenation of two non-null type arrays.

static T[]
@UnstableApi
<T> nullSafeArrayCopy(T[] input, int length)

Copies and optionally truncates an array.

static T[]
@UnstableApi
<T> nullSafeArrayCopyOfRange(T[] input, int from, int to)

Copies a subset of an array.

static void
@UnstableApi
<T> nullSafeListToArray(List<T> list, T[] array)

Copies the contents of list into array.

static long

Parses an xs:dateTime attribute value, returning the parsed timestamp in milliseconds since the epoch.

static long

Parses an xs:duration attribute value, returning the parsed duration in milliseconds.

static boolean
@UnstableApi
postOrRun(Handler handler, Runnable runnable)

Posts the Runnable if the calling thread differs with the Looper of the .

static ListenableFuture<T>
@UnstableApi
<T> postOrRunWithCompletion(
    Handler handler,
    Runnable runnable,
    T successValue
)

Posts the Runnable if the calling thread differs with the Looper of the .

static boolean

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 void
@UnstableApi
recursiveDelete(File fileOrDirectory)

Recursively deletes a directory and its content.

static @Nullable Intent
@UnstableApi
registerReceiverNotExported(
    Context context,
    @Nullable BroadcastReceiver receiver,
    IntentFilter filter
)

Registers a BroadcastReceiver that's not intended to receive broadcasts from other apps.

static void
@UnstableApi
<T> removeRange(List<T> list, int fromIndex, int toIndex)

Removes an indexed range from a List.

static long
@UnstableApi
sampleCountToDurationUs(long sampleCount, int sampleRate)

Returns the total duration (in microseconds) of sampleCount samples of equal duration at sampleRate.

static long
@UnstableApi
scaleLargeTimestamp(long timestamp, long multiplier, long divisor)

Scales a large timestamp.

static long[]
@UnstableApi
scaleLargeTimestamps(
    List<Long> timestamps,
    long multiplier,
    long divisor
)

Applies scaleLargeTimestamp to a list of unscaled timestamps.

static void
@UnstableApi
scaleLargeTimestampsInPlace(
    long[] timestamps,
    long multiplier,
    long divisor
)

Applies scaleLargeTimestamp to an array of unscaled timestamps.

static long
@UnstableApi
scaleLargeValue(
    long value,
    long multiplier,
    long divisor,
    RoundingMode roundingMode
)

Scales a large value by a multiplier and a divisor.

static long[]
@UnstableApi
scaleLargeValues(
    List<Long> values,
    long multiplier,
    long divisor,
    RoundingMode roundingMode
)

Applies scaleLargeValue to a list of unscaled values.

static void
@UnstableApi
scaleLargeValuesInPlace(
    long[] values,
    long multiplier,
    long divisor,
    RoundingMode roundingMode
)

Applies scaleLargeValue to an array of unscaled values.

static void
@UnstableApi
setForegroundServiceNotification(
    Service service,
    int notificationId,
    Notification notification,
    int foregroundServiceType,
    String foregroundServiceManifestType
)

Sets the notification required for a foreground service.

static boolean
@EnsuresNonNullIf(result = true, expression = "#1")
@UnstableApi
shouldEnablePlayPauseButton(@Nullable Player player)

Returns whether a play-pause button should be enabled or not.

static boolean
@EnsuresNonNullIf(result = false, expression = "#1")
shouldShowPlayButton(@Nullable Player player)

Returns whether a play button should be presented on a UI element for playback control.

static boolean
@UnstableApi
@EnsuresNonNullIf(result = false, expression = "#1")
shouldShowPlayButton(@Nullable Player player, boolean playIfSuppressed)

Returns whether a play button should be presented on a UI element for playback control.

static void

A hacky method that always throws t even if t is a checked exception, and is not declared to be thrown.

static String[]
@UnstableApi
split(String value, String regex)

Splits a string using value.split(regex, -1).

static String[]

Splits the string at the first occurrence of the delimiter regex.

static String[]

Splits a codecs sequence string, as defined in RFC 6381, into individual codec strings.

static @Nullable ComponentName

Calls startForegroundService if SDK_INT is 26 or higher, or startService otherwise.

static long
@UnstableApi
subtractWithOverflowDefault(long x, long y, long overflowResult)

Returns the difference between two arguments, or a third argument if the result overflows.

static long
@UnstableApi
sum(long[] summands)

Returns the sum of all summands of the given array.

static boolean

Returns whether the table exists in the database.

static byte[]

This method is deprecated.

Use Guava's toByteArray instead.

static byte[]
@UnstableApi
toByteArray(float value)

Converts a float into an equivalent byte array.

static byte[]
@UnstableApi
toByteArray(int[] values)

Converts an array of integers into an equivalent byte array.

static String
@UnstableApi
toHexString(byte[] bytes)

Returns a string containing a lower-case hex representation of the bytes provided.

static long
@UnstableApi
toLong(int mostSignificantBits, int leastSignificantBits)

Returns the long that is composed of the bits of the 2 specified integers.

static long

Converts an integer to a long by unsigned conversion.

static ListenableFuture<T>
@UnstableApi
<T, U> transformFutureAsync(
    ListenableFuture<U> future,
    AsyncFunction<U, T> transformFunction
)

Asynchronously transforms the result of a ListenableFuture.

static @Nullable String

Unescapes an escaped file or directory name back to its original value.

static long
@UnstableApi
usToMs(long timeUs)

Converts a time in microseconds to the corresponding time in milliseconds, preserving TIME_UNSET and TIME_END_OF_SOURCE values.

static void
@UnstableApi
writeBoolean(Parcel parcel, boolean value)

Writes a boolean to a Parcel.

Constants

DEVICE

@UnstableApi
public static final String DEVICE

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.

EMPTY_BYTE_ARRAY

@UnstableApi
public static final byte[] EMPTY_BYTE_ARRAY

An empty byte array.

EMPTY_LONG_ARRAY

@UnstableApi
public static final long[] EMPTY_LONG_ARRAY

An empty long array.

MANUFACTURER

@UnstableApi
public static final String MANUFACTURER

MODEL