PX Developer
PX Developer

Reputation: 8145

Android: Advice on sending data to a server

I have an application that sends data to a server with a post request. This request can fail, and if it does I want it to retry until it's finally sent, something similar to WhatsApp: if u send a message when u are offline it stays as pendant and when you go online again the message is sent.

Since I don't know how WhatsApp internally works I have some doubts in how to implement that. I thought two ways:

1- Setting an AbstractThreadedSyncAdapter to be executed every X time (like 30 seconds) that checks if there is data to send and, if there is, it sends it to the server.

2- When the user clicks to send some data, I create a thread that tries to send it and, if it fails, it sleeps some seconds and try again.

I really don't like any of these options. The first one is going to increase the battery usage since the application is going to perform operations every X seconds even if it isn't needed. The second one is going to use a lot of battery if the request fails a lot of times.

Is there any better way to do it? It'd be awesome if there was an easy way to detect if the phone has connection to internet.

Thanks!

Upvotes: 1

Views: 158

Answers (1)

Heiko Rupp
Heiko Rupp

Reputation: 30934

In your scenario 2, you can set an alarm when the initial post fails to trigger a re-sent some time later. If the send succeeds, you cancel the alarm (or don't schedule another one).

For getting noticed when the device goes online you may look at this answer: https://stackoverflow.com/a/11084311/100957

Upvotes: 1

Related Questions