Yogie Soesanto
Yogie Soesanto

Reputation: 172

Android AsyncTask How to Set Timer

i am new in Async Task android

i just really have one simple question.. please tell me where to look for if this question has been asked before

i am using AsyncTask

my doInBackground in this asynctask is used for POST Request to my Own Server

but sometimes, when my server is down maybe because of electricity or another problem,

this AsyncTask will load forever

and while the asynctask still running, i open my computer, and the server is up again, but the async task still running and loading forever until i close the program, and run in back

i dont want my user to experience it

i guess, what i want is

making the async task to run doInBackground for like 20second, and after 20 second, if there is still no result , then i will do something

how do i do that?

should i make another thread for this 20 second? or is there any timer that can be set to asynctask..

thanks before..

Upvotes: 1

Views: 357

Answers (1)

matiash
matiash

Reputation: 55340

You should add a timeout for the network operation. That way, it will throw an exception if this timeout is exceeded.

For example, if using a DefaultHttpClient, it would be something like:

HttpParams httpParameters = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT);

If it's an HttpUrlConnection instead, use:

connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setReadTimeout(SOCKET_TIMEOUT);

where CONNECTION_TIMEOUT and SOCKET_TIMEOUT are in milliseconds.

Upvotes: 4

Related Questions