如何从另一个活动刷新 asyncTask?
我正在启动一个活动,一旦用户登录,我想刷新主要活动。从登录用户加载数据。
例如图像和名称。我已经把这一切都设置好了。
我只需要知道是否可以启动另一个活动并再次运行其异步任务。从另一个活动内部启动意图?
I am launching a activity, and once a user is logged in, i want to refresh the main activity. To load the data from the logged in user.
Such as the image and name. I have all of this set up already.
I just need to know is it possible to launch another activity and run its async task again.From an launching an intent from inside another activity?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知,AsyncTasks 不应该被重用。它们应该运行一次,然后您可以根据需要创建一个新的。
As far as I'm aware, AsyncTasks aren't supposed to be reused. They're supposed to be run once and then you can create a new one if you need it.
AsyncTask
一旦执行一次,就无法再次执行。不过,您可以做的是使用onProgressUpdate()
和publishProgress()
控制它的“刷新”,如下所示。请注意,这仅适用于一次性刷新。如果您想在语义上更加正确,您可以在onProgressUpdate()
中执行“正常”操作,并使用onPostExecute()
进行刷新。然后,您可以维护对
MyAsyncTask
对象的引用,并在需要刷新时调用refreshTask()
。Once an
AsyncTask
is executed once, you cannot execute it again. What you can do, though, is control it's "refresh" usingonProgressUpdate()
andpublishProgress()
as follows. Note that this will only work for a one-time refresh. If you wanted to be more semantically correct, you might do the "normal" operation inonProgressUpdate()
and useonPostExecute()
for your resfresh.You could then maintain a reference to the object of
MyAsyncTask
and invokerefreshTask()
on it whenever you want to refresh it.目前尚不清楚您的设计到底是什么,但如果您需要从两个不同的活动使用相同的 AsyncTask,它应该是一个单独的类,而不是绑定到特定的活动。您可以让这两个活动实现一个通用接口,以便 AsyncTask 不需要知道它正在更新哪个活动。然后通过传递对封闭活动的引用来实例化任务,并根据需要启动它。不需要一项活动来启动另一项活动。
像这样的东西:
It's not clear what exactly your design is, but if you need to use the same AsyncTask from two different activities, it should be a separate class, not tied to a particular activity. You can have the two activities implement a common interface, so that the AsyncTask doesn't need to know which activity it is updating. Then instantiate the task by passing a reference to the enclosing activity, and start it as needed. There is no need for one activity to start the other.
Something like: