取消 Firebase 存储上传任务

Canceling an Firebase Storage UploadTask

我的用例很简单。在后台上传多张图片并在通知中显示进度。现在我想在用户按下通知中的取消按钮时取消此任务。由于上传任务无法序列化,那么我应该如何取消特定的上传任务?

Upload multiple images in the background and show the progress in a notification.

对于这些操作,我假设您使用的是类似于以下的一行代码:

UploadTask uploadTask = storageReference.putFile(filePath);

Now I want to cancel this task when the user presses the cancel button in the notification.

如上一行代码所示,putFile(Uri uri) method that is called on a StorageReference object, returns an object of type UploadTask. This class is a subclass of StorageTask, which in terms is a subclass of ControllableTask, which is also a subclass of CancellableTask.

因为这些类之间的继承关系,可以直接调用CancellableTask的cancel()方法:

Attempts to cancel the task.

为了取消任务。在代码中应该是这样的:

uploadTask.cancel();