Google Play services Task API: can a Task be cance

2019-07-22 03:08发布

When use Tasks.call(Callable), can I cancel it, and remove all the listeners from the task?

2条回答
再贱就再见
2楼-- · 2019-07-22 03:55

If you need a way to remove all the listeners from any Task at any time, you will have to remember all the listeners you previously added, then remove them all manually.

If you're working with an Android app, and you add Activity-scoped listeners, they will be removed automatically when the host activity is stopped (goes through its onStop() lifecycle method). Note that you have to pass the activity as an argument to addOnCompleteListener().

查看更多
▲ chillily
3楼-- · 2019-07-22 04:06

A Task class doesn't have a function you can call to cancel. You should use it's subclass CancellableTask instead, to be able to use cancel():

public abstract boolean cancel ()

Attempts to cancel the task. A canceled task cannot be resumed later. A canceled task calls back on listeners subscribed to addOnFailureListener(OnFailureListener) with an exception that indicates the task was canceled.

Returns

  • true if this task was successfully canceled or is in the process of being canceled. Returns false if the task is already completed or in a state that cannot be canceled.

If you still insist on using Task instead, I think it'd be best to refer to similar posts that are using AsyncTasks like this one.

查看更多
登录 后发表回答