About android.os.networkonmainthreadexception in Android development

First of all, let's be clear that this error is not a code error.

After android2.3, direct access to the network is prohibited in the main thread, and another thread such as a handler mechanism must be used, or an asynchronous task can be used to obtain network data. Two solutions are given below.
1. If you want to access the network directly in the main thread, please use the first method, which is simple and violent, but not recommended.
We just need to add this piece of code after setContentView(R.layout.activity_main); in the onCreate method:
if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy. Builder().permitAll().build();           

    StrictMode.setThreadPolicy(policy);       

}

2. Since we cannot connect to the network in the main thread, we will create a new thread to operate network data. This method is recommended.
new Thread(){
@Override
public void run(){
//Put the code to be connected here
}
}.start();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326389694&siteId=291194637