Search code examples
androidbroadcastreceiverandroid-serviceintentserviceandroid-networking

Fetch data from network when network connection is available in a scheduled service


I have an app that effectively kicks off an intent service every 5 hours (from boot) to fetch data from the network.

What I want to achieve is if there is no network connection (at the time of fetching), subscribe to some broadcast to listen to when a network becomes available and fetch data again.

What is the best approach/technique to achieve this?

Also, I would probably want to cancel the subscription (for network connection broadcast), after I have successfully fetched the data this way, and reset the original service schedule so it checks again in 5 hours.


Solution

  • In the end what I did was allowed my Broadcast receiver via the manifest (which kicks of my intent service) to listen for android.net.conn.CONNECTIVITY_CHANGE. i.e. this enabled me to listen for changes in the network.

    Now in my intent service, if data failed to fetch due to network connection, then I would set a flag in shared pref called "waiting_for_connection";

    If on network changed I would check the "waiting_for_connection" flag and if set. If false, then I would just return; otherwise I would proceed to fetch data only if there is a network. And if successful, I would reset the flag.