Java 等待internet响应时强制关闭
我的应用程序执行了一个HTTP请求,将数据提交给php脚本,然后等待响应。当手机已连接互联网,但连接非常糟糕,即信号不好,或路由器未连接到互联网时,应用程序将强制关闭。我怎样才能阻止这一切 到目前为止,这些是它采取的步骤 人员按下提交按钮 这将启动一个异步任务,确保手机有一个连接错误连接通过此任务 它执行HTTP Post 它等待响应 所有这些步骤都围绕着try-and-catch,它们处理异常,但我仍然得到强制关闭 下面是异步任务代码Java 等待internet响应时强制关闭,java,php,android,httpresponse,Java,Php,Android,Httpresponse,我的应用程序执行了一个HTTP请求,将数据提交给php脚本,然后等待响应。当手机已连接互联网,但连接非常糟糕,即信号不好,或路由器未连接到互联网时,应用程序将强制关闭。我怎样才能阻止这一切 到目前为止,这些是它采取的步骤 人员按下提交按钮 这将启动一个异步任务,确保手机有一个连接错误连接通过此任务 它执行HTTP Post 它等待响应 所有这些步骤都围绕着try-and-catch,它们处理异常,但我仍然得到强制关闭 下面是异步任务代码 private class checkDatabase e
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);
}
}
只要检查响应是否为空 如果你想抓住一切可能发生的事情,你可以抓住一个一次性的
了解如何读取堆栈跟踪,这是最好的建议。你必须了解你的程序在哪里失败,以及他们如何有机会了解失败的原因并纠正错误。导致强制关闭的异常是什么?你的应用程序是否有访问互联网的权限?我不确定异常是什么,因为它发生在没有连接的地方,我不知道如何模拟坏的连接,因为我家只有一个好的连接。你可以在你的设备上打开飞行模式…可能正在禁用网络检查,设置飞行模式可以帮助你重现问题我可以这样做,但是,我无法获得任何错误消息,因为我无法在完全连接的情况下在家中重新创建此错误。我已经完成了此操作,但是没有收到相同的错误。即使我移除了连接检查。