在 ASyncTask.execute() 之后从 Activity 做 x() [英] After ASyncTask.execute() do x() from Activity

查看:27
本文介绍了在 ASyncTask.execute() 之后从 Activity 做 x()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个我不知道如何去做的.基本上我有一个 ASyncTask 类,它在后台照常工作.完成后我想做点什么.现在,在你跳到前面说只使用 onPostExecute()"之前,有一个问题.我需要运行的方法在 Activity 中,而不是 Task 类中.

This is one I'm not sure how to go about. Basically I have an ASyncTask class thats doing its business as usual in the background. I'd like to do something after its finished. Now before you jump ahead and say "just use onPostExecute()", theres a catch. The method I need run is in the activity and not the Task class.

在我看来,我有两个选择.

The way I see it, I have 2 options.

    CustomTask task = new CustomTask();
    task.execute(passedParams);
            //when(task.execute is finished)
            {
                doX();
            }

我希望我可以这样做,因为它非常简单,让我可以检查任务何时完成,而不必不断轮询它的活动和 getStatus() 活动.我不认为我会这么幸运,但如果有人有办法做到这一点,那就太好了

I hope I can do it this way as Its so simple and lets me check when the task is completed without having to constantly poll it for activity and getStatus() on the activity. I don't think I'll get this lucky but If anyone has a way of doing it, that'd be great

将活动作为参数传递给 ASyncTask.这很混乱,我对使用它不满意,但除此之外还有对象引用,我不知道它是否会起作用

Pass the activity as a paramater to the ASyncTask. This is messy and I'm not happy about using it but asides from that and the object reference, I don't know if it will work

    CustomTask task = new CustomTask();
    task.execute(passedParams,MyActivity);

然后在任务 onPostExecute 中,我可以让它调用 MyActivity.doX();

Then in the Tasks onPostExecute, I can just have it call the MyActivity.doX();

第三种方法是使 asynctask 成为活动本身的私有类,但我真的希望将其分开.可重用性和什么不是 -

A third way would be to make the asynctask a private class in the activity itself but i really would like to keep it separate. Resusability and what not –

对此有什么想法吗?

总结一下,task.execute 完成后需要 doX().任何想法表示赞赏.

To summarize, Need to doX() after task.execute is finished. Any ideas appreciated.

好的,我知道我在这里很忙.我一直在想新的解决方案.可以从任何地方调用的类方法或静态方法.

Ok I know I'm on a roll here. I keep thinking up new solutions. A class method or static method that can be called from any where.

public class ProfileSettings extends Activity
{
      public static void doX()
      {
          //Logic...
      }
}

来自异步任务

MyActivity.doX();

推荐答案

选项 B 应该有效,有时是一个不错的选择,但有时我为此使用匿名类.当您从您的活动中调用它时:

Option B should work and is sometimes a good option, but sometimes I use anonymous classes for this. When you call it from your activity:

CustomTask task = new CustomTask() {
    @Override
    protected void onPostExecute(Long result) {
        super.onPostExecute(result);
        MyActivity.this.doX();
    }
}.execute();

这篇关于在 ASyncTask.execute() 之后从 Activity 做 x()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆