【发布时间】:2011-12-19 17:06:39
【问题描述】:
我的应用程序执行了一个 HTTP 请求,它将数据提交到一个 php 脚本,然后等待响应。当手机有互联网连接,但连接非常糟糕(即信号不好,或路由器未连接到互联网)时,应用程序只会强制关闭。我怎样才能阻止这种情况?
到目前为止,这些是它所采取的步骤
用户按下提交按钮
这会启动一个异步任务,以确保手机有连接(坏连接通过此)
它执行 HTTP Post
等待响应
所有这些步骤都被处理异常的 try 和 catch 包围,但是我仍然强制关闭。
这里是 AsyncTask 代码
private class checkDatabase extends AsyncTask<String, Void, Boolean> {
ProgressDialog progressDialog;
protected void onPreExecute() {
super.onPreExecute();
// Starting the progress dialog
progressDialog = ProgressDialog.show(Login.this, "",
"Connecting. Please wait...", true);
}
protected Boolean doInBackground(String... info) {
// TODO Auto-generated method stub
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
String us = info[0];
String ps = info[1];
String responseText;
if (us.equals("") || ps.equals("")) {
//No username or password
return false;
} else {
try {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.myfirstagent.com/android/loginquery.php");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("username",
us));
nameValuePairs.add(new BasicNameValuePair("password",
ps));
httppost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
HttpResponse response;
// Execute HTTP Post Request
try {
response = httpclient.execute(httppost);
responseText = EntityUtils.toString(response
.getEntity());
} catch (Exception e) {
//problem connecting
return false;
}
if (responseText.equals("accept")) {
return true;
} else if (responseText.equals("decline")) {
//invalid username or password
return false;
} else {
//something went wrong
return false;
}
} catch (Exception e) {
//something went wrong
return false;
}
}
} else {
//No connection
return false;
}
}
protected void onPostExecute(Boolean result) {
// Dismissing the progress dialog
if (progressDialog.isShowing())
progressDialog.dismiss();
super.onPostExecute(result);
}
}
【问题讨论】:
-
什么是导致强制关闭的异常?
-
你的应用有权限上网吗?
-
我不确定异常是什么,因为它发生在没有连接的地方,而且我不确定如何模拟坏连接,因为我家只有良好的连接。
-
您可以在您的设备上开启飞行模式...
-
可能会停用您的网络检查,设置飞行模式可以帮助您重现问题
标签: java php android httpresponse