Task
API 是處理 Google Play 服務中非同步作業的標準方式。這項功能提供強大且靈活的方式來管理非同步呼叫,取代舊版 PendingResult
模式。使用 Task
時,您可以連結多個呼叫、處理複雜的流程,以及編寫明確的成功和失敗處理常式。
處理工作結果
Google Play 服務和 Firebase 中的許多 API 會傳回 Task
物件,用於代表非同步作業。舉例來說,FirebaseAuth.signInAnonymously()
會傳回 Task<AuthResult>
,代表登入作業的結果。Task<AuthResult>
表示工作成功完成時,會傳回 AuthResult
物件。
您可以透過附加可回應成功完成或失敗事件的事件監聽器,處理 Task
的結果:
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(); } } });
管理執行緒
根據預設,附加至 Task
的監聽器會在應用程式主 (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
的 onStop
方法時,系統會自動移除這些事件監聽器,因此在 Activity
停止後,系統就不會執行這些事件監聽器。
Activity activity = MainActivity.this; task.addOnCompleteListener(activity, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { // ... } });
連結工作
如果您使用一組 API,在複雜函式中傳回 Task
物件,則可以使用接續來將這些物件連結在一起。這有助於避免深層巢狀回呼,並整合多個鏈結工作錯誤處理作業。
舉例來說,假設您有一個方法 doSomething
,會傳回 Task<String>
,但需要 AuthResult
做為參數。您可以從另一個 Task
以非同步方式取得這個 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 非同步程式設計模式搭配使用。它可以轉換為其他原始類型,例如 ListenableFuture
和 Kotlin 協同程式,這些都是 AndroidX 推薦的類型,可讓您使用最符合需求的方法。
以下是使用 Task
的範例:
// ... simpleTask.addOnCompleteListener(this) { completedTask -> textView.text = completedTask.result }
Kotlin 協同程式
如要搭配 Task
使用 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'
文字片段
import kotlinx.coroutines.tasks.await // ... textView.text = simpleTask.await() }
Guava ListenableFuture
如要在 Task
中使用 Guava ListenableFuture
,請在專案中新增下列依附元件,然後使用程式碼片段從 Task
轉換。
Gradle (模組層級 build.gradle
,通常是 app/build.gradle
)
implementation "androidx.concurrent:concurrent-futures:1.2.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 Observable
除了所選的相對異步程式庫外,請將下列依附元件新增至專案,然後使用程式碼片段從 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 }