Caused by: android.os.networkonmainthreadexception error resolution

After not writing Android code for a long time, I found that the program I wrote before could not run, and there was no special error prompt. I saw a useful error caused by: android.os.networkonmainthreadexception. After checking the reason, this error will be reported when executing HTTP requests in the main thread after 4.0, I'm probably afraid that the HTTP request takes too long to cause the program to fake death.

There are two solutions, namely:

The first method: ignore it directly and force it to be used (it is strongly not recommended, but the modification is simple). Add the following code under setcontentview (r.layout. Activity_main) of mainactivity file

The second method: use thread, runnable and handler (recommended) to make HTTP requests in runnable without blocking the UI thread ~

Attachment: another solution

Android 4.1 project: use Sina Weibo sharing times: android.os.networkonmainthreadexception. After online search, you know that it is because of the version problem. After 4.0, this error will be reported when executing HTTP requests in the main thread. Maybe it is because you are afraid that the HTTP request takes too long to cause the false death of the program. Then, online friends have also given corresponding solutions, which are called "there are policies on the top and Countermeasures under the bottom": first, add the following code to the oncreate function in the activity that initiates the HTTP request:

If the project you are working on is not Android 4.0, you can't see the strictmode class. I also use the online com_ weibo_ android.jar。 However, when the jar package is downloaded, it is 2.3. First convert it into an Android 4.0 project, and then add the above two lines of code to the oncreate() function of the corresponding shareactivity. So you won't report this error.

2: Use three classes: thread, runnable and handler:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>