AsyncTask通知父Activity有关完成的最佳方法是什么?

时间:2012-11-16 12:32:00

标签: android android-asynctask android-activity

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 个答案:

答案 0 :(得分:18)

最好的办法是给代表打电话。在你的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;
}

on postExecute

delegate.taskCompletionResult(result/msg/json);

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

答案 1 :(得分:0)

将ListingFoundBeaconService类设为abstract,然后覆盖调用类中的onPostExecute。