Reproduced Android's networkonmainthreadexception anomaly

Source: Internet
Author: User

Look at the name should know, is the network request in Mainthread the exception that produces

http://blog.csdn.net/mad1989/article/details/25964495

Look at the name should know, is the network request in Mainthread the exception that produces

First look at the explanation of the official website:

Class Overview

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.

Also See StrictMode .

Http://developer.android.com/intl/zh-cn/reference/android/os/NetworkOnMainThreadException.html

To explain, from the Honeycomb SDK (3.0), Google no longer allows the network request (HTTP, Socket) and other related operations directly in the main thread class, in fact, should not do so, directly in the UI thread network operation, will block the UI, The user experience is quite bad! Even if Google doesn't forbid it, we wouldn't normally do it.

So, in other words, in the Honeycomb SDK (3.0) The following version, you can continue to do so in the main thread, at more than 3.0, it is not, it is recommended

1, and the network for more time-consuming operations into a sub-thread, and then use the handler message mechanism to communicate with the main thread.

[Java]View Plaincopy
  1. Public void OnCreate (Bundle savedinstancestate) {
  2. super.oncreate (savedinstancestate);
  3. This.setcontentview (r.layout.test);
  4. //Open a sub-thread for network operation, wait for return result, use handler to notify UI
  5. new Thread (Networktask). Start ();
  6. }
  7. Handler Handler = new Handler () {
  8. @Override
  9. public void Handlemessage (Message msg) {
  10. super.handlemessage (msg);
  11. Bundle data = Msg.getdata ();
  12. String val = data.getstring ("value");
  13. LOG.I ("MyLog", "request Result--" + val);
  14. //TODO
  15. //UI update and other related actions
  16. }
  17. };
  18. /**
  19. * Network operation related sub-threads
  20. */
  21. Runnable networktask = new Runnable () {
  22. @Override
  23. public Void Run () {
  24. //TODO
  25. //HTTP request is made here. Network requests related Operations
  26. Message msg = new Message ();
  27. Bundle data = new bundle ();
  28. Data.putstring ("value", "request result");
  29. Msg.setdata (data);
  30. Handler.sendmessage (msg);
  31. }
  32. };


2, using asynchronous mechanisms such as: Asynctask, this is a simple example of loading a network image

[Java]View Plaincopy
  1. Class Downimage extends Asynctask {
  2. private ImageView ImageView;
  3. Public downimage (ImageView ImageView) {
  4. This.imageview = ImageView;
  5. }
  6. @Override
  7. protected Bitmap doinbackground (String ... params) {
  8. String url = params[0];
  9. Bitmap Bitmap = null;
  10. try {
  11. //Load a network picture
  12. InputStream is = new URL (URL). OpenStream ();
  13. Bitmap = Bitmapfactory.decodestream (IS);
  14. } catch (Exception e) {
  15. E.printstacktrace ();
  16. }
  17. return bitmap;
  18. }
  19. @Override
  20. protected void OnPostExecute (Bitmap result) {
  21. Imageview.setimagebitmap (result);
  22. }
  23. }


3, directly in the main Thread of the network operation method, given online, I did not specifically test:

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

[Java]View Plaincopy
    1. Strictmode.setthreadpolicy (new StrictMode.ThreadPolicy.Builder ()
    2. . Detectdiskreads (). Detectdiskwrites (). Detectnetwork ()
    3. . Penaltylog (). build ());
    4. Strictmode.setvmpolicy (new StrictMode.VmPolicy.Builder ()
    5. . Detectleakedsqlliteobjects (). Detectleakedclosableobjects ()
    6. . Penaltylog (). Penaltydeath (). build ());



Keep in mind that if you declare a handler in the main thread, the handler post Runnable (thread) and the message processed are in the current Mian thread, not a child thread.

Reproduced Android's networkonmainthreadexception anomaly

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.