Search code examples
androidmultithreadingtimerunnableterminate

Android: run thread for an amount of time


In my app I'm making calls to an API to fetch some JSON. Sometimes when people are on 2g network or their network drops the wait time becomes awkwardly long (especially when you show a dialog), thus I would like to kill the thread after let's say 45 seconds.

I've searched on SO and found this thread: Running a thread for some seconds.

Is this the best way to do this?

The code I have is in the form of:

new Thread(new Runnable() {
                public void run() {
                     //i.e.
                    fetchJSON();
                }
            }).start(); 

Cheers!


Solution

  • For this, you actually need to use HTTP's connection_timeout feature to make your web calls terminate automatically after some time. for example:

    final int CONNECTION_TIME_OUT = 45;     //in seconds
    
    HttpParams httpPar = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpPar, CONNECTION_TIME_OUT * 1000);
    HttpConnectionParams.setSoTimeout(httpPar, CONNECTION_TIME_OUT * 1000);
    HttpClient client = new DefaultHttpClient(httpPar);
    

    With this, your client will automatically terminate http connection if it takes more than 45 seconds to complete your request.