Android's NetworkOnMainThreadException exception

You should know by looking at the name that it is an exception generated by a network request in MainThread

 

Let's take a look at the official website's explanation:

 

Class Overview

 

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness.

Also see StrictMode.

http://developer.android.com/intl/zh-cn/reference/android/os/NetworkOnMainThreadException.html

 

Explain, starting from Honeycomb SDK (3.0), google no longer allows network requests (HTTP, Socket) and other related operations to be directly in the Main Thread class. In fact, it should not be done in the first place. Performing network operations directly on the UI thread will block UI and user experience are pretty bad! Even if Google doesn't ban it, we won't do it under normal circumstances~

So, that is to say, in versions below Honeycomb SDK (3.0), you can continue to do this in the Main Thread, but in versions above 3.0, it will not work, it is recommended

 

1. The time-consuming operations related to the network are placed in a sub-thread, and then the Handler message mechanism is used to communicate with the main thread.

 

[java]  view plain copy  
 
  View code snippets on CODE Derive to my code slice
  1. publicvoid onCreate(Bundle savedInstanceState) {   
  2.     super .onCreate (savedInstanceState);  
  3.     this.setContentView(R.layout.test);  
  4.     // Open a sub thread, perform network operations, wait for a return result, and use the handler to notify the UI  
  5.     new Thread(networkTask).start();  
  6. }  
  7.   
  8. Handler handler =  new  Handler () {  
  9.     @Override  
  10.     publicvoid handleMessage(Message msg) {   
  11.         super.handleMessage(msg);  
  12.         Bundle data = msg.getData();  
  13.         String val = data.getString("value");  
  14.         Log.i( "mylog" "The request result is -->"  + val);  
  15.         // EVERYTHING  
  16.         // UI interface update and other related operations  
  17.     }  
  18. };  
  19.   
  20. /** 
  21.  * Sub-threads related to network operations 
  22.  */  
  23. Runnable networkTask = new Runnable() {  
  24.   
  25.     @Override  
  26.     publicvoid run() {   
  27.         // EVERYTHING  
  28.         // Perform http request. Network request related operations here  
  29.         Message msg = new Message();  
  30.         Bundle data = new Bundle();  
  31.         data.putString( "value" ​​"request result" );  
  32.         msg.setData(data);  
  33.         handler.sendMessage(msg);  
  34.     }  
  35. };  


2. Use asynchronous mechanisms such as: asynctask, this is a simple example of loading network pictures

 

 

[java]  view plain copy  
 
  View code snippets on CODE Derive to my code slice
  1. class DownImage extends AsyncTask {  
  2.   
  3.     private ImageView imageView;  
  4.   
  5.     public DownImage(ImageView imageView) {  
  6.         this.imageView = imageView;  
  7.     }  
  8.   
  9.     @Override  
  10.     protected Bitmap doInBackground(String... params) {  
  11.         String url = params[0];  
  12.         Bitmap bitmap = null;  
  13.         try {  
  14.             //加载一个网络图片  
  15.             InputStream is = new URL(url).openStream();  
  16.             bitmap = BitmapFactory.decodeStream(is);  
  17.         } catch (Exception e) {  
  18.             e.printStackTrace();  
  19.         }  
  20.         return bitmap;  
  21.     }  
  22.   
  23.     @Override  
  24.     protected void onPostExecute(Bitmap result) {  
  25.         imageView.setImageBitmap(result);  
  26.     }  
  27. }  


3,直接在main Thread 进行网络操作的方法,网上给出的,我没有具体测试:

 

在发起Http请求的Activity里面的onCreate函数里面添加如下代码:

 

[java]  view plain copy  
 
  View code snippets on CODE Derive to my code slice
  1. StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()  
  2.         .detectDiskReads().detectDiskWrites().detectNetwork()  
  3.         .penaltyLog().build());  
  4. StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()  
  5.         .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()  
  6.         .penaltyLog().penaltyDeath().build());  



 

Remember, if a handler is declared in the Main Thread, the Runnable (Thread) posted by this handler and the processed message are all in the current mian thread, not a child thread.

Guess you like

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