Search code examples
androidandroid-asynctaskbroadcastreceiver

Activity -> AsyncTask -> BroadcastReceiver -> Update UI


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.


Solution

  • 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