当前,我使用Task API进行以下异步调用。

异步

Task<GoogleSignInAccount> task = googleSignInClient.silentSignIn();
if (!task.isSuccessful()) {
    task.addOnCompleteListener(task1 -> {
        // Now, this is main thread.
        try {
            GoogleSignInAccount googleSignInAccount = task1.getResult(ApiException.class);
        } catch (ApiException e) {
            if (e.getStatusCode() == GoogleSignInStatusCodes.SIGN_IN_REQUIRED) {
            }
        }
    });
}


我想将其重构为同步调用。

同步

Task<GoogleSignInAccount> task = googleSignInClient.silentSignIn();

try {
    // How to capture ApiException in Tasks.await
    GoogleSignInAccount googleSignInAccount = Tasks.await(task);
} catch (ExecutionException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}


但是,我想知道如何像使用ApiException一样捕获所需的task.getResult(ApiException.class)

最佳答案

只是解决了这个问题:查看Tasks.await()的来源,它将ApiException(或任务抛出的任何Exception)包装在ExecutionException中:

private static <TResult> TResult zzb(Task<TResult> task) throws ExecutionException {
    if (task.isSuccessful()) {
        return task.getResult();
    } else if (task.isCanceled()) {
        throw new CancellationException("Task is already canceled");
    } else {
        throw new ExecutionException(task.getException());
    }
}


因此,找出原因并检查它是否为ApiException

} catch (ExecutionException e) {
    Throwable cause = e.getCause();
    if (cause instanceof ApiException) {
            String statusCodeString = GoogleSignInStatusCodes
                    .getStatusCodeString(((ApiException) cause).getStatusCode());
    }
}


play-services-tasks版本16.0.1测试。

https://developers.google.com/android/reference/com/google/android/gms/tasks/Tasks

关于android - 任务API-如何将异步调用重构为同步调用却又能够捕获所需的异常(ApiException),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50484855/

10-10 02:43