Android.os.NetworkOnMainThreadException Workaround:

Source: Internet
Author: User

Causes of the production:

Executing HTTP requests in the main thread after 4.0 will report the error, perhaps because the HTTP request is too long to cause the program to feign death.

Workaround:

1. Add the following code to the OnCreate function inside the activity that initiated the HTTP request

Strictmode.setthreadpolicy (New StrictMode.ThreadPolicy.Builder (). Detectdiskreads (). Detectdiskwrites (). Detectnetwork (). Penaltylog (). build ());
Strictmode.setvmpolicy (New StrictMode.VmPolicy.Builder (). Detectleakedsqlliteobjects (). Detectleakedclosableobjects (). Penaltylog (). Penaltydeath (). build ());

2. use thread, Runnable, handler three classes

Public void 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 ("value");         LOG.I ("MyLog", "request result is-- > " + val";     }}runnable runnable = new runnable () {      @Override        public void ruN ()  {              message msg  = new message ();        bundle data =  New bundle ();         data.putstring ("Value", "request result");         msg.setdata (data);         Handler.sendmessage (msg);     }}


Android.os.NetworkOnMainThreadException Workaround:

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.