/
Util.java
3103 lines (2930 loc) · 116 KB
/
Util.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.media3.common.util;
import static android.content.Context.UI_MODE_SERVICE;
import static androidx.media3.common.Player.COMMAND_SEEK_BACK;
import static androidx.media3.common.Player.COMMAND_SEEK_FORWARD;
import static androidx.media3.common.Player.COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM;
import static androidx.media3.common.Player.COMMAND_SEEK_TO_DEFAULT_POSITION;
import static androidx.media3.common.Player.COMMAND_SEEK_TO_MEDIA_ITEM;
import static androidx.media3.common.Player.COMMAND_SEEK_TO_NEXT;
import static androidx.media3.common.Player.COMMAND_SEEK_TO_NEXT_MEDIA_ITEM;
import static androidx.media3.common.Player.COMMAND_SEEK_TO_PREVIOUS;
import static androidx.media3.common.Player.COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM;
import static androidx.media3.common.util.Assertions.checkNotNull;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.Manifest.permission;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.UiModeManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Point;
import android.hardware.display.DisplayManager;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.MediaDrm;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Parcel;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.security.NetworkSecurityPolicy;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.SparseLongArray;
import android.view.Display;
import android.view.SurfaceView;
import android.view.WindowManager;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.media3.common.C;
import androidx.media3.common.C.ContentType;
import androidx.media3.common.Format;
import androidx.media3.common.MediaItem;
import androidx.media3.common.MediaLibraryInfo;
import androidx.media3.common.MimeTypes;
import androidx.media3.common.ParserException;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.common.Player.Commands;
import com.google.common.base.Ascii;
import com.google.common.base.Charsets;
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Formatter;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.NoSuchElementException;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.DataFormatException;
import java.util.zip.GZIPOutputStream;
import java.util.zip.Inflater;
import org.checkerframework.checker.initialization.qual.UnknownInitialization;
import org.checkerframework.checker.nullness.compatqual.NullableType;
import org.checkerframework.checker.nullness.qual.EnsuresNonNull;
import org.checkerframework.checker.nullness.qual.PolyNull;
/** Miscellaneous utility methods. */
public final class Util {
/**
* Like {@link Build.VERSION#SDK_INT}, but in a place where it can be conveniently overridden for
* local testing.
*/
@UnstableApi public static final int SDK_INT = Build.VERSION.SDK_INT;
/**
* Like {@link Build#DEVICE}, but in a place where it can be conveniently overridden for local
* testing.
*/
@UnstableApi public static final String DEVICE = Build.DEVICE;
/**
* Like {@link Build#MANUFACTURER}, but in a place where it can be conveniently overridden for
* local testing.
*/
@UnstableApi public static final String MANUFACTURER = Build.MANUFACTURER;
/**
* Like {@link Build#MODEL}, but in a place where it can be conveniently overridden for local
* testing.
*/
@UnstableApi public static final String MODEL = Build.MODEL;
/** A concise description of the device that it can be useful to log for debugging purposes. */
@UnstableApi
public static final String DEVICE_DEBUG_INFO =
DEVICE + ", " + MODEL + ", " + MANUFACTURER + ", " + SDK_INT;
/** An empty byte array. */
@UnstableApi public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
private static final String TAG = "Util";
private static final Pattern XS_DATE_TIME_PATTERN =
Pattern.compile(
"(\\d\\d\\d\\d)\\-(\\d\\d)\\-(\\d\\d)[Tt]"
+ "(\\d\\d):(\\d\\d):(\\d\\d)([\\.,](\\d+))?"
+ "([Zz]|((\\+|\\-)(\\d?\\d):?(\\d\\d)))?");
private static final Pattern XS_DURATION_PATTERN =
Pattern.compile(
"^(-)?P(([0-9]*)Y)?(([0-9]*)M)?(([0-9]*)D)?"
+ "(T(([0-9]*)H)?(([0-9]*)M)?(([0-9.]*)S)?)?$");
private static final Pattern ESCAPED_CHARACTER_PATTERN = Pattern.compile("%([A-Fa-f0-9]{2})");
// https://docs.microsoft.com/en-us/azure/media-services/previous/media-services-deliver-content-overview#URLs
private static final Pattern ISM_PATH_PATTERN =
Pattern.compile("(?:.*\\.)?isml?(?:/(manifest(.*))?)?", Pattern.CASE_INSENSITIVE);
private static final String ISM_HLS_FORMAT_EXTENSION = "format=m3u8-aapl";
private static final String ISM_DASH_FORMAT_EXTENSION = "format=mpd-time-csf";
// Replacement map of ISO language codes used for normalization.
@Nullable private static HashMap<String, String> languageTagReplacementMap;
private Util() {}
/**
* Converts the entirety of an {@link InputStream} to a byte array.
*
* @param inputStream the {@link InputStream} to be read. The input stream is not closed by this
* method.
* @return a byte array containing all of the inputStream's bytes.
* @throws IOException if an error occurs reading from the stream.
*/
@UnstableApi
public static byte[] toByteArray(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024 * 4];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
return outputStream.toByteArray();
}
/**
* Registers a {@link BroadcastReceiver} that's not intended to receive broadcasts from other
* apps. This will be enforced by specifying {@link Context#RECEIVER_NOT_EXPORTED} if {@link
* #SDK_INT} is 33 or above.
*
* @param context The context on which {@link Context#registerReceiver} will be called.
* @param receiver The {@link BroadcastReceiver} to register. This value may be null.
* @param filter Selects the Intent broadcasts to be received.
* @return The first sticky intent found that matches {@code filter}, or null if there are none.
*/
@UnstableApi
@Nullable
public static Intent registerReceiverNotExported(
Context context, @Nullable BroadcastReceiver receiver, IntentFilter filter) {
if (SDK_INT < 33) {
return context.registerReceiver(receiver, filter);
} else {
return context.registerReceiver(receiver, filter, Context.RECEIVER_NOT_EXPORTED);
}
}
/**
* Registers a {@link BroadcastReceiver} that's not intended to receive broadcasts from other
* apps. This will be enforced by specifying {@link Context#RECEIVER_NOT_EXPORTED} if {@link
* #SDK_INT} is 33 or above.
*
* @param context The context on which {@link Context#registerReceiver} will be called.
* @param receiver The {@link BroadcastReceiver} to register. This value may be null.
* @param filter Selects the Intent broadcasts to be received.
* @param handler Handler identifying the thread that will receive the Intent.
* @return The first sticky intent found that matches {@code filter}, or null if there are none.
*/
@UnstableApi
@Nullable
public static Intent registerReceiverNotExported(
Context context, BroadcastReceiver receiver, IntentFilter filter, Handler handler) {
if (SDK_INT < 33) {
return context.registerReceiver(receiver, filter, /* broadcastPermission= */ null, handler);
} else {
return context.registerReceiver(
receiver,
filter,
/* broadcastPermission= */ null,
handler,
Context.RECEIVER_NOT_EXPORTED);
}
}
/**
* Calls {@link Context#startForegroundService(Intent)} if {@link #SDK_INT} is 26 or higher, or
* {@link Context#startService(Intent)} otherwise.
*
* @param context The context to call.
* @param intent The intent to pass to the called method.
* @return The result of the called method.
*/
@UnstableApi
@Nullable
public static ComponentName startForegroundService(Context context, Intent intent) {
if (SDK_INT >= 26) {
return context.startForegroundService(intent);
} else {
return context.startService(intent);
}
}
/**
* Checks whether it's necessary to request the {@link permission#READ_EXTERNAL_STORAGE}
* permission read the specified {@link Uri}s, requesting the permission if necessary.
*
* @param activity The host activity for checking and requesting the permission.
* @param uris {@link Uri}s that may require {@link permission#READ_EXTERNAL_STORAGE} to read.
* @return Whether a permission request was made.
*/
public static boolean maybeRequestReadExternalStoragePermission(Activity activity, Uri... uris) {
if (SDK_INT < 23) {
return false;
}
for (Uri uri : uris) {
if (maybeRequestReadExternalStoragePermission(activity, uri)) {
return true;
}
}
return false;
}
/**
* Checks whether it's necessary to request the {@link permission#READ_EXTERNAL_STORAGE}
* permission for the specified {@link MediaItem media items}, requesting the permission if
* necessary.
*
* @param activity The host activity for checking and requesting the permission.
* @param mediaItems {@link MediaItem Media items}s that may require {@link
* permission#READ_EXTERNAL_STORAGE} to read.
* @return Whether a permission request was made.
*/
public static boolean maybeRequestReadExternalStoragePermission(
Activity activity, MediaItem... mediaItems) {
if (SDK_INT < 23) {
return false;
}
for (MediaItem mediaItem : mediaItems) {
if (mediaItem.localConfiguration == null) {
continue;
}
if (maybeRequestReadExternalStoragePermission(activity, mediaItem.localConfiguration.uri)) {
return true;
}
List<MediaItem.SubtitleConfiguration> subtitleConfigs =
mediaItem.localConfiguration.subtitleConfigurations;
for (int i = 0; i < subtitleConfigs.size(); i++) {
if (maybeRequestReadExternalStoragePermission(activity, subtitleConfigs.get(i).uri)) {
return true;
}
}
}
return false;
}
private static boolean maybeRequestReadExternalStoragePermission(Activity activity, Uri uri) {
return SDK_INT >= 23
&& (isLocalFileUri(uri) || isMediaStoreExternalContentUri(uri))
&& requestExternalStoragePermission(activity);
}
private static boolean isMediaStoreExternalContentUri(Uri uri) {
if (!"content".equals(uri.getScheme()) || !MediaStore.AUTHORITY.equals(uri.getAuthority())) {
return false;
}
List<String> pathSegments = uri.getPathSegments();
if (pathSegments.isEmpty()) {
return false;
}
String firstPathSegment = pathSegments.get(0);
return MediaStore.VOLUME_EXTERNAL.equals(firstPathSegment)
|| MediaStore.VOLUME_EXTERNAL_PRIMARY.equals(firstPathSegment);
}
/**
* 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.
*
* @param mediaItems A list of {@link MediaItem media items}.
* @return Whether it may be possible to load the URIs of the given media items.
*/
public static boolean checkCleartextTrafficPermitted(MediaItem... mediaItems) {
if (SDK_INT < 24) {
// We assume cleartext traffic is permitted.
return true;
}
for (MediaItem mediaItem : mediaItems) {
if (mediaItem.localConfiguration == null) {
continue;
}
if (isTrafficRestricted(mediaItem.localConfiguration.uri)) {
return false;
}
for (int i = 0; i < mediaItem.localConfiguration.subtitleConfigurations.size(); i++) {
if (isTrafficRestricted(mediaItem.localConfiguration.subtitleConfigurations.get(i).uri)) {
return false;
}
}
}
return true;
}
/**
* Returns true if the URI is a path to a local file or a reference to a local file.
*
* @param uri The uri to test.
*/
@UnstableApi
public static boolean isLocalFileUri(Uri uri) {
String scheme = uri.getScheme();
return TextUtils.isEmpty(scheme) || "file".equals(scheme);
}
/**
* Tests two objects for {@link Object#equals(Object)} equality, handling the case where one or
* both may be null.
*
* @param o1 The first object.
* @param o2 The second object.
* @return {@code o1 == null ? o2 == null : o1.equals(o2)}.
*/
@UnstableApi
public static boolean areEqual(@Nullable Object o1, @Nullable Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
/**
* Tests whether an {@code items} array contains an object equal to {@code item}, according to
* {@link Object#equals(Object)}.
*
* <p>If {@code item} is null then true is returned if and only if {@code items} contains null.
*
* @param items The array of items to search.
* @param item The item to search for.
* @return True if the array contains an object equal to the item being searched for.
*/
@UnstableApi
public static boolean contains(@NullableType Object[] items, @Nullable Object item) {
for (Object arrayItem : items) {
if (areEqual(arrayItem, item)) {
return true;
}
}
return false;
}
/**
* Removes an indexed range from a List.
*
* <p>Does nothing if the provided range is valid and {@code fromIndex == toIndex}.
*
* @param list The List to remove the range from.
* @param fromIndex The first index to be removed (inclusive).
* @param toIndex The last index to be removed (exclusive).
* @throws IllegalArgumentException If {@code fromIndex} < 0, {@code toIndex} > {@code
* list.size()}, or {@code fromIndex} > {@code toIndex}.
*/
@UnstableApi
public static <T> void removeRange(List<T> list, int fromIndex, int toIndex) {
if (fromIndex < 0 || toIndex > list.size() || fromIndex > toIndex) {
throw new IllegalArgumentException();
} else if (fromIndex != toIndex) {
// Checking index inequality prevents an unnecessary allocation.
list.subList(fromIndex, toIndex).clear();
}
}
/**
* Casts a nullable variable to a non-null variable without runtime null check.
*
* <p>Use {@link Assertions#checkNotNull(Object)} to throw if the value is null.
*/
@UnstableApi
@SuppressWarnings({"nullness:contracts.postcondition", "nullness:return"})
@EnsuresNonNull("#1")
public static <T> T castNonNull(@Nullable T value) {
return value;
}
/** Casts a nullable type array to a non-null type array without runtime null check. */
@UnstableApi
@SuppressWarnings({"nullness:contracts.postcondition", "nullness:return"})
@EnsuresNonNull("#1")
public static <T> T[] castNonNullTypeArray(@NullableType T[] value) {
return value;
}
/**
* Copies and optionally truncates an array. Prevents null array elements created by {@link
* Arrays#copyOf(Object[], int)} by ensuring the new length does not exceed the current length.
*
* @param input The input array.
* @param length The output array length. Must be less or equal to the length of the input array.
* @return The copied array.
*/
@UnstableApi
@SuppressWarnings({"nullness:argument", "nullness:return"})
public static <T> T[] nullSafeArrayCopy(T[] input, int length) {
Assertions.checkArgument(length <= input.length);
return Arrays.copyOf(input, length);
}
/**
* Copies a subset of an array.
*
* @param input The input array.
* @param from The start the range to be copied, inclusive
* @param to The end of the range to be copied, exclusive.
* @return The copied array.
*/
@UnstableApi
@SuppressWarnings({"nullness:argument", "nullness:return"})
public static <T> T[] nullSafeArrayCopyOfRange(T[] input, int from, int to) {
Assertions.checkArgument(0 <= from);
Assertions.checkArgument(to <= input.length);
return Arrays.copyOfRange(input, from, to);
}
/**
* Creates a new array containing {@code original} with {@code newElement} appended.
*
* @param original The input array.
* @param newElement The element to append.
* @return The new array.
*/
@UnstableApi
public static <T> T[] nullSafeArrayAppend(T[] original, T newElement) {
@NullableType T[] result = Arrays.copyOf(original, original.length + 1);
result[original.length] = newElement;
return castNonNullTypeArray(result);
}
/**
* Creates a new array containing the concatenation of two non-null type arrays.
*
* @param first The first array.
* @param second The second array.
* @return The concatenated result.
*/
@UnstableApi
@SuppressWarnings("nullness:assignment")
public static <T> T[] nullSafeArrayConcatenation(T[] first, T[] second) {
T[] concatenation = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(
/* src= */ second,
/* srcPos= */ 0,
/* dest= */ concatenation,
/* destPos= */ first.length,
/* length= */ second.length);
return concatenation;
}
/**
* Copies the contents of {@code list} into {@code array}.
*
* <p>{@code list.size()} must be the same as {@code array.length} to ensure the contents can be
* copied into {@code array} without leaving any nulls at the end.
*
* @param list The list to copy items from.
* @param array The array to copy items to.
*/
@UnstableApi
@SuppressWarnings("nullness:toArray.nullable.elements.not.newarray")
public static <T> void nullSafeListToArray(List<T> list, T[] array) {
Assertions.checkState(list.size() == array.length);
list.toArray(array);
}
/**
* Creates a {@link Handler} on the current {@link Looper} thread.
*
* @throws IllegalStateException If the current thread doesn't have a {@link Looper}.
*/
@UnstableApi
public static Handler createHandlerForCurrentLooper() {
return createHandlerForCurrentLooper(/* callback= */ null);
}
/**
* Creates a {@link Handler} with the specified {@link Handler.Callback} on the current {@link
* Looper} thread.
*
* <p>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.
*
* @param callback A {@link Handler.Callback}. May be a partially initialized class, or null if no
* callback is required.
* @return A {@link Handler} with the specified callback on the current {@link Looper} thread.
* @throws IllegalStateException If the current thread doesn't have a {@link Looper}.
*/
@UnstableApi
public static Handler createHandlerForCurrentLooper(
@Nullable Handler.@UnknownInitialization Callback callback) {
return createHandler(Assertions.checkStateNotNull(Looper.myLooper()), callback);
}
/**
* Creates a {@link Handler} on the current {@link Looper} thread.
*
* <p>If the current thread doesn't have a {@link Looper}, the application's main thread {@link
* Looper} is used.
*/
@UnstableApi
public static Handler createHandlerForCurrentOrMainLooper() {
return createHandlerForCurrentOrMainLooper(/* callback= */ null);
}
/**
* Creates a {@link Handler} with the specified {@link Handler.Callback} on the current {@link
* Looper} thread.
*
* <p>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.
*
* <p>If the current thread doesn't have a {@link Looper}, the application's main thread {@link
* Looper} is used.
*
* @param callback A {@link Handler.Callback}. May be a partially initialized class, or null if no
* callback is required.
* @return A {@link Handler} with the specified callback on the current {@link Looper} thread.
*/
@UnstableApi
public static Handler createHandlerForCurrentOrMainLooper(
@Nullable Handler.@UnknownInitialization Callback callback) {
return createHandler(getCurrentOrMainLooper(), callback);
}
/**
* Creates a {@link Handler} with the specified {@link Handler.Callback} on the specified {@link
* Looper} thread.
*
* <p>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.
*
* @param looper A {@link Looper} to run the callback on.
* @param callback A {@link Handler.Callback}. May be a partially initialized class, or null if no
* callback is required.
* @return A {@link Handler} with the specified callback on the current {@link Looper} thread.
*/
@UnstableApi
@SuppressWarnings({"nullness:argument", "nullness:return"})
public static Handler createHandler(
Looper looper, @Nullable Handler.@UnknownInitialization Callback callback) {
return new Handler(looper, callback);
}
/**
* Posts the {@link Runnable} if the calling thread differs with the {@link Looper} of the {@link
* Handler}. Otherwise, runs the {@link Runnable} directly.
*
* @param handler The handler to which the {@link Runnable} will be posted.
* @param runnable The runnable to either post or run.
* @return {@code true} if the {@link Runnable} was successfully posted to the {@link Handler} or
* run. {@code false} otherwise.
*/
@UnstableApi
public static boolean postOrRun(Handler handler, Runnable runnable) {
Looper looper = handler.getLooper();
if (!looper.getThread().isAlive()) {
return false;
}
if (handler.getLooper() == Looper.myLooper()) {
runnable.run();
return true;
} else {
return handler.post(runnable);
}
}
/**
* Posts the {@link Runnable} if the calling thread differs with the {@link Looper} of the {@link
* Handler}. Otherwise, runs the {@link Runnable} directly. Also returns a {@link
* ListenableFuture} for when the {@link Runnable} has run.
*
* @param handler The handler to which the {@link Runnable} will be posted.
* @param runnable The runnable to either post or run.
* @param successValue The value to set in the {@link ListenableFuture} once the runnable
* completes.
* @param <T> The type of {@code successValue}.
* @return A {@link ListenableFuture} for when the {@link Runnable} has run.
*/
@UnstableApi
public static <T> ListenableFuture<T> postOrRunWithCompletion(
Handler handler, Runnable runnable, T successValue) {
SettableFuture<T> outputFuture = SettableFuture.create();
postOrRun(
handler,
() -> {
try {
if (outputFuture.isCancelled()) {
return;
}
runnable.run();
outputFuture.set(successValue);
} catch (Throwable e) {
outputFuture.setException(e);
}
});
return outputFuture;
}
/**
* Asynchronously transforms the result of a {@link ListenableFuture}.
*
* <p>The transformation function is called using a {@linkplain MoreExecutors#directExecutor()
* direct executor}.
*
* <p>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.
*
* @param future The input {@link ListenableFuture}.
* @param transformFunction The function transforming the result of the input future.
* @param <T> The result type of the input future.
* @param <U> The result type of the transformation function.
* @return A {@link ListenableFuture} for the transformed result.
*/
@UnstableApi
public static <T, U> ListenableFuture<T> transformFutureAsync(
ListenableFuture<U> future, AsyncFunction<U, T> transformFunction) {
// This is a simplified copy of Guava's Futures.transformAsync.
SettableFuture<T> outputFuture = SettableFuture.create();
outputFuture.addListener(
() -> {
if (outputFuture.isCancelled()) {
future.cancel(/* mayInterruptIfRunning= */ false);
}
},
MoreExecutors.directExecutor());
future.addListener(
() -> {
U inputFutureResult;
try {
inputFutureResult = Futures.getDone(future);
} catch (CancellationException cancellationException) {
outputFuture.cancel(/* mayInterruptIfRunning= */ false);
return;
} catch (ExecutionException exception) {
@Nullable Throwable cause = exception.getCause();
outputFuture.setException(cause == null ? exception : cause);
return;
} catch (RuntimeException | Error error) {
outputFuture.setException(error);
return;
}
try {
outputFuture.setFuture(transformFunction.apply(inputFutureResult));
} catch (Throwable exception) {
outputFuture.setException(exception);
}
},
MoreExecutors.directExecutor());
return outputFuture;
}
/**
* Returns the {@link Looper} associated with the current thread, or the {@link Looper} of the
* application's main thread if the current thread doesn't have a {@link Looper}.
*/
@UnstableApi
public static Looper getCurrentOrMainLooper() {
@Nullable Looper myLooper = Looper.myLooper();
return myLooper != null ? myLooper : Looper.getMainLooper();
}
/**
* Instantiates a new single threaded executor whose thread has the specified name.
*
* @param threadName The name of the thread.
* @return The executor.
*/
@UnstableApi
public static ExecutorService newSingleThreadExecutor(String threadName) {
return Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, threadName));
}
/**
* Closes a {@link Closeable}, suppressing any {@link IOException} that may occur. Both {@link
* java.io.OutputStream} and {@link InputStream} are {@code Closeable}.
*
* @param closeable The {@link Closeable} to close.
*/
@UnstableApi
public static void closeQuietly(@Nullable Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException e) {
// Ignore.
}
}
/**
* Reads an integer from a {@link Parcel} and interprets it as a boolean, with 0 mapping to false
* and all other values mapping to true.
*
* @param parcel The {@link Parcel} to read from.
* @return The read value.
*/
@UnstableApi
public static boolean readBoolean(Parcel parcel) {
return parcel.readInt() != 0;
}
/**
* Writes a boolean to a {@link Parcel}. The boolean is written as an integer with value 1 (true)
* or 0 (false).
*
* @param parcel The {@link Parcel} to write to.
* @param value The value to write.
*/
@UnstableApi
public static void writeBoolean(Parcel parcel, boolean value) {
parcel.writeInt(value ? 1 : 0);
}
/**
* Returns the language tag for a {@link Locale}.
*
* <p>For API levels ≥ 21, this tag is IETF BCP 47 compliant. Use {@link
* #normalizeLanguageCode(String)} to retrieve a normalized IETF BCP 47 language tag for all API
* levels if needed.
*
* @param locale A {@link Locale}.
* @return The language tag.
*/
@UnstableApi
public static String getLocaleLanguageTag(Locale locale) {
return SDK_INT >= 21 ? getLocaleLanguageTagV21(locale) : locale.toString();
}
/**
* Returns a normalized IETF BCP 47 language tag for {@code language}.
*
* @param language A case-insensitive language code supported by {@link
* Locale#forLanguageTag(String)}.
* @return The all-lowercase normalized code, or null if the input was null, or {@code
* language.toLowerCase()} if the language could not be normalized.
*/
@UnstableApi
public static @PolyNull String normalizeLanguageCode(@PolyNull String language) {
if (language == null) {
return null;
}
// Locale data (especially for API < 21) may produce tags with '_' instead of the
// standard-conformant '-'.
String normalizedTag = language.replace('_', '-');
if (normalizedTag.isEmpty() || normalizedTag.equals(C.LANGUAGE_UNDETERMINED)) {
// Tag isn't valid, keep using the original.
normalizedTag = language;
}
normalizedTag = Ascii.toLowerCase(normalizedTag);
String mainLanguage = splitAtFirst(normalizedTag, "-")[0];
if (languageTagReplacementMap == null) {
languageTagReplacementMap = createIsoLanguageReplacementMap();
}
@Nullable String replacedLanguage = languageTagReplacementMap.get(mainLanguage);
if (replacedLanguage != null) {
normalizedTag =
replacedLanguage + normalizedTag.substring(/* beginIndex= */ mainLanguage.length());
mainLanguage = replacedLanguage;
}
if ("no".equals(mainLanguage) || "i".equals(mainLanguage) || "zh".equals(mainLanguage)) {
normalizedTag = maybeReplaceLegacyLanguageTags(normalizedTag);
}
return normalizedTag;
}
/**
* Returns a new {@link String} constructed by decoding UTF-8 encoded bytes.
*
* @param bytes The UTF-8 encoded bytes to decode.
* @return The string.
*/
@UnstableApi
public static String fromUtf8Bytes(byte[] bytes) {
return new String(bytes, Charsets.UTF_8);
}
/**
* Returns a new {@link String} constructed by decoding UTF-8 encoded bytes in a subarray.
*
* @param bytes The UTF-8 encoded bytes to decode.
* @param offset The index of the first byte to decode.
* @param length The number of bytes to decode.
* @return The string.
*/
@UnstableApi
public static String fromUtf8Bytes(byte[] bytes, int offset, int length) {
return new String(bytes, offset, length, Charsets.UTF_8);
}
/**
* Returns a new byte array containing the code points of a {@link String} encoded using UTF-8.
*
* @param value The {@link String} whose bytes should be obtained.
* @return The code points encoding using UTF-8.
*/
@UnstableApi
public static byte[] getUtf8Bytes(String value) {
return value.getBytes(Charsets.UTF_8);
}
/**
* Splits a string using {@code value.split(regex, -1}). Note: this is is similar to {@link
* String#split(String)} but empty matches at the end of the string will not be omitted from the
* returned array.
*
* @param value The string to split.
* @param regex A delimiting regular expression.
* @return The array of strings resulting from splitting the string.
*/
@UnstableApi
public static String[] split(String value, String regex) {
return value.split(regex, /* limit= */ -1);
}
/**
* Splits the string at the first occurrence of the delimiter {@code 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.
*
* @param value The string.
* @param regex A delimiting regular expression.
* @return The string split by the first occurrence of the delimiter.
*/
@UnstableApi
public static String[] splitAtFirst(String value, String regex) {
return value.split(regex, /* limit= */ 2);
}
/**
* Returns whether the given character is a carriage return ('\r') or a line feed ('\n').
*
* @param c The character.
* @return Whether the given character is a linebreak.
*/
@UnstableApi
public static boolean isLinebreak(int c) {
return c == '\n' || c == '\r';
}
/**
* Formats a string using {@link Locale#US}.
*
* @see String#format(String, Object...)
*/
@UnstableApi
public static String formatInvariant(String format, Object... args) {
return String.format(Locale.US, format, args);
}
/**
* Divides a {@code numerator} by a {@code denominator}, returning the ceiled result.
*
* @param numerator The numerator to divide.
* @param denominator The denominator to divide by.
* @return The ceiled result of the division.
*/
@UnstableApi
public static int ceilDivide(int numerator, int denominator) {
return (numerator + denominator - 1) / denominator;
}
/**
* Divides a {@code numerator} by a {@code denominator}, returning the ceiled result.
*
* @param numerator The numerator to divide.
* @param denominator The denominator to divide by.
* @return The ceiled result of the division.
*/
@UnstableApi
public static long ceilDivide(long numerator, long denominator) {
return (numerator + denominator - 1) / denominator;
}
/**
* Constrains a value to the specified bounds.
*
* @param value The value to constrain.
* @param min The lower bound.
* @param max The upper bound.
* @return The constrained value {@code Math.max(min, Math.min(value, max))}.
*/
@UnstableApi
public static int constrainValue(int value, int min, int max) {
return max(min, min(value, max));
}
/**
* Constrains a value to the specified bounds.
*
* @param value The value to constrain.
* @param min The lower bound.
* @param max The upper bound.
* @return The constrained value {@code Math.max(min, Math.min(value, max))}.
*/
@UnstableApi
public static long constrainValue(long value, long min, long max) {
return max(min, min(value, max));
}
/**
* Constrains a value to the specified bounds.
*
* @param value The value to constrain.
* @param min The lower bound.
* @param max The upper bound.
* @return The constrained value {@code Math.max(min, Math.min(value, max))}.
*/
@UnstableApi
public static float constrainValue(float value, float min, float max) {
return max(min, min(value, max));
}
/**
* Returns the sum of two arguments, or a third argument if the result overflows.
*
* @param x The first value.
* @param y The second value.
* @param overflowResult The return value if {@code x + y} overflows.
* @return {@code x + y}, or {@code overflowResult} if the result overflows.
*/
@UnstableApi
public static long addWithOverflowDefault(long x, long y, long overflowResult) {
long result = x + y;
// See Hacker's Delight 2-13 (H. Warren Jr).
if (((x ^ result) & (y ^ result)) < 0) {
return overflowResult;
}
return result;
}