Run the code you posted above in a back-ground thread (either as a plain
thread or an AsyncTask's 'doInBackground(...)' implementation).
After 5 seconds or on user input, call either the back-ground thread's
'interrupt()' method (if you are using a plain Thread) or 'cancel(true)' on
your AsyncTask (if you're using AsyncTask).
Network I/O is usually (immediately) interrupted by Thread interruptions.
--- Anton.
On Friday, October 5, 2012 7:39:55 PM UTC-4, saex wrote:
> i have a thread that is connecting to a url to obtaining some data.
> Sometimes the method httpConnection.connect(); taked too munch time to
> get the response, and i want to limit the loading dialog of this connection
> thread to 5 seg.
> I tryed adding timeouts into the code, *but it doesn't work*!!
> URL formattedUrl = new URL(url);
> URLConnection connection = formattedUrl.openConnection();
> connection.setConnectTimeout(5000);
> connection.setReadTimeout(5000);
> HttpURLConnection httpConnection = (HttpURLConnection) connection;
> httpConnection.setAllowUserInteraction(false);
> httpConnection.setInstanceFollowRedirects(true);
> httpConnection.setRequestMethod("GET");
> httpConnection.setConnectTimeout(5000);
> httpConnection.setReadTimeout(5000);
> httpConnection.connect();
> So, i must stop the connect method and the thread when 5000 seconds have
> passed or when the used has pressed the back key on the phone.
> How can this be achieved? i can't find info about doing this work in
> android with a url connection thread.
> thanks