Android-Droid
Android-Droid

Reputation: 14565

Android finish thread in Service and update UI

I have a little question about threads and services. I have an example which is downloading data over internet in thread which is running in service. The thing that I want to know is how can I detect when my thread is finished (all data is downloaded) and then to invoke service's onDestroy() which will update the UI in all activities which I have to do that.

Any suggestions how to do that and is that the right way which I should do it.

Thanks in advance!

Upvotes: 4

Views: 1801

Answers (3)

Rodja
Rodja

Reputation: 8081

  1. Detecting Finished Downloads: If you use a simple Thread and not AsyncTask, you need to create a callback which get's called by the thread to notify the service about the finished downloads (eg. onDownloadsFinished()).
  2. Communicating with the Activity: There are many ways to communicate between Services and Activities but I find binding to a service simplest. When bound to the service an Activity can register callbacks directly in the service.
  3. Modify UI: Make sure you use runOnUiThread when trying to change UI from within the callback because it will be executed async.
  4. Stopping the Service: As long as the Activity is bound to the Service, it will run. That is not a problem because when there is no thread within executing something it hardly consumes any resources. You only need to call stopSelf() within onDownloadsFinished() if you use startService() to begin the background downloads. Check service documentation for further informations.

Upvotes: 4

teoREtik
teoREtik

Reputation: 7916

Firstly It depends on what kind of web client do you use to download data, this client determine end of incoming data, after that you should call stopSelf() method in your Service object class than define your actions in onDestroy() method's block

Upvotes: 0

vikky
vikky

Reputation: 258

1) use can make use of messenger in order to communicate between activity and service. 2) if your data is stored in some file or database then just send a broadcast receiver which will tell activity that its time to refresh. 3) use interface. but in this case you will have to store object of that interface which even service can use.

Upvotes: 0

Related Questions