【发布时间】:2015-03-12 09:21:55
【问题描述】:
我正在做离线缓存。我想允许用户在他/她离线时进行事件。为此,我正在使用一个处理程序,它每秒检查网络连接是否存在以及网络连接是否存在执行与事件关联的任务。例如,如果用户想在他/她离线时发表评论,那么当他点击发布按钮时,将运行一个处理程序,只要用户设备上有互联网连接,就会发布评论。但是使用处理程序或线程可能不是最佳选择,因为它们将一直运行直到存在网络连接并反复检查条件。是否有任何其他更好的方法允许用户在他/她离线时安排事件并在网络连接存在时执行它们?
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();
}
【问题讨论】:
标签: android caching event-handling offline-caching android-handler