Android.os.NetworkOnMainThreadException

Source: Internet
Author: User

Because the HTTP request is written in the main thread, after 4.0 in the main thread inside the HTTP request will be reported this error, probably is afraid of HTTP request time too long cause the program suspended animation situation it.

There are two ways to solve this, and I'll describe each of the following:

The first, is directly ignored in the main thread, enforced. (This method is not recommended, but the method is simple to modify.)

Under Setcontentview (R.layout.activity_main) of the mainactivity file, add the following code

9) {        new StrictMode.ThreadPolicy.Builder (). Permitall (). build ();  Strictmode.setthreadpolicy (Policy);  }

If you have an error, add it to the class header.

@Targetapi (build.version_codes. Gingerbread) @suppresslint ("Newapi")  

Add the above oncreate:

@Suppresslint ("Newapi") 

Second, start another thread to perform network connection tasks, such as using Thread, Runnable, Handler (this method is recommended)

The code is as follows:

Publicvoid OnCreate (Bundle savedinstancestate) {Super.oncreate (savedinstancestate);This.setcontentview (R.layout.share_mblog_view);New Thread (runnable). Start ();} Handler Handler =new Handler () { @Override public void handlemessage (Message msg) {super.handlemessage (msg); Bundle data = Msg.getdata (); String val = data.getstring ( "MyLog",  "request Result--" + val);}} Runnable Runnable = new Runnable () { @Override  Public void run () {////todo:http request. //message msg = new message (); Bundle data = new bundle () data.putstring ( 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.