Android Development Notes

Source: Internet
Author: User

1, Exception: Android.os.NetworkOnMainThreadException

After android2.3, you must use another thread, such as the handler mechanism, or an asynchronous task to get network data in the main thread

If your access to the network must be performed in the main thread, add the following in OnCreate ():

 Public voidonCreate (Bundle savedinstancestate) {//See Strictmode documentationStrictmode.setthreadpolicy (NewStrictMode.ThreadPolicy.Builder (). Detectdiskreads (). Detectdiskwrites () . Detectnetwork ()//or. Detectall () for all detectable problems. Penaltylog (). build ()); Strictmode.setvmpolicy (NewStrictMode.VmPolicy.Builder (). Detectleakedsqlliteobjects (). Detectleakedclosableobject                S (). Penaltylog (). Penaltydeath (). build ()); Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.main); InitDialog ();}

This allows the network operation to be performed in the main thread in the high version, or the thread can be restarted to perform network operations:

 Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);  This. Setcontentview (R.layout.share_mblog_view); NewThread (runnable). 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); }} Runnable Runnable=NewRunnable () {@Override Public voidrun () {//        //todo:http request. //Message msg =NewMessage (); Bundle Data=NewBundle (); Data.putstring ("Value", "Request Result");        Msg.setdata (data);    Handler.sendmessage (msg); }}

Extensions: Handler mainly accepts the data sent by the child thread, and uses this data to update the UI with the main thread, reference http://www.pin5i.com/showtopic-android-handler.html

Multithreading reference : http://www.cnblogs.com/ccdc/p/3836966.html

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.