0

Consider the scenario where I have get data from server and post it to UI in say list view , but this is an going activity ,it never stops.

taskA{ //fetches data over network

if(!update)
    fetch();//network operation

}

taskB{//using this data UI is updated at runtime just like feed.

if(update)
    show();//UI operation
}

taskA starts first after it completes taskB starts by that time A is sleeping and vice versa , goes , now the problems i am facing are:

  1. both operations have to be in worker thread
  2. both operations are going in cycle till activity is alive.
  3. if handler is used to post UI operation to the main thread , taskB seems to stop.

Can anybody please suggest me a design to get this working?

oers
  • 18,436
  • 13
  • 66
  • 75
user1254554
  • 203
  • 1
  • 4
  • 14

3 Answers3

2

AsyncTask is doing the job for you. You can make it as an inner class under your Activity main class.

http://developer.android.com/reference/android/os/AsyncTask.html

Example code

private class YourTask extends AsyncTask<URL, Integer, String> {
     protected String doInBackground(URL... urls) {
         // Fetch Data (Task A)
         return "Result";
     }

     protected void onProgressUpdate(Integer... progress) {
         // Show progress
     }

     protected void onPostExecute(String result) {
         // Show UI after complete (Task B)
     }
}
Victor Wong
  • 2,486
  • 23
  • 32
  • This is a good answer but it's only correct if the activity does not rotate when user rotates device. – Juozas Kontvainis Jul 10 '12 at 09:33
  • 1
    The handling is not that complicated. See http://stackoverflow.com/questions/2620917/how-to-handle-an-asynctask-during-screen-rotation for more concrete solutions. – Victor Wong Jul 10 '12 at 09:56
  • please correct me if i am wrong , but if i use asynctask for recurring operation like taskA , then it will create a new thread everytime to do the same operation. – user1254554 Jul 10 '12 at 10:23
  • I am not sure what your operation looks like, but if you are worried about this issue, you may want to use singleton instance for fetching data. Logically, you won't fetch from the same data source multiple times at the same time. – Victor Wong Jul 11 '12 at 02:29
  • The operation is similar to producer consumer problem , except that it is an ongoing operation. – user1254554 Jul 11 '12 at 05:02
0

AsyncTask is what you're looking for. Check out this link for some sample code: http://geekjamboree.wordpress.com/2011/11/22/asynctask-call-web-services-in-android/

Code Poet
  • 11,227
  • 19
  • 64
  • 97
0

You can also use IntentService you can check some sample code

An Android service is lightweight but more complex to setup.

AsyncTask is very easy but not recommended as it has many downsides and flaws. You could also look into Loaders but it's not as easy as AsyncTasks.

Benoit
  • 4,549
  • 3
  • 28
  • 45