简体   繁体   English

对AsyncTask使用委托

[英]Using delegates for AsyncTask

I'm having trouble implementing a delegate in my android app. 我在Android应用中实现委托时遇到问题。

In my GetData class I have nested asynctask, and I need to notify my main activity when all the work has actually finished. 在我的GetData类中,我嵌套了asynctask,当所有工作实际完成时,我需要通知我的主要活动。

I came up with this answer from Mohd Mufiz What is the best way for AsyncTask to notify parent Activity about completion? 我从Mohd Mufiz那里得到了这个答案,AsyncTask通知父Activity有关完成的最好方法是什么?

But I always get stuck at the same point: in my GetData class I call a constructor with the delegate as only argument: 但是我总是会遇到同样的问题:在我的GetData类中,我调用了一个仅将委托作为参数的构造函数:

public class GetData {

    private TaskDelegate delegate;

    public GetData(TaskDelegate delegate) {
        this.delegate = delegate;
    }
...
}

In my main activity I don't know what I have to pass to get it working: 在我的主要活动中,我不知道必须通过什么才能使其正常工作:

 GetData getData = new GetData(**???**);

Going from the question you linked to, that defined TaskDelegate as : 从您链接到的问题开始,将TaskDelegate定义为:

public interface TaskDelegate {
    public void taskCompletionResult(String result);
}

You can pass GetData any instance of a class that implements TaskDelegate - but typically, that would be the object that creates it - ie. 您可以将实现TaskDelegate的类的任何实例传递给GetData-但通常,它是创建它的对象-即。 your main activity (and so, therefore, it would also implement "void taskCompletionResult(String result);"). 您的主要活动(因此,它还将实现“ void taskCompletionResult(String result);”)。 That then means you can pass "this" to GetData's constructor, so : 这意味着您可以将“ this”传递给GetData的构造函数,因此:

public class MyMainActivity implements TaskDelegate {

    public void someMethod() {
        GetData getData = new GetData(this);
    }

    public void taskCompletionResult(String result) {
        // do stuff
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM