我已经编写了使用Firebase Auth创建新帐户的代码:
public static int signUp(String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.i("accountMessage", "User has registered successfully!");
} else {
try {
throw task.getException();
} catch (FirebaseAuthUserCollisionException e) {
Log.i("accountMessage", "User is registered already!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
Log.i("accountMessage", "I want that this message works lastest!");
}
我可以使用LogCat捕获accountMessage
个消息。通常,我必须先看到"User is registered already!"
消息,但是我看不到它:
我在Google APIs for Android上看到OnCompleteListener
在主应用程序线程上被调用,但是我不明白如果OnCompleteListener
在主应用程序线程上被调用(我知道主应用程序线程是在同一UI线程上Android),它如何以异步方式工作?如果它在主应用程序线程上运行,是否应该同步工作?我的意思是我们不应该先看到"User is registered already!"
,然后看到"I want that this message works lastest!"
消息吗?如果OnCompleteListener可以异步工作,是否有办法同步处理UI线程?
编辑2:
实际上,onComplete
的异步操作导致以下代码中的res[0]
从signUp
方法返回,然后在onComplete
中被赋值。 :
public static int signUp(String email, String password) {
final int[] res = new int[1];
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
res[0] = 123;
// We can't use 'return 123;' in here...
}
}
});
// You can see that value of res[0] is "0", because not given "123" value.
// Must be: First, given "123" value to res[0], after then return res[0];
return res[0];
}
答案 0 :(得分:1)
该工作发生在主线程之外,因此不会阻止您的应用程序。然后,将onComplete
回调计划到主线程上,以便您无需亲自进行上下文切换即可更新UI。