有谁知道如何处理 ConnectTimeoutException?我正在使用 AsyncTask 将变量发布到 url,但我的互联网连接令人震惊,所以由于 ConnectTimeoutException,我正在接收空数据。处理此问题的最佳方法是什么,例如,如果发生超时,请尝试再次运行等我之前没有遇到过这个问题,所以不知道如何处理,但我觉得它需要处理以改善用户体验。所以有什么想法吗?
问问题
1089 次
3 回答
0
这是您应该检查网络状态的方式
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
//execute your AsyncTask method
} else {
//maketoast..."No network connection available"
}
于 2013-03-01T14:49:37.130 回答
0
创建一个名为 Activity 助手的单独类,并在您的异步任务中为您创建的任何需要 Web 服务调用的类实现它。
public class ActivityHelper {
public static final String NETWORK_CONNECTION_MESSAGE = "No Network Connection. Please make sure you have a Network Connection.";
public static boolean isNetworkPresent(Context applicationContext){
boolean hasService = false;
NetworkInfo info=(NetworkInfo)( (ConnectivityManager)applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
hasService = (info==null || !info.isConnected())?false:true;
return hasService;
}
}
在“doInBackground”方法中调用 Activity Helper 有点像这样..
private class YourAsyncTask extends AsyncTask<String, Void, String> {
Message message = new Message();
String type = "";
protected void onPreExecute() {
ActivityHelper.onUserInteraction(getApplicationContext());
dialog = ProgressDialog.show(LocationType.this,
"Connecting to server", "Please wait...", true, true);
dialog.setCancelable(false);
}
protected String doInBackground(final String... args) {
try {
if(!ActivityHelper.isNetworkPresent(getApplicationContext())){
message.what = ActivityHelper.NONETWORKCONNECTION;
return null;
}
} catch (Exception e) {
Log.e(this.getClass().getName(),
"Exception Message");
}
return null;
}
于 2013-03-01T15:35:54.583 回答