处理离线事件

时间:2015-03-12 09:21:55

标签: android caching event-handling offline-caching android-handler

我正在进行离线缓存。我想允许用户即使在他/她离线时也能制作事件。因为我正在使用一个处理程序来检查每一秒是否存在网络连接以及每当网络连接时执行与事件相关联的任务。例如,如果用户想要在他/她离线时发表评论,那么当他点击发布按钮时,将运行处理程序,只要用户的设备上有互联网连接就会发布评论。但是处理程序或线程可能不是最佳选择,因为它们将一直运行,直到网络连接存在并且还反复检查条件。还有其他更好的方法允许用户在他/她离线时安排事件并在网络连接时执行它们?

  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();
    }

1 个答案:

答案 0 :(得分:2)

您可以使用ConnectivityManager BroadcastReceiver进行此操作。有关这方面的更多信息,请访问Determining and Monitoring the Connectivity Status