Tasks API

從 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,則可使用接續功能將其鏈結在一起。這有助於避免使用深層巢狀結構的回呼,並合併工作鏈結的錯誤處理方式。

舉例來說,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 推薦ListenableFuture 和 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 ListenableFuture

將以下依附元件新增至專案,並使用下列程式碼從 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 }

後續步驟