A Service, like an Activity, has a main thread with a message-loop. You can create an AsyncTask in the onXXXXX() callbacks of Services, just like in an Activity. The onPostExecute can do your handling of the results, as you described.
However, AsyncTask is more geared towards the one-time executing of a background process. E.g. retrieve some data from the internet now, or create/process a bitmap. It is not really meant to stay in the background forever in a loop polling for some data to come in. When you have something like 'while (true)' or 'while (!mStopped)' or something like it, you should not use a AsyncTask. Use a regular Thread instead that calls 'post' on the owning Activity that will consume the results generated by the thread. On Jan 21, 6:22 pm, Flapjack <millerhugg...@gmail.com> wrote: > According to my research, which includes reputable sources (Mark > Murphy et al), the most preferred way of polling a remote source and > presenting said data to the user is by creating a service and using > AsyncTask within that service to do the polling. I have done that. > > But, when I read the docs (http://developer.android.com/reference/ > android/os/AsyncTask.html), there seem to be several "Threading Rules" > that conflict with this way of doing things: "The task instance must > be created on the UI thread." and "execute(Params...) must be invoked > on the UI thread." As stated, I have created the task instance on the > Service thread (not the UI thread). Am I missing something? > > Also, when the AsyncTask finished, I sent out a Broadcast on > onPostExecute, which is then picked up by the Activity, telling it to > retrieve the final value again from the service (since I couldn't > obviously update the UI from the service). I couldn't figure out any > other way to return the result of the AsyncTask. Is this the correct > practice? > > Java is not my native language so please bear with my ignorance. > Thanks! -- You received this message because you are subscribed to the Google Groups "Android Developers" group. To post to this group, send email to android-developers@googlegroups.com To unsubscribe from this group, send email to android-developers+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/android-developers?hl=en