Maintaining session in android ( application stay authenticated on the server side)

Finally I solved the issue of session handling in Android. Android cant handle the session itself(which a simple browser can) so we have to handle it explicitly. I changed the code for http connection a bit. Created an instance of DefaultHttpClient in the first Activity when connection established.

public static DefaultHttpClient httpClient;

For the first time connection,I did the following:

URL url=new URL(urlToHit);
LoginScreen.httpClient = new DefaultHttpClient(); //LoginScreen is the name of the current Activity

HttpPost httppost = new HttpPost(url.toString());
HttpResponse response = LoginScreen.httpClient.execute(httppost); 

xr.parse(new InputSource(url.openStream())); //SAX parsing

Now for all further connections I used the same httpClient For example in the next activity:

URL url=new URL(urlToHit);

HttpPost httppost = new HttpPost(url.toString());
HttpResponse response = LoginScreen.httpClient.execute(httppost); 

// Log.v("response code",""+response.getStatusLine().getStatusCode());

// Get hold of the response entity
HttpEntity entity = response.getEntity();

InputStream instream = null;

if (entity != null) {
    instream = entity.getContent();
}
xr.parse(new InputSource(instream)); //SAX parsing

Hope this will help you all too to solve session issue in Android.


The best idea is to put all the function that your server do in on unique class which is going to be call by the tasks which want to connect. I call this class WebServiceManager. This class have exactly the same method than the server.

As you want an unique session do :

private static WebServiceManager wsm = null;

public static WebServiceManager getInstance() {
    if (wsm == null) {
        wsm = new WebServiceManager();
    }
    return wsm;
}

private final HttpClient httpClient;

private WebServiceManager() {
    httpClient=new DefaultHttpClient();
}

and then you call the method of your instance of webServiceManager to use always the same session. :)