处理离线事件

Handling offline events

我正在离线 caching.I 想要允许用户创建事件,即使 he/she 是 offline.For 我正在使用一个处理程序每​​秒检查是否存在网络连接或不是,只要有网络连接,它就会执行与 event.For 示例相关的任务,如果用户想 post 在 he/she 离线时发表评论,那么当他单击 post 按钮时处理程序将 运行 每当用户 device.But 上存在互联网连接时,使用处理程序或线程将 post 注释可能不是最佳选择,因为它们将保持 运行ning 直到是否存在网络连接并检查条件 repeatedly.Is 还有其他更好的方法允许用户在 he/she 离线时安排事件并在网络连接存在时执行它们吗?

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

您可以使用 ConnectivityManager BroadcastReceiver for this. More information on this is available at Determining and Monitoring the Connectivity Status.