Search code examples
androidandroid-asynctaskbroadcastreceiverreturn-valuestatic-methods

Static methods or broadcast receiver?


I found a lot of useful answer on this great site that helped me a lot in learning app programming. Now it's my time to make a question as I cannot find something similar. Things are: I have an activity (suppose main activity) that uses a class to execute various background operation with async task. In the onPostExecute method I return values to the main activity using a public static method (es. MainActivity.setResult(asyTaskResult); my question is: is this the correct way to handle the result? Should I use a broadcast receiver? Are there any better methods to use? I'm new In posting questions and I don't really know if I made it in the correct way. I will appreciate any help or link pointing to a useful answer. Thanks in advance.


Solution

  • is this the correct way to handle the result?

    Probably not, as it is easy to get a memory leak that way.

    Should I use a broadcast receiver?

    Probably not in the way that you are thinking.

    Are there any better methods to use?

    Have the AsyncTask be managed by a retained fragment, and have the task talk to the fragment instance, as in this sample app.

    Or, use an event bus, such as LocalBroadcastManager, Square's Otto, or greenrobot's EventBus, as in this sample app.