-
Notifications
You must be signed in to change notification settings - Fork 0
/
ToastQueue.java
61 lines (49 loc) · 1.85 KB
/
ToastQueue.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
package com.lorenzostanco.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;
/**
* Enqueue toasts in order to avoid Toast overlapping occurring in Android 8.1+
* https://issuetracker.google.com/issues/79159357
*/
@SuppressWarnings("unused") public final class ToastQueue {
private static final int LONG_DELAY = 3500;
private static final int SHORT_DELAY = 2000;
private static long nextAvailableTime = 0;
private static final Object lock = new Object();
/** Shows a toast, delaying it in order to avoid Toast overlapping occurring in Android 8.1+ */
@SuppressLint("ShowToast") public static void enqueue(final Context c, final int message, final int length) {
enqueue(Toast.makeText(c, message, length));
}
/** Shows a toast, delaying it in order to avoid Toast overlapping occurring in Android 8.1+ */
@SuppressLint("ShowToast") public static void enqueue(final Context c, final String message, final int length) {
enqueue(Toast.makeText(c, message, length));
}
/** Shows an already built toast, delaying it in order to avoid Toast overlapping occurring in Android 8.1+ */
public static void enqueue(final Toast toast) {
// Compute delay
final long delay;
synchronized (lock) {
final long duration = toast.getDuration() == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY;
final long now = System.currentTimeMillis();
if (nextAvailableTime < now) {
delay = 0;
nextAvailableTime = now + duration;
} else {
delay = nextAvailableTime - now;
nextAvailableTime += duration;
}
}
// Show the toast, delaying if necessary
try {
new Handler().postDelayed(new Runnable() {
@Override public void run() {
try {
toast.show();
} catch (Exception ignored) { }
}
}, delay);
} catch (Exception ignored) { }
}
}