Android Exception Android.os.NetworkOnMainThreadException

Source: Internet
Author: User
<span id="Label3"></p>Recently in the implementation of an Android data acquisition sdk, collect users using data using HTTP to send to the cloud platform for data analysis. But in the send data times the following error:<br>caused by:android.os.NetworkOnMainThreadException<br><p><p>The reason for the cause, the official explanation:</p></p><p><p></p></p><pre name="code" class="html"><pre name="code" class="html">Class Overviewthe Exception That's thrown when an application attempts to perform a networking operation on its main thre Ad. 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.</pre></pre><p><p></p></p><p><p>Http://developer.android.com/intl/zh-cn/reference/android/os/NetworkOnMainThreadException.html<br></p></p><p><p> Above means that, starting from SDK3.0, Google no longer allows the network request (HTTP, Socket) and other related operations directly in the main thread, in fact, should not do so, directly in the UI thread network operation, blocking the ui, the user experience is not good. <br> that is, in the SDK3.0 of the following version, you can continue to do in the main line thread, at more than 3.0, will not be. so, in the following code, the three classes of thread, Runnable, handler are used: <br> </p></p><pre name="code" class="java"><pre name="code" class="java">public void OnCreate (Bundle Savedinstancestate) { super.oncreate (savedinstancestate); This.setcontentview (r.layout.test); Open a sub-thread for network operation, wait for the return result, and use handler to notify UI new thread (networktask). start (); Handler Handler = new Handler () { @Override public void Handlemessage (Message msg) { super.handlemessage ( msg); Bundle data = Msg.getdata (); String val = data.getstring ("value"); LOG.I ("mylog", "request result--" + val); UI updates and other related actions } }; /** * Network operation related sub-thread */ Runnable networktask = new Runnable () { @Override public void Run () { //http request is made Here. network requests related operations Mobeventservice.postonkillprocess (context); Message msg = new Message (); Bundle data = new Bundle (); Data.putstring ("value", "request result"); Msg.setdata (data); Handler.sendmessage (msg); } }; </pre></pre><p><p><br></p></p>The second, using asynchronous mechanisms such as: asynctask, This is a simple example of loading a network image:<p><p></p></p><pre name="code" class="java"><pre name="code" class="java">Class Downimage extends Asynctask { private ImageView ImageView; Public downimage (ImageView ImageView) { this.imageview = ImageView; } @Override protected Bitmap doinbackground (string ... params) { string url = params[0]; Bitmap Bitmap = null; Try { //load A network picture inputstream is = new URL (url). openstream (); Bitmap = Bitmapfactory.decodestream (is); } Catch (Exception e) { e.printstacktrace (); } return bitmap; } @Override protected void OnPostExecute (Bitmap Result) { imageview.setimagebitmap (result); } } </pre></pre><br>third, Direct neglect, Mandatory use (strongly not recommended, but simple to modify)<br>Under Setcontentview (r.layout.activity_main) of the mainactivity file, add the following code<br><pre name="code" class="java"><pre name="code" class="java">If (android.os.Build.VERSION.SDK_INT > 9) { strictmode.threadpolicy policy = new StrictMode.ThreadPolicy.Builder (). permitall (). build (); Strictmode.setthreadpolicy (policy);}</pre></pre>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 main thread, not a child thread.<p><p></p></p><p><p><br></p></p><p><p><br></p></p><p><p><br><br></p></p> <p style="font-size:12px;"><p style="font-size:12px;">Copyright Notice: This article for Bo Master original article, without Bo Master permission not Reproduced.</p></p> <p><p>Android Exception Android.os.NetworkOnMainThreadException</p></p></span>

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.