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?
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .
Android AsyncTask is an abstract class provided by Android which gives us the liberty to perform heavy tasks in the background and keep the UI thread light thus making the application more responsive. Android application runs on a single thread when launched.
If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes. And when it completes, the AsyncTask won't update the UI of the new Activity.
Limitation Of AsyncTask There is a limit of how many tasks can be run simultaneously. Since AsyncTask uses a thread pool executor with max number of worker threads (128) and the delayed tasks queue has fixed size 10. If you try to execute more than 138 AsyncTasks the app will crash with java.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With