如果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