My android application has a BroadcastReceiver. At start I start a Service that has an AlarmManager for calling my receiver periodically every 10 minutes and the receiver tries to make a http connection. When the receiver is trying to make a httpConnection sometimes it takes times in lines httpConnection.getResponseCode(); or in androidHttpTransport.call(soapAction, envelope); and in these situations android UI (Activity) hangs and waits until the receiver’s operation is completed. But I think the BroadcastReceiver’s operation is in a separate thread and it should not pauses UI thread.
Why this happens and how can I correct it?
My httpconnection in receiver:
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);
}
}
you must run your connection code whithin new
Thread, not onUI Thread (Main Thread), because theBroadcastReceiverand yourActivityruns on the same thread.