When my activity loads, I am connecting to a web service. As and when I get the response from service, I again call then service and so on.
@Override
protected void onCreate(Bundle savedInstanceState) {
….
callWebMethod();
}
// Called on getting response
@Override
public void run(String value) {
….
callWebMethod();
}
This is how I am connecting to service
HttpGet request = new HttpGet(url + combinedParams);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse;
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
response = StringUtils.remove(response, "\n");
response = StringUtils.remove(response, '"');
}
Is it possible that I connect to the service only once at the start, then the connection remains open and application keeps on reading data from service till connection is forcefully closed.
Please let me know if more code is required.
Update: I then tried with ClientConnectionManager but still connection is again and again initialising. Though it is getting data. What I want is that connection remains open, and keeps on reading data from service.
HttpParams httpParameters = new BasicHttpParams();
SharedPreferences preferences = context.getSharedPreferences(
"MyPreferences", Context.MODE_PRIVATE);
int timeoutConnection = Integer.parseInt(preferences.getString(
"timeout", "60")) * 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, 2000);
System.setProperty("http.keepAlive", "true");
HttpClient client = new DefaultHttpClient(httpParameters);
ClientConnectionManager mgr = client.getConnectionManager();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(
client.getParams(), mgr.getSchemeRegistry()),
client.getParams());
while (true) {
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
response = StringUtils.remove(response, "\n");
response = StringUtils.remove(response, '"');
((Activity) context).runOnUiThread(new Runnable() {
public void run() {
callback.run(response); // This calls activity callback function.
}
});
// Closing the input stream will trigger connection release
// instream.close();
}
} catch (ConnectTimeoutException e) {
….
}