Android.os.NetworkOnMainThreadException Exception Handling

Source: Internet
Author: User

When I try to connect to the network on the UI thread (mainactivity), the runtime throws an exception droid.os.NetworkOnMainThreadException

The official Android document says

The exception is thrown when an application attempts to perform a networking operation on its main thread.

This is a thrown for applications targeting the honeycomb SDK or higher. Applications targeting earlier SDK versions is allowed to does networking on their main event loop threads, but it's heavil Y discouraged. See the document designing for responsiveness.

Based on the consideration of reducing the time-consuming operation of the UI thread, Android over 3.0 no longer allows network connectivity on the UI thread.

Workaround

1. Use strict Mode to force the connection to the UI thread (not recommended by the official)

2. Open a thread for the network connection, and then use handler to pass the result to the UI thread.

Android.os.NetworkOnMainThreadException Exception Handling

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.