Android Firebase:如果OnCompleteListener在主应用程序线程上调用,它将如何异步工作?

时间:2019-04-25 17:33:47

标签: java android multithreading firebase firebase-authentication

我已经编写了使用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!"消息,但是我看不到它: Android LogCat accountMessage 我在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];
}

1 个答案:

答案 0 :(得分:1)

该工作发生在主线程之外,因此不会阻止您的应用程序。然后,将onComplete回调计划到主线程上,以便您无需亲自进行上下文切换即可更新UI。