Android 任务API-如何将异步调用重构为同步调用,同时能够捕获所需的异常(ApiException)
目前,我使用任务API进行了以下异步调用 异步的Android 任务API-如何将异步调用重构为同步调用,同时能够捕获所需的异常(ApiException),android,google-play-services,google-signin,Android,Google Play Services,Google Signin,目前,我使用任务API进行了以下异步调用 异步的 Task Task=googleSignInClient.silentSignIn(); 如果(!task.issusccessful()){ task.addOnCompleteListener(task1->{ //现在,这是主线。 试一试{ GoogleSignInAccount GoogleSignInAccount=task1.getResult(ApiException.class); }捕获(APIE){ 如果(例如getStatu
Task Task=googleSignInClient.silentSignIn();
如果(!task.issusccessful()){
task.addOnCompleteListener(task1->{
//现在,这是主线。
试一试{
GoogleSignInAccount GoogleSignInAccount=task1.getResult(ApiException.class);
}捕获(APIE){
如果(例如getStatusCode()==谷歌登录状态码。需要登录){
}
}
});
}
我想将其重构为同步调用
同步的
Task Task=googleSignInClient.silentSignIn();
试一试{
//如何在Tasks.await中捕获ApiException
GoogleSignInAccount GoogleSignInAccount=Tasks.wait(任务);
}捕获(执行例外){
e、 printStackTrace();
}捕捉(中断异常e){
e、 printStackTrace();
}
然而,我想知道,我如何才能捕获所需的
ApiException
,就像我使用task.getResult(ApiException.class)
所做的那样?刚刚解决了这个问题:查看Tasks.wait()的源代码,它包装了ApiException
(或者任务抛出的任何异常
)在执行异常中
:
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());
}
}
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof ApiException) {
String statusCodeString = GoogleSignInStatusCodes
.getStatusCodeString(((ApiException) cause).getStatusCode());
}
}
使用播放服务任务测试版本16.0.1
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());
}
}
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof ApiException) {
String statusCodeString = GoogleSignInStatusCodes
.getStatusCodeString(((ApiException) cause).getStatusCode());
}
}