Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

android - What is the best way for AsyncTask to notify parent Activity about completion?

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.
    }

Can I trigger a notification or complete event listener in onPostExecute() function so that the parent class which started this class(ListingFoundBeaconService) is notified? What is the standard way of doing it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Best way is to call delegate. In your AsyncTask class make a constructor and have a delegate

Delegate interface:

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

now in 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);

In your main class implement TaskDelegate and implemented a method which is called when the task completed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...