Say this question from two aspects:
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'sRunmethod to performdosomething. There's another one in there.Handlerobject, which in turn involves cross-threading modificationUIthe problem with the element content. In theJavais not allowed to be modified across threadsUIelement, as we would like to modify in a newly started threadUIin the main threadTextViewtext, the error is reported. If you want to do this, we have to useHandlerthis class to implement. About thisHandlerclass, we'll write a separate blog to introduce it.
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) StrictmodeModify 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