Sritam Saha
Sritam Saha

Reputation: 69

How to keep http requests pending until restoration of internet connectivity in Android Apps?

I am relatively new to developing Android apps. I have an android app that downloads several resources from the internet and keeps on generating these requests. I want to create a queue of such download requests when there is no internet connectivity and get them started as and when the connection is restored. In this case, the connectivity may be in either form both Mobile data as well as over Wifi

Upvotes: 2

Views: 1011

Answers (3)

There are several parts to this: first, detecting whether you're online now, if you're not online detecting when you'll come online, and having the actual queue.

The queue itself can use a SQLite database. You just need to store enough information to reconstruct what the request should be when you resume.

You can see the documentation on monitoring the connection state here.

Basically, if you're targeting API less than 24, you register a broadcast receiver to receive the CONNECTIVITY_ACTIVITY broadcast. (Otherwise, you can "listen" for CONNECTIVITY_CHANGE). Your logic once you figure out what request you want to queue will probably be something like the following:

  1. Push request onto the queue
  2. Check to see if you have connectivity
  3. If so: start processing the queue.
  4. Otherwise: wait for a broadcast receiver to notify you that you have connectivity again and start your service that does the processing.

Sorry to be a little vague (I'm not sitting in front of an IDE right now) but hopefully that outline'll be at least semi-useful.

Upvotes: 1

Haris Qurashi
Haris Qurashi

Reputation: 2124

Create a local database which should have HTTP request details, time stamp and its status. Whenever your application initiate HTTP request store it in database with HTTP request details and time stamp of its initiation and its status to non completed.

When your HTTP request is complete change its status to complete so when your Http request generates some kind of exception or error you don't have to do anything.

Now your application should have a connectivity broadcast listener so when your application connects with internet read your database and initiate your HTTP requests.

Upvotes: 0

John O'Reilly
John O'Reilly

Reputation: 10330

There's a number of popular "job queue" libraries that allow you to specify dependency on network being available (along with various retry policies). For example:

https://github.com/yigit/android-priority-jobqueue

https://github.com/evernote/android-job

Upvotes: 0

Related Questions