Anshu Dwibhashi
Anshu Dwibhashi

Reputation: 4675

How to queue requests in Volley when no internet connection?

Is it possible to queue a request in Volley, such that if there's no internet connection at the present time, it waits until there's an internet connection available, and then makes the request?

Looking at Volley's documentation, I'm quite sure I have to call setRetryPolicy() on a Request object, passing in a RetryPolicy object. However, I'm not quite sure how to implement it's retry() method to execute the desired behaviour.

The Volley documentation doesn't quite inform us when exactly the retry() method will be called, so I'm unsure how to go about this:

http://afzaln.com/volley/com/android/volley/RetryPolicy.html#retry(com.android.volley.VolleyError)

Upvotes: 1

Views: 1484

Answers (1)

Anshu Dwibhashi
Anshu Dwibhashi

Reputation: 4675

Here's a way of doing it that doesn't quite involve the Request.retry() method of Volley:

First, each time I make a Volley request, I first test if there's any internet connection using this function:

public boolean isInternetConnected(Context context) {
    ConnectivityManager connectivityManager 
        = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

If there isn't any internet connection, I save the request in a SharedPreferences file. (You may argue if this is a good way of storing pending web-requests, but I just needed something to get up and running quickly. You may use a database if you want.)

I defined a BroadcastReceiver in my manifest to respond to internet connectivity changes.

<receiver android:name=".NetworkBroadcastReceiver" >
     <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
     </intent-filter>
</receiver>

And then in the NetworkBroadcastReceiver:

public class NetworkBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        if(Utlis.isInternetConnected(context)) { 
            // Here, I read all the pending requests from the SharedPreferences file, and execute them one by one.
        }    
    }
}

Upvotes: 3

Related Questions