0

At first, this is for a step counter.

My initial structure is a service keeps logging step counter value to database.
Then a async task keeps updating the value shown to user when the app is visible to user.
I planed to create a thread to periodically call the async task.
However, after digging into the official document, "async task should be created and invoked within UI thread".
The conflict now is UI thread should not be blocked vs calling async task periodically.
Or there is else a better way to implement?

Thanks for any input.

user3042713
  • 175
  • 2
  • 12

1 Answers1

1

You need to derive from AsyncTask inside your UI class (service or activity).

Inside your AsyncTask (as described here) there is doInBackground which runs asynchronously and there is onPostExecute which runs inside UI thread after your asynchronous task is over.

Just put your DB operation inside doInBackground and put something like this inside onPostExecute

MyServiceClass.this.RunNextTask();

The RunNextTask method in your UI class could use the same AsyncTask to launch the next task.

Vahid
  • 1,829
  • 1
  • 20
  • 35
  • The MyServiceClass for – user3042713 Jan 22 '16 at 12:43
  • I oversaw onPostExecute and didn't know it runs in UI thread. Thanks. The MyServiceClass is for looping in a specific time? So I can open a worker thread to simulate what you said? Something like: Thread updater = Thread( new runnable( void run() {while(true) {wait(1s); callasyncTask();})) – user3042713 Jan 22 '16 at 12:48
  • By MyServiceClass I meant the class in which you declare your async task. You need to declare your AsyncTask class as inner class in this configuration. that class can be a service class or an activity. – Vahid Jan 22 '16 at 12:57
  • Ic. Then how to periodically call the async task because if using wait, then it would be a blocking behavior. Sorry i am really new to android development – user3042713 Jan 22 '16 at 14:42
  • If by periodically you mean the next task should start upon completion of the previous task then you're good to launch the next task inside `onPostExecute` as suggested above. If what you need is to run a task every x minutes then you might be looking for [this](http://stackoverflow.com/questions/14376470/scheduling-recurring-task-in-android) – Vahid Jan 22 '16 at 16:12
  • most likely Alarm Manager is my solution – user3042713 Jan 22 '16 at 17:42