Tasks API

Stay organized with collections Save and categorize content based on your preferences.

從 Google Play 服務 9.0.0 版開始,您可以使用 Task API,以及傳回 Task 或其子類別的方法。Task 是一個 API,代表非同步方法呼叫,類似舊版 Google Play 服務中的 PendingResult

處理工作結果

傳回 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 中的工作結果,您可能需要在工作中新增以活動為範圍的事件監聽器。這些事件監聽器會在活動的 onStop 方法中移除,因此當活動不再顯示時,系統不會呼叫事件監聽器。

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

鏈結

如果您使用多個傳回 Task 的 API,則可使用連續連結將這些 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 可以直接轉換為其他原始檔案,包括 AndroidX 建議的 Kotlin 和 Kotlin 協同程式。

以下是使用 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.4.1'
文字片段
import kotlinx.coroutines.tasks.await
// ...
  textView.text = simpleTask.await()
}

Guava SoundableFuture

將以下依附元件新增至專案,並使用下列程式碼從 Task 轉換。

Gradle (模組層級 build.gradle,通常為 app/build.gradle)
implementation "androidx.concurrent:concurrent-futures:1.1.0"
文字片段
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'
文字片段
import io.ashdavies.rx.rxtasks.toSingle
import java.util.concurrent.TimeUnit
// ...
simpleTask.toSingle(this).subscribe { result -> textView.text = result }

後續步驟