從 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
中的工作結果,建議您在工作中加入以活動為範圍的事件監聽器。這些事件監聽器會在 Activity 的 onStop
方法期間移除,這樣一來,當 Activity 不再顯示時,系統就不會呼叫事件監聽器。
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 推薦的 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 }