所以我现在已经在Android应用程序上工作了一段时间。一切顺利,直到我在Android 2.2以上的设备上测试此代码。
我只是在AsyncTask中将数据发布到我的PHP服务器,它只是永远不会完成,没有任何错误。我试图设置超时但无济于事。我将每个不同的语句放在try {} catch {}块中,但它们都没有触发。通过在互联网上阅读,似乎错误是在HTTPClient.execute(httppost)序列中的某个地方。这是我的代码:
private class NewUserTask extends AsyncTask<Context, Void, String> {
@Override
protected String doInBackground(Context... params) {
Functions functions = new Functions();
if (!functions.isOnline(params[0])) {
return "false";
}
String result = null;
InputStream is = null;
StringBuilder sb = null;
String userDeviceID = Secure.getString(params[0].getContentResolver(),Secure.ANDROID_ID);
String userAccount = getUsername(params[0]);
HttpClient httpclient = null;
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
httpclient = new DefaultHttpClient(httpParameters);
}catch (Exception e) {
return "error httpclient setup";
}
String url = null;
try {
url = "http://www.xxx.com/xxx/xxx.php?userDeviceID=" + userDeviceID + "&database=" + "xxx" + "&userAccount=" + userAccount;
}catch (Exception e) {
return "url setup";
}
HttpPost httppost = null;
try {
httppost = new HttpPost(url);
}catch (Exception e) {
return "httppostsetup";
}
try {
httppost.setEntity(new UrlEncodedFormEntity(new ArrayList()));
}catch (Exception e) {
return "setetnityfsda";
}
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
}catch (Exception e) {
return "response";
}
try {
is = response.getEntity().getContent();
}catch (Exception e) {
return "getcontent";
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String temp = sb.toString();
temp = temp.substring(0, temp.length() - 1);
result = temp;
}catch (Exception e) {
return "error in reader";
}
return result;
}
protected void onPostExecute(String result) {
Functions functions = new Functions();
functions.showMessage("Info", result, DisplayExtrasActivity.this);
}
private String getUsername(Context context){
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(context).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
return account.name;
}
}
return null;
}
}
然后我称之为:
new NewUserTask().execute(DisplayExtrasActivity.this);
我真的希望有人能够帮助我,因为我几乎无望。我已经花了几个小时来解决这个问题,试图找出我出错的地方。
编辑: 更多代码!