A. networkonmainthreadexception exception occurs when accessing the network in a later version of Android.

Source: Internet
Author: User

I. Problems

Before Android 2.3, we had no problem performing network operations in mainthread. However, after Android 2.3 (that is, 3.0, etc.), A. networkonmainthreadexception occurs. For example, if we want to display a network image and use the csdn logo as an example, we can write as follows:

 

package com.example.netimageviewer;import java.io.IOException;import com.example.netimageviewer.service.ImageUtil;import android.os.Bundle;import android.os.StrictMode;import android.app.Activity;import android.graphics.Bitmap;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.ImageView;import android.widget.Toast;public class MainActivity extends Activity {private Button button;private ImageView imageView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);     button = (Button) findViewById(R.id.button);imageView = (ImageView) findViewById(R.id.img);button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {                              });}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main, menu);return true;}}

Tool class for retrieving images:

 

 

package com.example.netimageviewer.service;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;import com.example.netimageviewer.util.StreamUtil;import android.graphics.Bitmap;import android.graphics.BitmapFactory;public class ImageUtil {public static Bitmap getImage(String addressUrl) throws IOException {URL url = new URL(addressUrl);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(5000);InputStream is = conn.getInputStream();byte[] b = StreamUtil.getByte(is);Bitmap bf = BitmapFactory.decodeByteArray(b, 0, b.length);return bf;}}

Convert inputstream into a tool class of byte:

 

 

package com.example.netimageviewer.util;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;public class StreamUtil {public static byte[] getByte(InputStream is) throws IOException{ByteArrayOutputStream stream = new ByteArrayOutputStream();byte[] b = new byte[1024];int len = 0;while ((len = is.read(b)) != -1) {stream.write(b, 0, len);}is.close();byte[] byteStream=stream.toByteArray();System.out.println(byteStream.toString());return byteStream;}}

Then add the network access permission: <uses-Permission Android: Name = "android. permission. internet "/>, and finally run the program. If the image is displayed before Version 2.3, it will appear after Version 2.3. networkonmainthreadexception exception.

 

Ii. solution:

1. Add the following code to the oncreate () method of the main thread:

 

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());

Note:
After reading the relevant information, we found that the system has added a class: strictmode since Android 2.3. This class changes the way the network is accessed. Android official documentation provides the purpose of this class setting: strictmode is a development tool provided by the system to detect potential system problems caused by accidental accidents during development, then, the developer is prompted to fix the vulnerability. Strictmode is usually used to capture problems arising from interactions between disk access or network access and the main process, because in the main process, UI operations and the execution of some actions are most often used, conflicts may occur between them. Detaching disk access and network access from the main thread can make disk or network access smoother and improve response and user experience.

 

Obviously, most beginners choose to put the code that accesses the network directly into the main process during network development. Because it is in conflict with the primary task of the main process-UI interaction, A certain detection mechanism must be set up to ensure smooth system operation and detect all exceptions. When using this code, you only need to put this code in oncreate of the entry activity that runs your project, so the entire project program is useful. You do not need to add each activity.

However, we can know from the usage of the strictmode class that this is not a good method.
2. A safe method is to use asynctask. This class is believed to be no stranger. Then the code can be written as follows:

 

package com.example.netimageviewer.util;import java.io.InputStream;import java.net.URL;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.AsyncTask;import android.widget.ImageView;public class DownImage extends AsyncTask<String, Void, Bitmap> {private ImageView imageView;public DownImage(ImageView imageView) {this.imageView = imageView;}@Overrideprotected Bitmap doInBackground(String... params) {String url = params[0];Bitmap bitmap = null;try {InputStream is = new URL(url).openStream();bitmap = BitmapFactory.decodeStream(is);} catch (Exception e) {e.printStackTrace();}return bitmap;}@Overrideprotected void onPostExecute(Bitmap result) {super.onPostExecute(result);imageView.setImageBitmap(result);}}

The mainactivity code should be like this:

 

 

package com.example.netimageviewer;import java.io.IOException;import com.example.netimageviewer.util.DownImage;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import com.android.internal.util.*;import android.widget.ImageView;public class MainActivity extends Activity {private Button button;private ImageView imageView;private String uriCSDN = "http://csdnimg.cn/www/images/csdnindex_logo.gif?20121229";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button = (Button) this.findViewById(R.id.button);imageView = (ImageView) this.findViewById(R.id.img);button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {new DownImage(imageView).execute(uriCSDN);}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main, menu);return true;}}

In addition, some friends suggest using thread, handler, runnable and so on. Of course, this is also possible, with flexible thinking and many methods.

 

 

Related Article

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.