The Android main thread does not have access to the network exception solution from the two aspects of the question:
1. Reasons for not allowing access to the network
2. Solutions to the problem
Reasons for not allowing access to the network:
Due to the unpredictability of network conditions, it is possible to block when 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 from the main thread, the exception is reported, and the name is Networkonmainthreadexception
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
The Android main thread cannot access network exception resolution