Android. OS. NetworkOnMainThreadException, androidexception
Android 4.1 project: Share with Sina Weibo:
Android. OS. NetworkOnMainThreadException
After searching on the internet, you will know that this error is caused by version issues. If you execute an Http request in the main thread after 4.0, you may be afraid that the program will be suspended due to a long time of the Http request. Therefore, our online friends have also provided corresponding solutions, which are called policy-based countermeasures:
I. Add the following code to the onCreate function in the Activity that initiates an Http request:
// For details, see StrictMode. setThreadPolicy (new StrictMode. threadPolicy. builder (). detectDiskReads (). detectDiskWrites (). detectNetwork (). penaltyLog (). build (); StrictMode. setVmPolicy (new StrictMode. vmPolicy. builder (). detectLeakedSqlLiteObjects (). detectLeakedClosableObjects (). penaltyLog (). penaltyDeath (). build ());
If the project you are working on is not Android 4.0, you cannot see the StrictMode class. I also used com_weibo_android.jar from the Internet. However, when downloading this jar package is 2.3, you must first convert it to an Android 4.0 Project, and then add the following two lines of code to the onCreate () function of the corresponding external activity. In this way, this error will not be reported.
Ii. Use the Thread, Runnable, and Handler classes:
Public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); this. setContentView (R. layout. performance_mblog_view); new Thread (runnable ). 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", "The request result is -->" + val) ;}} Runnable runnable = new Runnable () {@ Override public void run () {// TODO: http request. // Message msg = new Message (); Bundle data = new Bundle (); data. putString ("value", "request result"); msg. setData (data); handler. sendMessage (msg );}}