AsyncTask通知父Activity任务完成的最佳方式是什么?

6
public class ListingFoundBeaconService 
                    extends AsyncTask<String, String, String> {

    public ListingFoundBeaconService(Context contextGiven, 
                                     JSONObject jsonParams) {
        this.contextGiven = contextGiven;
        this.jsonParams = jsonParams;
    }

    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(contextGiven);
        pDialog.setMessage("Loading list of active Beacons..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
        Log.d("onPreExecute","onPreExecute worked" );
    }

    protected String doInBackground(String... args) {}

    protected void onPostExecute(String file_url) {   
        // Two activities will need this thread so I have 
        // kept this as a separate class. Here I want to send a
        // boolean value to the parent activity to show that 
        // the task has completed or not.
    }

我能在onPostExecute()函数中触发通知或完成事件监听吗?这样启动该类(ListingFoundBeaconService)的父类将被通知。做此操作的标准方法是什么?

2个回答

20

最好的方法是调用委托。在您的 AsyncTask 类中创建一个构造函数并设置一个委托。

委托接口:

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

现在在AsyncTask中:

private TaskDelegate delegate;

public ListingFoundBeaconService(Context contextGiven, 
                                 JSONObject jsonParams,
                                 TaskDelegate delegate) {
    this.contextGiven = contextGiven;
    this.jsonParams = jsonParams;
    this.delegate = delegate;
}

postExecute 中:

delegate.taskCompletionResult(result/msg/json);

在你的主类中实现TaskDelegate并实现一个方法,当任务完成时调用该方法。

1
我发现了这篇文章:http://256design.com/blog/asynctask-in-android-and-oncompletelistener/ 你对使用它有什么评论吗? - Muhammad Irfan
1
我看到你的链接是针对Android特定的,而我们正在专注于Java本地代码,特别是链接代码会给匿名内部类带来负担。除此之外,链接概念将起作用,但您也可以在委托中设置两个函数:失败和成功。祝愉快! - Mohd Mufiz
taskDelegateResult ?? 应该是 taskCompletionResult - Muhammad Irfan
在我的主类中,我是这样传递引用的:TaskDelegateReference = this;ListingFoundBeaconService Lfb_object = new ListingFoundBeaconService(findBeaconContext,jsonData,TaskDelegateReference); - Muhammad Irfan
1
这不可能是最好的方法。如果 Activity 被重新创建会发生什么?当前(重新创建的)Activity 永远不会收到回调。 - Brais Gabin
显示剩余2条评论

0
将ListingFoundBeaconService类设为抽象类,然后在调用该类的类中重写onPostExecute方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接