如果HTTP连接不超时,你可以在后台线程本身(AsyncTask,Service等)中实现超时检查器,下面的类是考试PLE为自定义的AsyncTask其一定时期
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);
}
针对此
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;
};
}
我将该值设置为10分钟。然而,在2分钟之前,它会抛出一个'java.net.ConnectException:Connection超时:connect'。你知道是什么导致了这个问题? – Pacerier 2012-02-03 10:16:32
@dbyrne这对我来说似乎有点困惑 - 因为我们在创建HttpURLConnection对象后设置了超时时间,所以我想知道代码中引发'SocketTimeoutException'的确切位置是什么? – Less 2013-07-24 16:57:36
SocketTimeoutException是IOException的子类。如果两个catch块都执行相同的操作,则可以捕获IOException。 – spaaarky21 2013-12-05 22:27:01