public final class Util


Miscellaneous utility methods.

Summary

Constants

static final String

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

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

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

static final String

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

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 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

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

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
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 = 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

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

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

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

MODEL

@UnstableApi
public static final String MODEL

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

SDK_INT

@UnstableApi
public static final int SDK_INT

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

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 x + y overflows.

Returns
long

x + y, or overflowResult if the result overflows.

areEqual

@UnstableApi
@InlineMe(replacement = "Objects.equals(o1, o2)", imports = [""java.util.Objects""])
public static boolean areEqual(@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 (a.length - 1) will be returned in the case that the value is greater than the largest element in the array. If false then a.length will be returned.

Returns
int

The index of the smallest element in array that is greater than (or optionally equal to) value.

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 (a.length - 1) will be returned in the case that the value is greater than the largest element in the array. If false then a.length will be returned.

Returns
int

The index of the smallest element in array that is greater than (or optionally equal to) value.

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 (list.size() - 1) will be returned in the case that the value is greater than the largest element in the list. If false then list.size() will be returned.

Returns
int

The index of the smallest element in list that is greater than (or optionally equal to) value.

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 array that is less than (or optionally equal to) value.

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 array that is less than (or optionally equal to) value.

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 list that is less than (or optionally equal to) value.

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 array that is less than (or optionally equal to) value.

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 media items.

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 and InputStream are Closeable.

Parameters
@Nullable Closeable closeable

The Closeable to close.

compareLong

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

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

Parameters
long left

The left operand.

long right

The right operand.

Returns
int

0, if left == right, a negative value if left 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 Math.max(min, Math.min(value, max)).

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 Math.max(min, Math.min(value, max)).

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 Math.max(min, Math.min(value, max)).

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 SparseArray instance.

@Nullable SparseArray<T> sparseArray2

The second SparseArray instance.

Returns
boolean

True if the two SparseArray instances are equal in contents.

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 SparseArray instance.

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 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 Looper to run the callback on.

@Nullable @UnknownInitialization Handler.Callback callback

A Handler.Callback. May be a partially initialized class, or null if no callback is required.

Returns
Handler

A Handler with the specified callback on the current Looper thread.

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 Looper.

createHandlerForCurrentLooper

@UnstableApi
public static Handler createHandlerForCurrentLooper(
    @Nullable @UnknownInitialization Handler.Callback callback
)

Creates a Handler with the specified Handler.Callback on the current 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 Handler.Callback. May be a partially initialized class, or null if no callback is required.

Returns
Handler

A Handler with the specified callback on the current Looper thread.

Throws
java.lang.IllegalStateException

If the current thread doesn't have a Looper.

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 is used.

createHandlerForCurrentOrMainLooper

@UnstableApi
public static Handler createHandlerForCurrentOrMainLooper(
    @Nullable @UnknownInitialization Handler.Callback callback
)

Creates a Handler with the specified Handler.Callback on the current 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 is used.

Parameters
@Nullable @UnknownInitialization Handler.Callback callback

A Handler.Callback. May be a partially initialized class, or null if no callback is required.

Returns
Handler

A Handler with the specified callback on the current Looper thread.

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 of the original buffer.

createTempDirectory

@UnstableApi
public static File createTempDirectory(Context context, String prefix)

Creates an empty directory in the directory returned by getCacheDir.

createTempFile

@UnstableApi
public static File createTempFile(Context context, String prefix)

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

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 durationUs.

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 ERROR if an error occurred in which case audio playback may fail.

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 int getAudioContentTypeForStreamType(@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 CHANNEL_INVALID if output is not possible.

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.

Player.Commands permanentAvailableCommands

The commands permanently available in the player.

Returns
Player.Commands

The available Commands.

getBigEndianInt

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

Absolute get method for reading an int value in BIG_ENDIAN in a . 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.

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 track type.

Returns
@Nullable String

A copy of codecs without the codecs whose track type doesn't match trackType. If this ends up empty, or codecs is null, returns null.

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.

Parameters
Context context

Any context.

Display display

The display whose size is to be returned.

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.

getDefaultDisplayLocale

@UnstableApi
public static Locale getDefaultDisplayLocale()

Returns the default DISPLAYLocale.

getDrawable

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

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

Parameters
Context context

The context to get the theme from starting with API 21.

Resources resources

The resources to load the drawable from.

@DrawableRes int drawableRes

The drawable resource int.

Returns
Drawable

The loaded Drawable.

getDrmUuid

public static @Nullable UUID getDrmUuid(String drmScheme)

Derives a DRM UUID from drmScheme.

Parameters
String drmScheme

A UUID string, or "widevine", "playready" or "clearkey".

Returns
@Nullable UUID

The derived UUID, or null if one could not be derived.

getErrorCodeForMediaDrmErrorCode

@UnstableApi
@PlaybackException.ErrorCode
public static int getErrorCodeForMediaDrmErrorCode(int mediaDrmErrorCode)

Returns a PlaybackException.ErrorCode value that corresponds to the provided 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.

Parameters
@Nullable String diagnosticsInfo

A string from which to parse the error code.

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 C.FormatSupport flag.

Returns
String

A string representation of the flag.

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.

Parameters
Locale locale

A Locale.

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 playoutDuration.

getNowUnixTimeMs

@UnstableApi
public static long getNowUnixTimeMs(long elapsedRealtimeEpochOffsetMs)

Returns the current time in milliseconds since the epoch.

Parameters
long elapsedRealtimeEpochOffsetMs

The offset between elapsedRealtime and the time since the Unix epoch, or TIME_UNSET if unknown.

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 PCM encoding constant.

Parameters
int bitDepth

The bit depth. Supported values are 8, 16, 24 and 32.

Returns
int

The corresponding encoding. One of ENCODING_PCM_8BIT, ENCODING_PCM_16BIT, ENCODING_PCM_24BIT and ENCODING_PCM_32BIT. If the bit depth is unsupported then ENCODING_INVALID is returned.

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 C.PcmEncoding.

int channels

The number of channels, or NO_VALUE if unknown.

int sampleRate

The sample rate in Hz, or NO_VALUE if unknown.

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 mediaDuration.

getRoleFlagStrings

@UnstableApi
public static List<StringgetRoleFlagStrings(@C.RoleFlags int roleFlags)

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

getSelectionFlagStrings

@UnstableApi
public static List<StringgetSelectionFlagStrings(@C.SelectionFlags int selectionFlags)

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

getStreamTypeForAudioUsage

@UnstableApi
@C.StreamType
public static int getStreamTypeForAudioUsage(@C.AudioUsage int usage)

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

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 will write to.

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 C.TrackType constant,

Returns
String

A string representation of this constant.

getUserAgent

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

Parameters
String value

The String whose bytes should be obtained.

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.

Parameters
@Nullable Player player

The Player. May be null.

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.

Parameters
@Nullable Player player

The Player. May be null.

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.

Parameters
@Nullable Player player

The Player. May be null.

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 Player. May be null.

boolean playIfSuppressed

Whether to trigger a play action if playback is suppressed.

Returns
boolean

Whether a player method was triggered to handle this action.

inferContentType

@UnstableApi
@C.ContentType
public static int inferContentType(String fileName)

inferContentType

@C.ContentType
public static int inferContentType(Uri uri)

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

Parameters
Uri uri

The Uri.

Returns
int

The content type.

inferContentType

@UnstableApi
@C.ContentType
public static int inferContentType(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.

Parameters
Uri uri

The Uri.

@Nullable String mimeType

If MIME type, or null.

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 output.data isn't big enough to hold the uncompressed data, a new array is created. If true is returned then the output's position will be set to 0 and its limit will be set to the length of the uncompressed data.

@Nullable Inflater inflater

If not null, used to uncompressed the input. Otherwise a new Inflater is created.

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

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 array, or INDEX_UNSET if value is not contained in array.

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 array, or INDEX_UNSET if value is not contained in array.

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 Context.

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 SparseLongArray.

Returns
long

The maximum value.

Throws
java.util.NoSuchElementException

If the array is empty.

maybeRequestReadExternalStoragePermission

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

maybeRequestReadExternalStoragePermission

public static boolean maybeRequestReadExternalStoragePermission(
    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

Media itemss that may require storage reading permissions to read.

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 SparseLongArray.

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 forLanguageTag.

Returns
@PolyNull String

The all-lowercase normalized code, or null if the input was null, or language.toLowerCase() if the language could not be normalized.

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.

postOrRun

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

Posts the Runnable if the calling thread differs with the Looper of the . Otherwise, runs the Runnable directly.

Parameters
Handler handler

The handler to which the Runnable will be posted.

Runnable runnable

The runnable to either post or run.

Returns
boolean

true if the Runnable was successfully posted to the Handler or run. false otherwise.

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 . Otherwise, runs the Runnable directly. Also returns a for when the Runnable has run.

Parameters
<T>

The type of successValue.

Handler handler

The handler to which the Runnable will be posted.

Runnable runnable

The runnable to either post or run.

T successValue

The value to set in the ListenableFuture once the runnable completes.

Returns
ListenableFuture<T>

A ListenableFuture for when the Runnable has run.

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.

Parameters
Parcel parcel

The Parcel to read from.

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 BroadcastReceiver to register. This value may be null.

Context context

The context on which registerReceiver will be called.

IntentFilter filter

Selects the Intent broadcasts to be received.

Returns
@Nullable Intent

The first sticky intent found that matches filter, or null if there are none.

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 fromIndex<0, toIndex> list.size(), or fromIndex>toIndex.

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 sampleCount samples.

scaleLargeTimestamp

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

Scales a large timestamp.

Equivalent to scaleLargeValue with FLOOR.

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 Service.

int notificationId

The notification id.

Notification notification

The Notification.

int foregroundServiceType

The foreground service type defined in .

String foregroundServiceManifestType

The required foreground service type string for the <service> element in the manifest.

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.

Parameters
@Nullable Player player

The Player. May be null.

shouldShowPlayButton

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

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 Player. May be null.

boolean playIfSuppressed

Whether to show a play button if playback is suppressed.

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.

Parameters
String value

The string to split.

String regex

A delimiting regular expression.

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.

Parameters
String value

The string.

String regex

A delimiting regular expression.

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.

Parameters
@Nullable String codecs

A codec sequence string, as defined in RFC 6381.

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 x - y overflows.

Returns
long

x - y, or overflowResult if the result overflows.

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)

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 bytes.

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 mostSignificantBits bits and its 32 least significant bits are leastSignificantBits.

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 ListenableFuture.

AsyncFunction<U, T> transformFunction

The function transforming the result of the input future.

Returns
ListenableFuture<T>

A ListenableFuture for the transformed result.

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.

Returns
@Nullable String

The original value of the file name before it was escaped, or null if the escaped fileName seems invalid.

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).

Parameters
Parcel parcel

The Parcel to write to.

boolean value

The value to write.