Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android queue http requests while network is unavailable and process them when turned on

I'm new in Android and I created a little app that tracks my location. Now I what I need to do is to send these locations to external API in JSON format and I was able to get it working also.

The problem is, what if network connection is unavailable? And what if I turn off my device?

I need to do something that will hold those locations in queue and proceed them to API if network connection would be available again.

I thought about maybe holding them in SQLite but I am afraid about performance. Maybe some IntentService that would process the queue? What would you suggest? How should I solve those problems?

like image 667
newicz Avatar asked Nov 12 '22 22:11

newicz


1 Answers

The Volley library features a request queue which may help you. http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/ http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put

As far as detecting when the network becomes available again, i used a BroadcastReceiver listening for NetworkState intents.

NetworkStateReceiver.java

           public class NetworkStateReceiver extends BroadcastReceiver
        {
            private final static String TAG = "NetworkStateReceiver";

            public void onReceive(Context context, Intent intent)
            {
            Log.d(TAG, "Network connectivity change");
            if (intent.getExtras() != null)
            {
                ConnectivityManager connectivityManager = ((ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE));

                NetworkInfo ni = (NetworkInfo) connectivityManager.getActiveNetworkInfo();
                if (ni != null && ni.getState() == NetworkInfo.State.CONNECTED)
                {
                                    //Network becomes available
                    Log.i(TAG, "Network " + ni.getTypeName() + " connected");
                }
                else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
                        Boolean.FALSE))
                {
                    Log.d(TAG, "There's no network connectivity");
                }
            }
        }

    }

Manifest

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 <receiver android:name="YOUR.PACKAGE.NetworkStateReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" >
                </action>
            </intent-filter>
        </receiver>
like image 143
user2818782 Avatar answered Nov 14 '22 23:11

user2818782