1

I have few network activities in my application, Example- Database operation, Send/Receive Files etc. How can i limit the execution time of these activities? For example, if the file transfer operation to server is not completed within 1 minute , then i want to abort that operation and continue executing the remaining code. Can you give some reference for this?

djac
  • 187
  • 19

3 Answers3

1

Depending on type of http client you can set operations timeout and handle the timeout exceptions.

Here is good explanation how to handle timeouts in OkHttp: Retrofit and OkHttpClient, catch connection timeout in failure method

  1. Set timeout you prefer in your http client, like in example above: client.setConnectTimeout(10, TimeUnit.SECONDS); client.setReadTimeout(30, TimeUnit.SECONDS);

  2. Set handler for timeout exception (depending on your http client).

If you need custom operations timeout handling, you can use Executors to track if background operation completed or not, so you can implement general solution to extend any background operation with timeout, pretty interesting explanation of idea could be found here: ExecutorService that interrupts tasks after a timeout

Happy coding!

0

You can take the help of the following code:

HttpURLConnection urlc = (HttpURLConnection) urlConnect.openConnection();
urlc.setConnectTimeout(1000); //milliseconds
urlc.setReadTimeout(1000); //milliseconds

According to the Java manual:

connectTimeout

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection. If the timeout expires before the connection can be established, a java.net.SocketTimeoutException is raised. A timeout of zero is interpreted as an infinite timeout.

readTimeout

Sets the read timeout to a specified timeout, in milliseconds. A non-zero value specifies the timeout when reading from Input stream when a connection is established to a resource. If the timeout expires before there is data available for read, a java.net.SocketTimeoutException is raised. A timeout of zero is interpreted as an infinite timeout.

Debanik Dawn
  • 797
  • 5
  • 28
0

I would recommend to use okHttp as okHttp powers HttpURLConnection from Android 4.4. Here is the code ->

OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout
client.setReadTimeout(15, TimeUnit.SECONDS);    // socket timeout
Harsh
  • 599
  • 3
  • 20