| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
package android.os; |
| 17 |
|
| 18 |
import android.annotation.NonNull; |
| 19 |
import android.annotation.Nullable; |
| 20 |
|
| 21 |
import java.util.concurrent.CompletableFuture; |
| 22 |
import java.util.concurrent.ExecutionException; |
| 23 |
import java.util.concurrent.TimeUnit; |
| 24 |
import java.util.concurrent.TimeoutException; |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
public class SynchronousResultReceiver extends ResultReceiver { |
| 35 |
public static class Result { |
| 36 |
public int resultCode; |
| 37 |
@Nullable public Bundle bundle; |
| 38 |
|
| 39 |
public Result(int resultCode, @Nullable Bundle bundle) { |
| 40 |
this.resultCode = resultCode; |
| 41 |
this.bundle = bundle; |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
private final CompletableFuture<Result> mFuture = new CompletableFuture<>(); |
| 46 |
private final String mName; |
| 47 |
|
| 48 |
public SynchronousResultReceiver() { |
| 49 |
super((Handler) null); |
| 50 |
mName = null; |
| 51 |
} |
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
public SynchronousResultReceiver(String name) { |
| 57 |
super((Handler) null); |
| 58 |
mName = name; |
| 59 |
} |
| 60 |
|
| 61 |
@Override |
| 62 |
final protected void onReceiveResult(int resultCode, Bundle resultData) { |
| 63 |
super.onReceiveResult(resultCode, resultData); |
| 64 |
mFuture.complete(new Result(resultCode, resultData)); |
| 65 |
} |
| 66 |
|
| 67 |
public String getName() { |
| 68 |
return mName; |
| 69 |
} |
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
public @NonNull Result awaitResult(long timeoutMillis) throws TimeoutException { |
| 78 |
final long deadline = System.currentTimeMillis() + timeoutMillis; |
| 79 |
while (timeoutMillis >= 0) { |
| 80 |
try { |
| 81 |
return mFuture.get(timeoutMillis, TimeUnit.MILLISECONDS); |
| 82 |
} catch (ExecutionException e) { |
| 83 |
|
| 84 |
throw new AssertionError("Error receiving response", e); |
| 85 |
} catch (InterruptedException e) { |
| 86 |
|
| 87 |
|
| 88 |
timeoutMillis -= deadline - System.currentTimeMillis(); |
| 89 |
} |
| 90 |
} |
| 91 |
throw new TimeoutException(); |
| 92 |
} |
| 93 |
|
| 94 |
} |