I am starting an AsyncTask
from an Activity
. When, the AsyncTask
completes its execution I need to send a broadcast which needs to call Activity
method to update the UI.
Any good approach to achieve this.

- 2,063
- 2
- 29
- 60
-
I think, It's better to use Observer pattern to handle this scenario. – Manjunath Aug 06 '13 at 01:20
3 Answers
Yes.
If the AsyncTask
is an inner class of your Activity
then it has access to any member variables and your Activity
methods. If it isn't then you can simply pass variables to its constructor or even a reference to the Activity
to call Activity
methods from onPostExecute()
. Without any code its hard to say much else.
To pass an instance of your Activity
and use its methods if its a separate class then you can create a constructor and do something like
public class MyTask extends AsyncTask<...> // add your params
{
private MyActivity activty;
public MyTask (MyActivity act)
{
this.activty = activty;
}
// ...
}
and in onPostExecute()
add something like
activity.myMethod();
and call the task like
MyTask task = new MyTask(this); // pass a reference of the activity
task.execute(); // add params if needed
If the AsyncTask
is a separate file from the Activity
then you can see this answer on how to use an interface for a callback
Please use Interface.
interface INotifyChange {
void notifyChange(); // You can use params to transfer data :D
}
In Activity you should implements this interface.
YourActivity extends Activity implements INotifyChange {
@Override
public void notifyChange() {
// Right here, you can Update UI.
}
}
When you create new instance of AsyncTask
Example:
YourAsyncTask mTask = new YourAsyncTask(this); // You put INotifyChange
In YourAsyncTask
private INotifyChange iNotifyChange;
public YourAsyncTask(INotifyChange iNotifyChange) {
this.iNotifyChange = iNotifyChange;
}
// When you complete doInBackground or anywhere you want to Update UI please use iNotifyChange.notifyChange()
Example:
@Override
public void onPostExecute(ResultType mResult) {
iNotifyChange.notifyChange();
}
By this way I often use to update progress bar. In this case, I use parameter in my method:
Example:
iNotifyChange.notify(progress);

- 2,800
- 2
- 25
- 46
Have you considered overwriting the onPostExecute() method of the AsyncTask to update the UI? Try something like this:
AsyncTask<String, Void, Bitmap> task = new AsyncTask<String, Void, Bitmap>(imageView)
{
private ImageView imageView;
public AsyncTask(ImageView imageView)
{
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground (String... params)
{
if(params.length > 0)
{
String filePath = params[0];
// Load Bitmap from file
return bitmap;
}
}
@Override
protected void onPostExecute(Bitmap result)
{
imageView.setImageBitmap(result);
}
}
task.execute(filePath);

- 49,491
- 11
- 98
- 86