Jeśli połączenie HTTP nie ma limitu czasu, możesz zaimplementować sprawdzanie limitu czasu w samym wątku tła (AsyncTask, Service, itp.), kolejna klasa to egzamin ple dla Dostosuj AsyncTask których limit czasu po pewnym okresie
public abstract class AsyncTaskWithTimer<Params, Progress, Result> extends
AsyncTask<Params, Progress, Result> {
private static final int HTTP_REQUEST_TIMEOUT = 30000;
@Override
protected Result doInBackground(Params... params) {
createTimeoutListener();
return doInBackgroundImpl(params);
}
private void createTimeoutListener() {
Thread timeout = new Thread() {
public void run() {
Looper.prepare();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (AsyncTaskWithTimer.this != null
&& AsyncTaskWithTimer.this.getStatus() != Status.FINISHED)
AsyncTaskWithTimer.this.cancel(true);
handler.removeCallbacks(this);
Looper.myLooper().quit();
}
}, HTTP_REQUEST_TIMEOUT);
Looper.loop();
}
};
timeout.start();
}
abstract protected Result doInBackgroundImpl(Params... params);
}
próbkę tego
public class AsyncTaskWithTimerSample extends AsyncTaskWithTimer<Void, Void, Void> {
@Override
protected void onCancelled(Void void) {
Log.d(TAG, "Async Task onCancelled With Result");
super.onCancelled(result);
}
@Override
protected void onCancelled() {
Log.d(TAG, "Async Task onCancelled");
super.onCancelled();
}
@Override
protected Void doInBackgroundImpl(Void... params) {
// Do background work
return null;
};
}
Ustawiam wartość na 10 minut. Jednak wyrzuca mi 'java.net.ConnectException: Connection time out: connect' zanim minie nawet 2 minuty. Czy wiesz, co jest przyczyną problemu? – Pacerier
@dbyrne wydaje mi się to nieco kłopotliwe - ponieważ ustawiliśmy timeout po utworzeniu obiektu 'HttpURLConnection', zastanawiam się, jakie jest dokładne miejsce w kodzie, które podniesie' SocketTimeoutException'? – Less
SocketTimeoutException jest podklasą wyjątku IOException. Jeśli oba bloki catch robią to samo, możesz po prostu wychwycić wyjątek IOException. – spaaarky21