The ultimate solution to the no-network router (Transaction Thread blocking), the ultimate transaction
In order to solve the problem of No-network router timeout last time, the focus of the problem was shifted to HttpClient and HttpUrLConnection. What are the ReadTimeout and connectionTimeOut settings, and the so-called HttpParameters, which finally ended in failure. I also searched for a lot of similar things on the internet, and I also saw a lot of solutions to such problems, but I didn't see any real solutions. Later ..
Okay, let's talk about code.
Class BaiduHttpCallable implements Callable <Boolean> {
Private GetUrlFromServerCallBack listener;
BaiduHttpCallable (GetUrlFromServerCallBack listener ){
This. listener = listener;
}
@ Override
Public Boolean call () throws Exception {
HttpURLConnection conn = null;
Try {
URL url = new URL ("http://www.baidu.com ");
Conn = (HttpURLConnection) url. openConnection ();
Conn. setRequestMethod ("GET ");
Conn. setConnectTimeout (5000 );
Conn. connect ();
Int responseCode = conn. getResponseCode ();
If (responseCode = 200 ){
Listener. onRequestSuccess ("wocao ");
} Else {
Listener. onNetError ();
}
} Catch (Exception e ){
Listener. onNetError ();
}
Log. e ("luomz", "over ");
Return true;
}
Public static void testConnection (GetUrlFromServerCallBack listener ){
FutureTask <Boolean> testConnectionTask = new FutureTask <Boolean> (new BaiduHttpCallable (listener ));
New Thread (testConnectionTask). start ();
Try {
TestConnectionTask. get (1, TimeUnit. SECONDS );
} Catch (Exception e ){
// Do something
Log. e ("luomz", "time out ");
Listener. onNetTimeOut ();
}
}
Public interface GetUrlFromServerCallBack {
Public void onNetError ();
Public void onNetTimeOut ();
Public void onRequestSuccess (String result );
}
The red part above is actually the most central solution, and an exception is actively thrown to solve the essential problem by using the blocked retrieval of FutureTask.
Recently, the body is not very good and dizzy, and the language organization is quite rough, but it is the most important thing to solve the problem.
In fact, the setTimeOut and other exceptions can be caught, but the premise can pass through a domain name detection phase (no network router is unable to pass through the blocking here, leading to the invalid timeout method you set)
I am also new to android for half a year. I hope you can learn and communicate with each other if you have any questions.
QQ 918032447 (don't add it if it's not a single girl)
If you do not need to test the demo, you can directly call the static method in it. This just provides an idea. If multiple threads are used for simultaneous monitoring, you 'd better add synchronized.
Finally, I wish you all the best !~~~