Reputation: 2139
Intro : I have 3 activities, DashBoard
, Feed
and Events
. DashBoard is the launched when the application launches. From there the user can goto Feed or Events.
Problem : I want to initiate a download (in a separate thread, of course) when the DashBoard
launches. From there the user can goto Feed
or Events
, and the download would be in progress or already finished. The activities Feed
or Event
(which ever appropriate at the instance) should be notified that the download is finished and the data is available. What is the best way to accomplish this?
My current code : I have a downloader class DownloadHandler
which gets initiated by the DashBoard
activity. This class downloads on a separate thread. The class keeps track of a boolean called completed
. It is instantiated to false
and when the download completes it is changed to true
.
Currently My classes Feed
or Events
will poll the variable completed
every 100ms or so in a separate thread so it doesn't block the UI thread. and when the completed
variable becomes true
it calls a function in that specific class which then queries the DataHandler
class for the downloaded data.
This does work, but I feel like my logic is a bit messy and there must be a better way to do it. Because I am using two separate threads, one for downloading, one for polling the completed variable. Is there a better way to do this?
I have read on AsyncTask
and different callbacks, but the problem is I cannot specify a callback in a specific class. Because when the download completes the current activity might be DashBoard
, Events
or Feeds
. There is no guarantee which activity will be in front when the download finishes.
Upvotes: 0
Views: 302
Reputation: 1382
i would fire up a broadcast in my download thread (seting up an intentfilter for that) and registerreceiver in Feeds and Events (dont forget to unregister them in onStop() ). I use this solution often for this purpose - its easy and makes a good job.
BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
}
};
you should solve the rest on your own :) isnt that hard. There are many tuts for that or buy a standard book to get in android.
Upvotes: 1