pteixeira
pteixeira

Reputation: 1687

Android - repeating WebService call

I need to consume a JSON webservice very often (every 5,10 sec tops).

I have the webservice call implemented in an AsyncTask that is performed whenever I press a button, for testing purposes.

Should I use Handlers, Timers or even the AlarmManager?

I am a bit confused since AsyncTask creates its own thread, but won't any of these methods create another thread, thus creating a thread which will create another thread?

I implemented it using the AsyncTask because I cannot afford for the application to hang whenever there's a problem in a webservice call, so if the first call failed, if the second succeeds there shouldn't be any problem and the data I'm fetching will show up the second time the task is performed.

(GCM could be a solution, but right now I need to use polling instead of notifications..)

thanks in advance

Upvotes: 1

Views: 1167

Answers (3)

Dharmesh
Dharmesh

Reputation: 221

I found great tutorial from here

https://www.thepolyglotdeveloper.com/2014/10/use-broadcast-receiver-background-services-android/

Service will run in background periodically every 30 minutes. Change it based on requirements.

May it helps you.

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93579

Handlers don't create a new thread, they occur on the UI thread. As such, you can't do an HTTP request on it.

I actually wouldn't suggest AsyncTasks for your use case. You'll have requests finishing out of order. Also, depending on the OS version you're running on, they may or may not be running in parallel.

My suggestion for you would be to use a Thread. They exist in Android, and they're the preferred method of offloading if you want something run continuously when your activity is in the foreground, and you only have one thing to worry about rather than N tasks. (If you want to run this even when not in the foreground, you need a Service).

Upvotes: 1

mihail
mihail

Reputation: 2173

I'd suggest you to use a Handler.postDelay(Runnable r,long delayMillis) and start your process again after desired delay.

Upvotes: 1

Related Questions