For Android, "NetworkOnMainThreadException" and networkonmainthread

Source: Internet
Author: User

For Android, "NetworkOnMainThreadException" and networkonmainthread

The reasons for network collection are as follows and solutions:

I would like to add a summary:

Solution 1:
Add the following code to the protected void onCreate (Bundle savedInstanceState) function of the activity that operates the Network Class (socket connection. Add it before super. onCreate (savedInstanceState.

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()                .detectDiskReads().detectDiskWrites().detectNetwork()                .penaltyLog().build());        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()                .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()                .penaltyLog().penaltyDeath().build());

This method is not recommended. But it is also one of the solutions.

Solution 2:
Start a new thread. This is the method shown in the figure above.

New Thread () {@ Override public void run () {// code for network operation connection mClientManage. Connect () ;}}. start ();

 

Related Article

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.