I have an app with an httprequest. I wanted to set a timeout for that request, and since I can't control de DNS timeout a user from stackoverflow suggested to create a Thread with a timer to cancel the request after a certain time, and that's what I'm doing.
In my new Thread I use Thread.sleep to wait 30 seconds and, when that time finishes, cancel the request if it hasn't ended, but my Thread never wakes up. This is my code:
private Thread timeout_request = new Thread(new Runnable() {
public void run() {
try{
Log.d(TAG, "Thread start");
Thread.sleep(30000);
Log.d(TAG, "Thread awake");
if(!httprequest_finished){
request_aborted = true;
mHttpClient.getConnectionManager().shutdown();
}
}catch(Exception e){
e.printStackTrace();
}
}
});
public String sendData(String token){
...
timeout_request.start();
Log.i(TAG, "Sending request");
final HttpResponse resp = httpClient.execute(post);
Log.i(TAG, "Execute finished");
if(request_aborted) return null;
httprequest_finished = true;
...
}
If I execute the sendData function without internet connection the log shows "Sending request" and "Thread start", but doesn't show "Thread awake" or "Execute finished" (I've waited like 5 minutes). Why is that?
------ EDIT ------
By the way, I don't know if it matters, but I'm using ThreadSafeClientConnManager in my connection.
I've tested a few thing:
1- Replace HttpResponse resp = httpClient.execute(post) with while(!request_aborted). The thread awakes (it works).
2- Use mHandler.postDelayed(r, 30000) instead of a Thread. I'm still executing httpClient.execute(post). Result: the Runnable is NOT launched.
private Handler mHandler = new Handler();
private Runnable r = new Runnable() {
public void run() {
Log.d(TAG, "Runnable()");
if(!httprequest_finished){
request_aborted = true;
mHttpClient.getConnectionManager().shutdown();
}
}
};
3- Use mHandler.postDelayed(r, 30000) instead of a Thread. Replace HttpResponse resp = httpClient.execute(post) with while(!request_aborted). Result: the Runnable is NOT launched.
So the thread works if I'm not executing the http request, but the handler never works. I noticed these lines in my log:
threadid=3: reacting to signal 3
Wrote stack traces to '/data/anr/traces.txt'
threadid=3: reacting to signal 3
Wrote stack traces to '/data/anr/traces.txt'
This appears 6 or 7 seconds after executing the thread or setting the handler. I've tried to use:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
Log.e("Alert","Lets See if it Works !!!");
}
});
But the log never shows "Lets See if it Works !!!". I looked the traces.txt file and I don't understand what it's saying -.-