The reason Google after Android4.0, prohibit the main thread to access the network for a better user experience. That is, the main thread is for the display of the interface. If the main thread accesses the network, it will cause "lag". That is, the network situation is unpredictable, it is possible to block the network access, so that our main thread UI thread will appear suspended animation phenomenon, resulting in a very bad user experience. So, by default, if accessed directly in the main thread, the exception is reported, and the name is networkonmainthreadexception. The thread is closed at the corresponding time of the main thread operation 5s, so it takes a lot of time to put the operation on the child thread.
solutions to this problem
1. Standalone Threads
2. Asynchronous Thread Asynctask
3. Strictmode Modify the default policy
1) method of independent threading
To start a new thread's code:
New Thread () {
@Override
public void Run () {
DoSomething ();
Handler.sendemptymessage (0);
}
}.start ();
Here we rewrite the thread class's Run method and execute dosomething. There is also a handler object, which involves modifying the content of UI elements across threads. In Java, it is not allowed to modify UI elements across threads, as we will report an error when we want to modify the TextView text in the main thread of the UI in the newly-launched threads. If you want to do this, we have to use the handler class to achieve. For the use of this handler class, we will write a separate blog to introduce.
2) method of asynchronous invocation Asynctask
Here about Asynctask introduction of the article is good, the details of the author's introduction it
http://www.cnblogs.com/dawei/archive/2011/04/18/2019903.html#2824345
Next, there will be a blog dedicated to all the ways to update the main thread UI threads
3) Strictmode Modify the default policy
In the OnCreate method of our Activity class, the following rules are set:
Strictmode.threadpolicy policy=new StrictMode.ThreadPolicy.Builder (). Permitall (). build ();
Strictmode.setthreadpolicy (Policy);
This can also solve the problem
For a specific introduction to Strictmode, see another blog for a very detailed description:
Http://hb.qq.com/a/20110914/000054.htm
Android sub-thread access network