Android Offline Request with Volley

前端 未结 3 946
臣服心动
臣服心动 2021-02-07 08:17

I want to give to my user a much better offline user experience, therefore, I want to build a Service which stores all POST, DELETE,

3条回答
  •  盖世英雄少女心
    2021-02-07 08:33

    You need to use a BroadcastReceiver to listen to network change events. Define a broadcastReciver in your AndroidManifest.xml with the following action.

    
         
            
         
    
    

    Also add the following permissions as well to your manifest file -

    
    
    

    NetworkBroadcastReceiver -

    public class NetworkBroadcastReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(final Context context, final Intent intent) {
    
            if(isInternetConnected(context)) {
                //Do something i.e. trigger an API call or start a IntentService etc.
            }    
        }
    
    
        public boolean isInternetConnected(Context context) {
            ConnectivityManager connectivityManager 
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }    
    }
    

    That's all you need to do to make a request as soon as you get Internet.

    To cache data, I'll advise you to parse the server response and keep it in your database for offline use. Every time you make a successful request save the new data in database and discard the old one. When user starts the app, load the data from database first and then trigger the Volley request, if request become successful then load the new data in app, store it in database and get rid of the old one. So in case if request fails, user will still be able to see the old data from previous successful request.

    To handle inconsistency between data in app and server, you need to use SyncAdapter. SyncAdapter provide a great support for periodic sync in the background. Just put the syncing code in onPerformSync() method of SyncAdapter. It might not work in following two scenarios - 1. If user isn't connected to internet 2. If user device is turned off

    To handle these scenario, use the BroadCastReceiver that I explained above in my answer to trigger the SyncAdapter. Also add the following actions to your receiver inside AndroidManifest.xml to listen to boot complete event of device.

    
    
    

    Let me know if you need more in depth explanation with coding example. Hope it helps

提交回复
热议问题