我的android应用程序有一个BroadcastReceiver。在开始时,我启动一个Service,它有一个AlarmManager,用于每隔10分钟周期性地呼叫我的接收器,并且接收器尝试建立http连接。当接收方尝试创建httpConnection时,有时在行httpConnection.getResponseCode();或androidHttpTransport.call(soapAction, envelope);中需要花费一些时间,在这些情况下,android UI (Activity)会挂起并等待,直到接收方的操作完成。但是我认为BroadcastReceiver的操作是在一个单独的线程中,它不应该暂停UI线程。
为什么会发生这种情况?我如何纠正它?
接收器中的httpconnection:
private Object callWebServiceMethodPublic(String url,
String namespace, String methodName,
HashMap<String, Object> parameters, String soapAction)
throws Exception {
//System.setProperty("http.keepAlive", "false");
Log.i("WebService", "URL: " + url);
Log.i("WebService", "MethodName: " + methodName);
Log.i("SendMapMovements", "1.2.3.1");
URL myurl = new URL(url);
URLConnection connection = myurl.openConnection();
connection.setConnectTimeout(20 * 1000);
//connection.setRequestProperty("Connection", "close");
HttpURLConnection httpConnection = (HttpURLConnection) connection;
Log.i("SendMapMovements", "1.2.3.2");
int responseCode = -1;
try {
responseCode = httpConnection.getResponseCode();
Log.i("SendMapMovements", "1.2.3.3");
} catch (Exception e1) {
if (e1.toString().contains("Network is unreachable")) {
} else if (e1.toString().contains("SocketTimeoutException")) {
} else {
throw e1;
}
}
if (responseCode == HttpURLConnection.HTTP_OK) {
httpConnection.disconnect();
Log.i("SendMapMovements", "1.2.3.4");
SoapObject request = new SoapObject(namespace, methodName);
if (parameters != null) {
String[] keys = new String[0];
keys = (String[]) parameters.keySet().toArray(keys);
Object[] vals = (Object[]) parameters.values().toArray();
for (int i = 0; i < parameters.size(); i++) {
request.addProperty(keys[i], vals[i]);
Log.i("WebService", keys[i] + ": " + vals[i]);
}
}
Log.i("SendMapMovements", "1.2.3.5");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(url,
TimeOutInSeconds * 1000);
Log.i("SendMapMovements", "1.2.3.6");
try {
androidHttpTransport.call(soapAction, envelope);
Log.i("SendMapMovements", "1.2.3.7");
} catch (Exception e) {
if (e.toString().contains("XmlPullParserException")) {
throw new Exception(...);
}
}
Object so = envelope.getResponse();
System.gc();
return so;
} else {
httpConnection.disconnect();
Log.i("SendMapMovements", "1.2.3.8");
String strErrorDescription = getHttpErrorDescription(responseCode);
throw new Exception(strErrorDescription);
}
}发布于 2012-11-11 15:20:35
你必须在新的Thread中运行你的连接代码,而不是在UI Thread (Main Thread)上,因为BroadcastReceiver和你的Activity运行在同一个线程上。
https://stackoverflow.com/questions/13329281
复制相似问题