HTTP requests cannot be made in the main thread after resolving Android3.0

Source: Internet
Author: User

After Android3.0, it will be found that the runtime will make an error if the HTTP request is written in the main thread (that is, activity), because Android after 3.0 is in order to prevent the application of the ANR (aplication not Response) exception.

There are two ways to solve this problem:

1. You can add such a piece of code to the OnCreate () method of the activity, as follows:

1  if (Build.VERSION.SDK_INT >=) {      2      strictmode.setthreadpolicy (new  StrictMode.ThreadPolicy.Builder (). Detectdiskreads (). Detectdiskwrites (). Detectnetwork (). Penaltylog (). build ());     3      Strictmode.setvmpolicy (new  StrictMode.VmPolicy.Builder (). Detectleakedsqlliteobjects (). Detectleakedclosableobjects (). Penaltylog (). Penaltydeath (). build ());   4  }

This allows you to perform network operations in the main thread.

2. The general situation is that we should do this

Start a child thread to make your network request.

Of course, if your application executes a small amount of network request data, you can use the first scenario.

  

HTTP requests cannot be made in the main thread after resolving Android3.0

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.