| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package android.service.translation; |
| 18 |
|
| 19 |
import android.annotation.NonNull; |
| 20 |
import android.os.DeadObjectException; |
| 21 |
import android.os.RemoteException; |
| 22 |
import android.util.Log; |
| 23 |
import android.view.translation.TranslationResponse; |
| 24 |
|
| 25 |
import java.util.Objects; |
| 26 |
import java.util.concurrent.atomic.AtomicBoolean; |
| 27 |
import java.util.function.Consumer; |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
final class OnTranslationResultCallbackWrapper implements |
| 35 |
Consumer<TranslationResponse> { |
| 36 |
|
| 37 |
private static final String TAG = "OnTranslationResultCallback"; |
| 38 |
|
| 39 |
private final @NonNull ITranslationCallback mCallback; |
| 40 |
|
| 41 |
private final AtomicBoolean mCalled; |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
public OnTranslationResultCallbackWrapper(@NonNull ITranslationCallback callback) { |
| 47 |
mCallback = Objects.requireNonNull(callback); |
| 48 |
mCalled = new AtomicBoolean(); |
| 49 |
} |
| 50 |
|
| 51 |
@Override |
| 52 |
public void accept(TranslationResponse response) { |
| 53 |
assertNotCalled(); |
| 54 |
if (mCalled.getAndSet(response.isFinalResponse())) { |
| 55 |
throw new IllegalStateException("Already called with complete response"); |
| 56 |
} |
| 57 |
|
| 58 |
try { |
| 59 |
mCallback.onTranslationResponse(response); |
| 60 |
} catch (RemoteException e) { |
| 61 |
if (e instanceof DeadObjectException) { |
| 62 |
Log.w(TAG, "Process is dead, ignore."); |
| 63 |
return; |
| 64 |
} |
| 65 |
throw e.rethrowAsRuntimeException(); |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
private void assertNotCalled() { |
| 70 |
if (mCalled.get()) { |
| 71 |
throw new IllegalStateException("Already called"); |
| 72 |
} |
| 73 |
} |
| 74 |
} |