HTTP requests of the HTTP queue while the network is unavailable and processes them when turned on

I am new to Android and I created a small application that tracks my location. Now I have to do this to send these locations to an external API in JSON format, and I also managed to get it working.

The problem is that if a network connection is not available? What if I turn off my device?

I need to do something that will contain these places in the queue and pass them to the API if the network connection is available again.

I thought about maybe keeping them in SQLite, but I'm afraid of performance. Maybe some IntentService that would handle the queue? What do you suggest? How can I solve these problems?

+4
source share
1 answer

There is a request queue in the Volley library that can 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 for detecting when a network becomes available again, I used BroadcastReceiver, which listened to NetworkState's intentions.

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 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> 
+1
source

Source: https://habr.com/ru/post/1501146/


All Articles