Problem:
Recently, I am working on a major software engineering job. I use spring MVC as the server and Android as the client.
Then the Tomcat server is enabled on the computer, and the android Virtual Machine Test client is used to find that the server can be connected, but the real machine test is still unable to connect.
Cause:
From Android 3, Google forces the main UI thread to initiate communication requests by default.
My virtual machine SDK version is 2.3.3, while the mobile phone is 4.1.1, so the virtual machine can connect to the server, but the real machine cannot.
Solution:
Method 1.You can temporarily specify stickmode during the initial stage of the activity to bypass the OS check, but do not take this as a complete solution.
Add:
StrictMode.setThreadPolicy(new Strict Mode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog() .build()); StrictMode.setVmPolicy(new Stric tMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .penaltyLog() .penaltyDeath() .build());
Add the @ suppresslint ("newapi") annotation before the oncreate () method.
Method 2:
After testing, the method above succeeded only when the program has only one activity, and the HTTP connection for multiple activities has not been successful, so this method is not universal.
A better way is to open a subthread for asynchronous HTTP connection.
We recommend that you use the aynstask class for asynchronous processing.
Aynstask is a set of classes provided by Android for asynchronous processing. This class can be used to open up a new thread for processing the time-consuming program and return the result after processing.
In fact, the asyntask class is an encapsulation of the thread class and some new methods are added.
We recommend that you read this article for more details: Click to open the link.
You can also use the handler + thread structure to view your preferences.