Page Summary
-
The
TaskAPI is the standard for handling asynchronous operations in Google Play services, offering a flexible replacement forPendingResult. -
You can handle
Taskresults by attaching listeners for success (OnSuccessListener), failure (OnFailureListener), or both (OnCompleteListener). -
Listeners for
Taskrun on the main thread by default, but you can specify anExecutorto schedule them on background threads. -
Activity-scoped listeners for
Taskautomatically manage their lifecycle and are removed when theActivitystops. -
You can chain
Taskobjects using continuations to manage complex asynchronous flows and avoid nested callbacks. -
You can block a background thread and wait for a
Taskto complete synchronously usingTasks.await(). -
Taskis designed for interoperability and can be converted to and from other asynchronous patterns like Kotlin coroutines andListenableFuture.
The Task API is the standard way to handle asynchronous operations in Google
Play services. It provides a powerful and flexible way to manage asynchronous
calls, replacing the older PendingResult pattern. With Task, you can chain
multiple calls, handle complex flows, and write clear success and failure
handlers.
Handle task results
Many APIs in Google Play services and Firebase return a Task object to
represent asynchronous operations. For example,
FirebaseAuth.signInAnonymously()
returns a Task<AuthResult> which represents the result of the sign-in
operation. The Task<AuthResult> indicates that when the task completes
successfully, it will return an AuthResult object.
You can handle the result of a Task by attaching listeners that respond to
successful completion, failure, or both:
Task<AuthResult> task = FirebaseAuth.getInstance().signInAnonymously();
To handle a successful task completion, attach an OnSuccessListener:
task.addOnSuccessListener(new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult authResult) { // Task completed successfully // ... } });
To handle a failed task, attach an OnFailureListener:
task.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull