Search code examples
androidcachingevent-handlingoffline-cachingandroid-handler

Handling offline events


I am doing offline caching.I want to allow user to make events even when he/she is offline.For that I am using a handler that checks every second whether net connection is there or not and whenever net connection is there it executes the task associated with the event.For example if user want to post comment when he/she is offline then when he click on post button a handler will run which will post the comment whenever internet connection is there on user's device.But using a handler or thread may not be the best choice as they will keep running until net connection is there and also checking condition repeatedly.Is there any other better way to allow user to schedule events when he/she is offline and execute them whenever netconnection is there?

  mPostCommentImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


        if(isNetworkAvailable())
        {
            postComment(mCommentEditText.getText().toString());
            hideKeypad();
            mCommentEditText.setText("");
        }
        else
        {
        Toast.makeText(getActivity(),"You comment will be posted once net connection is there",Toast.LENGTH_LONG).show();
            comment= new Handler();
            hideKeypad();
            final String commenttext=mCommentEditText.getText().toString();


            comment.postDelayed(runnable = new Runnable()
            {
                public void run() {

       addComment(videoid,commenttext,comment,runnable);
            comment.postDelayed(runnable, 2000);


                }
            },2000);
            refreshCommentList();
        }
    }


        });

public void addComment(String videoid,String commenttext, final Handler comment,final Runnable runnable) {

    if (isNetworkAvailable()) {
        CommentAPI.addComments(getApplicationContext(), videoid, commenttext, new APIResponseListener() {
            @Override
            public void onResponse(Object response)
            {
            comment.removeCallbacks(runnable);
            }


            @Override
            public void onError(VolleyError error)
            {



            }
        });
    }

}


private boolean isNetworkAvailable()
    {
        ConnectivityManager connectivityManager= (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

Solution

  • You can use the ConnectivityManager BroadcastReceiver for this. More information on this is available at Determining and Monitoring the Connectivity Status.