Android's networkonmainthreadexception anomaly

Source: Internet
Author: User

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.

     Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);  This. Setcontentview (R.layout.test); //Open a sub-thread for network operation, wait for return result, use handler to notify UI        NewThread (Networktask). Start (); } Handler Handler=NewHandler () {@Override Public voidhandlemessage (Message msg) {Super. Handlemessage (msg); Bundle Data=Msg.getdata (); String Val= Data.getstring ("Value"); LOG.I ("MyLog", "request result--" +val); //TODO//updates to the UI interface and other related actions        }    }; /*** Network operation related sub-threads*/Runnable Networktask=NewRunnable () {@Override Public voidrun () {//TODO//HTTP request is made here. Network requests related OperationsMessage msg =NewMessage (); Bundle Data=NewBundle (); Data.putstring ("Value", "Request Result");            Msg.setdata (data);        Handler.sendmessage (msg); }    };

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

classDownimageextendsAsynctask {PrivateImageView ImageView;  Publicdownimage (ImageView ImageView) { This. ImageView =ImageView; } @OverrideprotectedBitmap doinbackground (String ... params) {string URL= Params[0]; Bitmap Bitmap=NULL; Try {            //load a network pictureInputStream is =Newurl (url). OpenStream (); Bitmap=Bitmapfactory.decodestream (IS); } Catch(Exception e) {e.printstacktrace (); }        returnbitmap; } @Overrideprotected voidOnPostExecute (Bitmap result) {Imageview.setimagebitmap (result); }}

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:

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

From:never-say-never

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.