In my Android application I have an Observable Data class, which contains a method download() to download and parse some data. When this is done, it notifies its Observers.
Further, I have an Activity and a Service. The Activity calls the download() method asynchronous using an AsyncTask.
The Service constantly needs to listen for updates to process the data further. This should not happen in the UI thread. I’ve created this little Service class:
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
new MyWorkerThread().start();
}
private class MyWorkerThread extends Thread implements Observer{
@Override
public void run() {
observeData();
}
private void observeData(){
Data.getInstance().addObserver(this);
}
@Override
public void update(Observable observable, Object data) {
// In what thread does the code placed here run?
}
}
}
Now, my question: When the download() method of the Data class notifies its Observers, in which thread will the update() method run? Will this be in the thread of the AsyncTask created by the Activity, which prevents the code from going through the onPostExecute() method until the service is done? If so, would I be better off making my MyService an Observer and create a new MyWorkerThread each time?
Or will the code run in it’s own thread by the MyWorkerThread?
I hope it’s understandable, thanks in advance!
You can do that but you don’t have to. For example using a single
HandlerThreadwould accomplish the same. Also you don’t have to deal with multiple threads running in parallel then.