Tasks API

从 Google Play 服务 9.0.0 版开始,您可以使用 Task API 和 返回 Task 或其子类的方法数量。Task是一个 表示异步方法调用,类似于前面的 PendingResult 多个版本的 Google Play 服务

处理任务结果

返回 Task 的常见方法是 FirebaseAuth.signInAnonymously()。 它返回一个 Task<AuthResult>,这意味着任务将返回 在成功时返回 AuthResult 对象:

Task<AuthResult> task = FirebaseAuth.getInstance().signInAnonymously();

如需在任务成功时收到通知,请附加 OnSuccessListener

task.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
    @Override
    public void onSuccess(AuthResult authResult) {
        // Task completed successfully
        // ...
    }
});

如需在任务失败时收到通知,请附加 OnFailureListener

task.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        // Task failed with an exception
        // ...
    }
});

要在同一监听器中处理成功和失败,请将一个 OnCompleteListener:

task.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        if (task.isSuccessful()) {
            // Task completed successfully
            AuthResult result = task.getResult();
        } else {
            // Task failed with an exception
            Exception exception = task.getException();
        }
    }
});

线程处理

附加到线程的监听器在应用主 (UI) 线程上运行 默认情况。附加监听器时,您还可以指定一个 Executor,即 来调度监听器

// Create a new ThreadPoolExecutor with 2 threads for each processor on the
// device and a 60 second keep-alive time.
int numCores = Runtime.getRuntime().availableProcessors();
ThreadPoolExecutor executor = new ThreadPoolExecutor(numCores * 2, numCores *2,
        60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

task.addOnCompleteListener(executor, new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        // ...
    }
});

activity 作用域监听器

如果您正在监听 Activity 中的任务结果,则可能需要将 activity 作用域监听器。这些监听器会在 您的 Activity 的 onStop 方法,这样系统便不会调用监听器 当 activity 不再可见时触发。

Activity activity = MainActivity.this;
task.addOnCompleteListener(activity, new OnCompleteListener<AuthResult>() {
    @Override
    public void onComplete(@NonNull Task<AuthResult> task) {
        // ...
    }
});

如果您使用多个返回 Task 的 API,可以将它们链接在一起 使用接续。这有助于避免深度嵌套的回调并实现整合 任务链的错误处理。

例如,方法 doSomething 会返回 Task<String>,但需要 AuthResult,我们将从任务异步获取:

public Task<String> doSomething(AuthResult authResult) {
    // ...
}

使用 Task.continueWithTask 方法,我们可以将这两个任务串联起来:

Task<AuthResult> signInTask = FirebaseAuth.getInstance().signInAnonymously();

signInTask.continueWithTask(new Continuation<AuthResult, Task<String>>() {
    @Override
    public Task<String> then(@NonNull Task<AuthResult> task) throws Exception {
        // Take the result from the first task and start the second one
        AuthResult result = task.getResult();
        return doSomething(result);
    }
}).addOnSuccessListener(new OnSuccessListener<String>() {
    @Override
    public void onSuccess(String s) {
        // Chain of tasks completed successfully, got result from last task.
        // ...
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        // One of the tasks in the chain failed with an exception.
        // ...
    }
});

阻止

如果您的程序已在后台线程中执行,您可以阻止 同步获取结果并避免回调的任务:

try {
    // Block on a task and get the result synchronously. This is generally done
    // when executing a task inside a separately managed background thread. Doing this
    // on the main (UI) thread can cause your application to become unresponsive.
    AuthResult authResult = Tasks.await(task);
} catch (ExecutionException e) {
    // The Task failed, this is the same exception you'd get in a non-blocking
    // failure handler.
    // ...
} catch (InterruptedException e) {
    // An interrupt occurred while waiting for the task to complete.
    // ...
}

您还可以在阻止任务时指定超时,这样您的应用 不挂起:

try {
    // Block on the task for a maximum of 500 milliseconds, otherwise time out.
    AuthResult authResult = Tasks.await(task, 500, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
    // ...
} catch (InterruptedException e) {
    // ...
} catch (TimeoutException e) {
    // Task timed out before it could complete.
    // ...
}

互操作性

Task 在概念上与几种常用的 Android 管理方法保持一致 异步代码,也可以直接将 Task 转换为其他 包括 ListenableFuture 和 Kotlin 协程在内的基元, AndroidX 推荐

下面是一个使用 Task 的示例:

// ...
simpleTask.addOnCompleteListener(this) {
  completedTask -> textView.text = completedTask.result
}

Kotlin 协程

用法

将以下依赖项添加到您的项目中,并使用以下代码转换 (来自 Task)。

Gradle(模块级 build.gradle,通常为 app/build.gradle
// Source: https://github.com/Kotlin/kotlinx.coroutines/tree/master/integration/kotlinx-coroutines-play-services
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.7.3'
Snippet
import kotlinx.coroutines.tasks.await
// ...
  textView.text = simpleTask.await()
}

Guava ListenableFuture

将以下依赖项添加到您的项目中,并使用以下代码转换 (来自 Task)。

Gradle(模块级 build.gradle,通常为 app/build.gradle
implementation "androidx.concurrent:concurrent-futures:1.2.0"
Snippet
import com.google.common.util.concurrent.ListenableFuture
// ...
/** Convert Task to ListenableFuture. */
fun <T> taskToListenableFuture(task: Task<T>): ListenableFuture<T> {
  return CallbackToFutureAdapter.getFuture { completer ->
    task.addOnCompleteListener { completedTask ->
      if (completedTask.isCanceled) {
        completer.setCancelled()
      } else if (completedTask.isSuccessful) {
        completer.set(completedTask.result)
      } else {
        val e = completedTask.exception
        if (e != null) {
          completer.setException(e)
        } else {
          throw IllegalStateException()
        }
      }
    }
  }
}
// ...
this.listenableFuture = taskToListenableFuture(simpleTask)
this.listenableFuture?.addListener(
  Runnable {
    textView.text = listenableFuture?.get()
  },
  ContextCompat.getMainExecutor(this)
)

RxJava2 可观察

除了 选项添加到您的项目中,然后使用以下代码从 Task 进行转换。

Gradle(模块级 build.gradle,通常为 app/build.gradle
// Source: https://github.com/ashdavies/rx-tasks
implementation 'io.ashdavies.rx.rxtasks:rx-tasks:2.2.0'
Snippet
import io.ashdavies.rx.rxtasks.toSingle
import java.util.concurrent.TimeUnit
// ...
simpleTask.toSingle(this).subscribe { result -> textView.text = result }

后续步骤