Nếu Kết nối HTTP không hết thời gian chờ, Bạn có thể thực hiện trình kiểm tra thời gian chờ trong chính chuỗi nền (AsyncTask, Service, v.v.), lớp sau đây là một bài kiểm tra ple cho Customize AsyncTask mà thời gian chờ sau thời gian nhất định
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);
}
Một mẫu cho điều này
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;
};
}
Nguồn
2014-12-22 09:31:16
Tôi đặt giá trị thành 10 phút. Tuy nhiên nó ném cho tôi một 'java.net.ConnectException: Kết nối đã hết thời gian: kết nối' trước cả 2 phút. Bạn có biết điều gì gây ra vấn đề không? – Pacerier
@ dbyrne điều này có vẻ hơi khó hiểu với tôi - vì chúng tôi đặt thời gian chờ sau khi đối tượng 'HttpURLConnection' được tạo, tôi tự hỏi đâu là vị trí chính xác trong mã sẽ tăng' SocketTimeoutException'? – Less
SocketTimeoutException là một phân lớp của IOException. Nếu cả hai khối catch làm cùng một điều, bạn chỉ có thể bắt IOException. – spaaarky21