我使用 AsyncTask 来连接互联网。 进度对话框可以在 onPreExecute() 处显示,我检查该移动设备是否在线,如果是,则意味着它将执行 http 连接代码,还会在 onPostExecute() 处关闭进度对话框,其工作效果也很好。
但是,如果请求时网络连接可用,并且在获得响应之前连接关闭,则我会遇到问题,这意味着进度对话框始终显示。
现在我想解决这个问题,如果在获得响应之前互连断开意味着它会提醒我没有互联网连接并关闭进度对话框(可以将加载时间限制设置为 30 秒)。
下面是我的代码。
有人可以帮忙吗?
public class SubjectTask extends AsyncTask<Void, Void, Integer> {
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Login.this, "Loading",
"Please wait...");
//checkConnection();
}
@Override
protected Integer doInBackground(Void... arg0) {
if (isOnline()) { //using ConnectivityManager And Network Info
try {
//Http Request connections
} catch (Exception e) {
e.printStackTrace();
}
return 1;
} else {
alert("Check your internet connection");
return 0;
}
}
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
最佳答案
您可以使用广播接收器来获取网络连接或断开的事件。在 doInbackground 方法中注册此接收器,并在 onPostExecute 方法中取消注册。
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivity.getActiveNetworkInfo();
//Play with the info about current network state
if(info.getState()== NetworkInfo.State.DISCONNECTED) {
// hide loader and show alert here
}
}
}
};
intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
关于java - 如何在android AsyncTask中设置等待互联网连接的时间限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24902760/