机器人的AsyncTask发送回调UI回调、机器人、AsyncTask、UI

2023-09-12 21:29:13 作者:娃叔叔

我有不是活动里面以下AsyncTask的类。在活动中,我初始化AsyncTask的,我想在AsyncTask的报告回调回我的活动。 可能吗?抑或是AsyncTask的必须是在同一个类文件作为活动?

I have the following asynctask class which is not inside the activity. In the activity I'm initializing the asynctask, and I want the asynctask to report callbacks back to my activity. Is it possible? Or does the asynctask must be in the same class file as the activity?

protected void onProgressUpdate(Integer... values) 
{
    super.onProgressUpdate(values);
    caller.sometextfield.setText("bla");
}

这样的事情?

Something like this?

推荐答案

您可以创建一个接口,把它传递给的AsyncTask (在构造函数),然后调用方法 onPostExecute()

You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()

例如:

您接口:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

您活动:

public class YourActivity implements OnTaskCompleted{
    // your Activity
}

和你的AsyncTask:

And your AsyncTask:

public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    // required methods

    protected void onPostExecute(Object o){
        // your stuff
        listener.onTaskCompleted();
    }
}